Общие сведения о компоненте создания образов Windows
Компонент Windows Imaging Component (WIC) предоставляет расширяемую платформу для работы с изображениями и метаданными изображений. WIC позволяет независимым поставщикам программного обеспечения и независимым поставщикам оборудования (IHV) разрабатывать собственные кодеки изображений и поддерживать ту же самую платформу, что и стандартные форматы изображений (например, TIFF, JPEG, PNG, GIF, BMP и Хдфото). Один последовательный набор интерфейсов используется для обработки изображений независимо от формата изображения, поэтому любое приложение, использующее WIC, получает автоматическую поддержку новых форматов изображений сразу после установки кодека. Расширяемая платформа метаданных позволяет приложениям считывать и записывать собственные конфиденциальные метаданные непосредственно в файлы изображений, поэтому метаданные никогда не теряются или не отделяются от изображения.
Этот раздел включает следующие подразделы:
Компоненты компонента работы с образами Windows
Основные возможности WIC:
- Позволяет разработчикам приложений выполнять операции обработки изображений в любом формате изображения через единый последовательный набор общих интерфейсов, не требуя перед этим знания о конкретных форматах изображений.
- Предоставляет расширяемую архитектуру «Plug and Play» для кодеков изображений, форматов пикселей и метаданных с автоматическим обнаружением новых форматов во время выполнения.
- Поддерживает чтение и запись произвольных метаданных в файлах изображений с возможностью сохранять нераспознанные метаданные во время редактирования.
- Сохраняет данные изображений с высоким уровнем глубины, до 32 бит на канал в течение всего конвейера обработки изображений.
- Предоставляет встроенную поддержку для большинства популярных форматов изображений, форматов пикселей и схем метаданных.
Компонент WIC включает несколько встроенных кодеков. С платформой поставляются следующие стандартные кодеки.
Windows Imaging Component Overview
The Windows Imaging Component (WIC) provides an extensible framework for working with images and image metadata. WIC makes it possible for independent software vendors (ISVs) and independent hardware vendors (IHVs) to develop their own image codecs and get the same platform support as standard image formats (for example, TIFF, JPEG, PNG, GIF, BMP, and HDPhoto). A single, consistent set of interfaces is used for all image processing, regardless of image format, so any application using the WIC gets automatic support for new image formats as soon as the codec is installed. The extensible metadata framework makes it possible for applications to read and write their own proprietary metadata directly to image files, so the metadata never gets lost or separated from the image.
This topic includes the following sections.
Windows Imaging Component Features
The primary features of WIC are:
- Enables application developers to perform image processing operations on any image format through a single, consistent set of common interfaces, without requiring prior knowledge of specific image formats.
- Provides an extensible «plug and play» architecture for image codecs, pixel formats, and metadata, with automatic run-time discovery of new formats.
- Supports reading and writing of arbitrary metadata in image files, with the ability to preserve unrecognized metadata during editing.
- Preserves high bit depth image data, up to 32 bits per channel, throughout the image processing pipeline.
- Provides built-in support for most popular image formats, pixel formats, and metadata schemas.
WIC includes several built-in codecs. The following standard codecs are provided with the platform.
How the Windows Imaging Component Works
This topic contains the following sections:
Discovery and Arbitration
Before an image can be decoded, an appropriate codec must be found that can decode that image format. In most systems, because the supported image formats are hard-coded, no discovery process is required. Because the Windows Imaging Component (WIC) platform is extensible, itвЂ™s necessary to be able to identify the format of an image and match it with an appropriate codec.
To support run-time discovery, each image format must have an identifying pattern that can be used to identify the appropriate decoder for that format. (It is strongly recommended that, for new file formats, you use a GUID for the identifying pattern, because it is guaranteed to be unique.) The identifying pattern must be embedded in each image file that conforms to that image format. Each decoder has a registry entry that specifies the identifying pattern or patterns of the image formats it can decode. When an application needs to open an image, it requests a decoder from WIC. WIC looks up the available decoders in the registry, and checks each registry entry for an identifying pattern that matches the pattern embedded in the image file. For more information on decoder registry entries, see Encoder-Specific Registry Entries
When WIC finds a single decoder that matches the identifying pattern in the image, it creates an instance of the decoder and passes the image file to it. If WIC finds more than one match, it invokes a method called QueryCapability on each matching decoder to arbitrate among them and find the best match. For more information, see the QueryCapabilities section in the Implementing IWICBitmapDecoder.
After the appropriate decoder has been selected and instantiated, the application talks directly to the decoder. The decoder has several responsibilities, which it implements through various interfaces. These services can be classified as:
- Container-level services
- Frame-level services
- Metadata enumeration services
- Native decoder transforms
- Progress notifications and cancellation support
- Raw processing services
Container-level services include retrieving the top-level thumbnail (if supported), preview, color contexts, palette (if applicable), and container format, as well as providing access to the individual image frames within the container. (Some containers contain only a single frame while others, such as Tagged Image File Format (TIFF), can contain multiple frames.) This set of services also includes providing information about the decoder itself, and its capabilities with respect to a specific image file.
Individual frames have their own thumbnails, and may also have their own color contexts, palettes, and other properties, which are exposed at the frame level. The most important operation performed at the frame level, though, is the actual decoding of the image bits for that frame.
WIC provides metadata readers for the most common metadata formats (IFD, EXIF, IPTC, XMP, APP0, APP1, and other formats), and also supports extensibility for third-party metadata formats. This frees the codec of the responsibility for parsing metadata. However, the codec is responsible for enumerating the metadata blocks and requesting a metadata reader for each block. WIC performs discovery for metadata handlers the same way it does for codecs, based on a pattern in the block header matching a pattern in the metadata handlerвЂ™s registry entry. For more information, see the Encoder-Specific Registry Entries
Decoders are not required to natively support transform operations, but doing so enables significant performance optimizations that provide a better end-user experience. For example, an application can create a pipeline of various transforms (scaling, cropping, rotation, and pixel format conversion) to perform on an image before the image is rendered. For more information on transform pipelines, see IWICBitmapSource. After creating a transform pipeline, the application requests the final transform in the pipeline to produce the bitmap that results from applying all the transforms to the image source. At that point, if the decoder itself is able to perform transform operations, WIC asks which of the requested transforms it can perform. Any requested transforms the decoder cannot perform will be performed by WIC on the decoded image before returning it to the caller. This optimized transform pipeline provides better performance than performing each transform sequentially in memory, particularly when some or all of the transforms can be accomplished during the decoding process.
Progress notifications and cancellation support enable an application to request progress notifications for lengthy operations, and also enable the application to give the user an opportunity to cancel an operation that is taking too long. This is important because if a user cannot cancel an operation, he or she may feel the process has hung, and try to cancel it by closing the application.
These interfaces are described in detail in the section on Implementing a WIC-Enabled Decoder.
Raw processing services include adjusting camera settings, such as exposure, contrast, and sharpening, or changing the color space before processing the raw bits.
Like decoders, encoders have responsibilities that they implement through interfaces. The services that encoders provide are complementary to the services provided by decoders, except they write out image data rather than reading it. Encoders also provide services in the following categories:
- Container-level services
- Frame-level services
- Metadata enumeration and update services
- Progress notification and cancellation support
Container-level services for an encoder include setting the top-level thumbnail (if supported), preview, and palette (if applicable), and iterating through the individual image frames so they can be serialized into the container.
Frame-level services for an encoder mirror those for the decoder, except that they write out the image data, thumbnail, and any associated palette or other component, rather than reading them.
Also, metadata enumeration services for an encoder include iterating through the metadata blocks to be written, and invoking the appropriate metadata writers to serialize the metadata to disk.
These interfaces are described in detail in the section on Implementing a WIC-Enabled Encoder.
The Lifetime of a Codec
A WIC codec is instantiated to handle a single image, and usually has a short lifetime. ItвЂ™s created when an image is loaded and is released when the image is closed. An application may use a large number of codecs simultaneously with overlapping lifetimes (think of scrolling through a directory containing hundreds of images), and multiple applications may be doing this at the same time.
Although some codecs have a lifetime that is scoped to the lifetime of the process in which they live, this is not the case with WIC codecs. The WindowsВ Vista Photo Gallery, Windows Explorer, and Photo Viewer, as well as numerous other applications, are built on WIC and will be using your codec to display images and thumbnails. If the lifetime of your codec were scoped to the lifetime of the process, every time an image or thumbnail was displayed in the WindowsВ Vista Explorer, the codec instantiated to decode that image would remain in memory until the next time the user restarted his or her computer. If your codec is never unloaded, its resources are, in effect, «leaked» because they can’t be used by any other component in the system.
How to WIC-enabled a Codec
- Implement a container-level decoder class and a frame-level decoder class that exposes the required WIC interfaces for decoding images and iterating through blocks of metadata. This enables all WIC-based applications to interact with your codec the same way they interact with standard image formats.
- Implement a container-level encoder class and a frame-level encoder class that exposes the required WIC interfaces for encoding images and serializing blocks of metadata into an image file.
- If your container format is not based on a TIFF or JPEG container, you may need to write metadata handlers for the common metadata formats (EXIF, XMP). However, if you use a TIFF-based or JPEG-based container format, this is not necessary because you can delegate to the system-provided metadata handlers.
- Embed a unique identifying pattern (we recommend a GUID) in all your image files. This enables your image format to be matched against your codec during the discovery. If you are writing a WIC wrapper for an existing image format, you must find a pattern of bits that the encoder always writes into its image files thatвЂ™s unique to that image format, and use this as the identifying pattern.)
- Register your codec at installation time. This enables your codec to be discovered at run time by matching the identifying pattern in the registry with the pattern embedded in the image file.
- As of WindowsВ 7, WIC requires that codecs be of COM apartment type «Both». This means that you must do the appropriate locking to handle cross-apartment callers and callers in multi-threaded scenarios. For more information, see the next section on multi-threaded apartment support.
- Support for 64-bit platforms: For WindowsВ 7, WIC will require that third-party WIC codecs be delivered as both 32-bit and 64-bit native binaries. Further, the 32-bit form must install and run on 64-bit systems, and the third party WindowsВ 7 codec installer must install both the 32-bit and 64-bit binaries on 64-bit systems.
Multi-Threaded Apartment Support in WIC
Objects within a Multi-Threaded Apartment (MTA) may be called concurrently by any number of threads within the MTA. This allows for better performance on multi-core systems and certain server scenarios. In addition, WIC codecs in an MTA can call other objects in the MTA without the marshalling cost associated with calling between threads in different STA apartments. In WindowsВ 7, all in-box WIC codecs have been updated to support MTAs, including JPEG, TIFF, PNG, GIF, ICO, and BMP. It is highly recommended that third-party codecs be written to support MTAs. Third-party codecs that do not to support MTAs cause significant performance costs in multi-threaded applications because of marshaling. Enabling MTA support requires proper synchronization to be implemented in the third-party codec. Exact implementation of these synchronization techniques is beyond the scope of this paper. For more information on synchronizing COM objects, see Understanding and Using COM Threading Models.
WIC API Overview
The Windows Imaging Component (WIC) provides a Component Object Model (COM) based API for use in C and C++. The WIC API exposes a variety of image-related functionality, including:
- Built-in codecs for the standard web image formats.
- Built-in support for standard metadata formats.
- Wide range of pixel format support.
- High-color support; including 30-bit extended range, 30-bit high precision, and 48-bit high precision and wide gamut pixel formats.
- Extensible framework for image codecs, pixel formats, and metadata formats.
This topic contains the following topics.
WIC Header Files
The WIC APIs are defined in the following header and Interface Definition Language (IDL) files:
|wincodec.h||Defines C and C++ versions of the primary WIC APIs.|
|wincodec.idl||Defines the primary WIC interfaces.|
|wincodecsdk.h||Defines C and C++ versions of the metadata WIC APIs.|
|wincodecsdk.idl||Defines the WIC metadata interfaces.|
|wincodec_proxy.h||Defines the WIC proxy exports.|
To use WIC, your applications must include wincodec.h and/or wincodecsdk.h, depending on the API your application needs.
The WIC library files:
|windowscodecs.lib||Import library provided by the Windows Software Development Kit (SDK).|
|windowscodecs.dll||Stock implementation library provided by the operating system.|
To link to WIC APIs, your application must include windowscodec.lib as an additional linker dependency.
The following table describes the two COM class factories the WIC APIs provide for creating WIC components.
|IWICImagingFactory||Primary class factory for application development using WIC components. This factory creates components such as image decoders, encoders and streams.|
|IWICComponentFactory||Class factory targeted for WIC component developers. Components created from this factory are primarily used in codec and metadata handler development.|
To create either class factory, use the CoCreateInstance COM function. The following example demonstrates the creation of the WIC imaging factory.
The WIC APIs provide several types of imaging components. The following table describes some of the common WIC components. For a full list of available components, see WIC interfaces.