description | ms.assetid | title | ms.topic | ms.date |
---|---|---|---|---|
This topic demonstrates how to modify the pixels of a bitmap source using the IWICBitmap and IWICBitmapLock components. |
a08af015-bc42-4a31-af03-106714b08d08 |
How to Modify the Pixels of a Bitmap Source |
article |
05/31/2018 |
This topic demonstrates how to modify the pixels of a bitmap source using the IWICBitmap and IWICBitmapLock components.
To modify the pixels of a bitmap source
-
Create an IWICImagingFactory object to create Windows Imaging Component (WIC) objects.
// Create WIC factory hr = CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pIWICFactory) );
-
Use the CreateDecoderFromFilename method to create an IWICBitmapDecoder from an image file.
HRESULT hr = S_OK; IWICBitmapDecoder *pIDecoder = NULL; IWICBitmapFrameDecode *pIDecoderFrame = NULL; hr = m_pIWICFactory->CreateDecoderFromFilename( L"turtle.jpg", // Image to be decoded NULL, // Do not prefer a particular vendor GENERIC_READ, // Desired read access to the file WICDecodeMetadataCacheOnDemand, // Cache metadata when needed &pIDecoder // Pointer to the decoder );
-
Get the first IWICBitmapFrameDecode of the image.
// Retrieve the first bitmap frame. if (SUCCEEDED(hr)) { hr = pIDecoder->GetFrame(0, &pIDecoderFrame); }
The JPEG file format only supports a single frame. Because the file in this example is a JPEG file, the first frame (
0
) is used. For image formats that have multiple frames, see How to Retrieve the Frames of an Image for accessing each frame of the image. -
Create an IWICBitmap from the previously obtained image frame.
IWICBitmap *pIBitmap = NULL; IWICBitmapLock *pILock = NULL; UINT uiWidth = 10; UINT uiHeight = 10; WICRect rcLock = { 0, 0, uiWidth, uiHeight }; // Create the bitmap from the image frame. if (SUCCEEDED(hr)) { hr = m_pIWICFactory->CreateBitmapFromSource( pIDecoderFrame, // Create a bitmap from the image frame WICBitmapCacheOnDemand, // Cache bitmap pixels on first access &pIBitmap); // Pointer to the bitmap }
-
Obtain an IWICBitmapLock for a specified rectangle of the IWICBitmap.
if (SUCCEEDED(hr)) { // Obtain a bitmap lock for exclusive write. // The lock is for a 10x10 rectangle starting at the top left of the // bitmap. hr = pIBitmap->Lock(&rcLock, WICBitmapLockWrite, &pILock);
-
Process the pixel data that is now locked by the IWICBitmapLock object.
if (SUCCEEDED(hr)) { UINT cbBufferSize = 0; BYTE *pv = NULL; // Retrieve a pointer to the pixel data. if (SUCCEEDED(hr)) { hr = pILock->GetDataPointer(&cbBufferSize, &pv); } // Pixel manipulation using the image data pointer pv. // ... // Release the bitmap lock. SafeRelease(&pILock); } }
To unlock the IWICBitmap, call IUnknown::Release on all IWICBitmapLock objects associated with the IWICBitmap.
-
Clean up created objects.
SafeRelease(&pIBitmap); SafeRelease(&pIDecoder); SafeRelease(&pIDecoderFrame);