得到UIImage很简单,但是怎么把UIImage数据转换为位图形式?这样我可以得到任意一个给定像素的信息。谢谢了!


2个回答

#define RGBA                4
#define RGBA_8_BIT          8

size_t                  bytesPerRow;
size_t                  byteCount;
size_t                  pixelCount;

CGContextRef            context;
CGColorSpaceRef         colorSpace;

UInt8*                  pixelByteData;

RPVW_RGBAPixel*             pixelData;

typedef struct RGBAPixel{
    byte    red;
    byte    green;
    byte    blue;
    byte    alpha;
}RGBAPixel;

- (RGBAPixel*)  bitmap{
    NSLog( @"Returning bitmap representation of UIImage." );

    [self   setBytesPerRow:     self.size.width * RGBA];
    [self   setByteCount:       bytesPerRow     * self.size.height];
    [self   setPixelCount:      self.size.width * self.size.height];
    [self   setColorSpace:  CGColorSpaceCreateDeviceRGB()];

    if ( ! colorSpace ) {
        NSLog( @"Error allocating color space." );
        return nil;
    }

    [self   setPixelData:   malloc( byteCount )];

    if ( ! pixelData )  {
        NSLog( @"Error allocating bitmap memory. Releasing color space." );
        CGColorSpaceRelease( colorSpace );
        return nil;
    }

typedef unsigned char byte;

typedef struct RGBPixel {
byte    red;
byte    green;
byte    blue;
}   RGBPixel;

CFDataRef       bitmapData; 
UInt8*          pixelByteData;
RGBPixel*           pixelData;

[self   setBitmapData:  CGDataProviderCopyData( CGImageGetDataProvider( [self   CGImage] ) )];

[self   setPixelBitData:    malloc( CFDataGetLength( bitmapData ) )];

CFDataGetBytes( bitmapData, CFRangeMake( 0, CFDataGetLength( bitmapData ) ), pixelByteData );

pixelData   = (RGBPixel*) pixelByteData;

NSLog( @"Pixel data one red (%i), green (%i), blue (%i).", pixelData[0].red, pixelData[0].green, pixelData[0].blue );

return pixelData;

- (RGBPixel*)   pixelDataForRow:    (int)   row
        column:         (int)   column  {

    return &pixelData[ row * column ];      
}