typedef unsigned char byte;
typedef struct RGBPixel
{
byte red;
byte green;
byte blue;
} RGBPixel;
typedef struct RGBAPixel
{
byte red;
byte green;
byte blue;
byte alpha;
} RGBAPixel;
@interface UIImage(XXX)
- (RGBPixel*)bitmapFromBMP;
- (RGBAPixel*)bitmapFromPNG;
@end
xxx.m
#define RGBA 4
#define RGBA_8_BIT 8
@implementation UIImage(XXX)
- (RGBPixel*)bitmapFromBMP
{
CFDataRef bitmapData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage));
UInt8* pixelByteData = malloc(CFDataGetLength(bitmapData));
if (!pixelByteData)
return nil;
CFDataGetBytes(bitmapData, CFRangeMake(0, CFDataGetLength(bitmapData)), pixelByteData);
return (RGBPixel*)pixelByteData;
}
- (RGBAPixel*)bitmapFromPNG
{
size_t bytesPerRow = self.size.width * RGBA;
size_t byteCount = bytesPerRow * self.size.height;
CGContextRef context = 0;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
UInt8* pixelByteData = malloc(byteCount);
RGBAPixel* pixelData = nil;
if (!colorSpace)
{
return nil;
}
if (!pixelByteData)
{
CGColorSpaceRelease( colorSpace );
return nil;
}
context = CGBitmapContextCreate((void*) pixelByteData,
self.size.width,
self.size.height,
RGBA_8_BIT,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
if (!context)
{
free( pixelByteData );
CGColorSpaceRelease( colorSpace );
return nil;
}
CGRect rect = { { 0 , 0 }, { self.size.width, self.size.height } };
CGContextDrawImage( context, rect, self.CGImage );
pixelData = (RGBAPixel*) CGBitmapContextGetData(context);
return pixelData;
}
@end
沒有留言:
張貼留言