object-C 2011/02/01 00:49

CGImage 에서 픽셀 데이터를 얻는 방법 (Technical Q&A QA1509)

Technical Q&A QA1509

Getting the pixel data from a CGImage object

Q: How do I access the pixel data of a CGImage object?

A: On Mac OS X 10.5 or later, a new call has been added that allows you to obtain the actual pixel data from a CGImage object. This call, CGDataProviderCopyData, returns a CFData object that contains the pixel data from the image in question. An example of using this call to obtain pixel data from a CGImage is shown in Listing 1. Once you have the CFData object with your pixel information, you can call CFDataGetBytePtr to get a pointer to the pixel data, or CFDataGetBytes to copy a subrange of pixel data.

Listing 1: Getting raw pixel data from a CGImage.


Note: CopyImagePixels as written will return NULL if the passed in CGImage object is NULL or if the contents of the image are too large to fit in memory.

WARNING: The pixel data returned by CGDataProviderCopyData has not been color matched and is in the format that the image is in, as described by the various CGImageGet functions (see for Getting Information About an Image more information). If you want the image in a different format, or color matched to a specific color space, then you should draw the image to a bitmap context as described later in this Q&A, with the caveat that alpha information from the image will be multiplied into the color components.

Prior to Mac OS X 10.5 an image's pixels are not as readily available. The only way to guarantee access to the equivalent bits is to create a bitmap context with a memory buffer you specify and then draw the CGImage to the context using CGContextDrawImage. After drawing the CGImage to the context you will have a copy of the data in the buffer you specified (which can also be easily accessed using the CGBitmapContexGetData function). The code in Listing 2 demonstrates how to do this.

IMPORTANT: Listing 2 creates a bitmap context with a 8-bits per component ARGB color space, draws the source image to this context, then retrieves the image bits in this color space from the context. Regardless of what the source image format is (CMYK, 24-bit RGB, Grayscale, and so on) it will be converted over to this color space.

For more information about creating bitmap contexts for other pixel formats, see the Quartz 2D Programming Guide.

Listing 2: Accessing the pixel data of a CGImage.


저작자 표시 비영리 동일 조건 변경 허락