我正在尝试将像素动态插入到PNG图像文件中,并尝试将其检索回来,而不对使用下面的代码保存的像素进行任何更改。但我没有成功这样做。有人可以帮我指出问题所在吗?感谢。
// Original pixels for debugging only
NSString *sPixels = @"12345678";
const char *cpPixels8 = sPixels.UTF8String;
char *cpPixelsStore = calloc(sPixels.length + 1, 1);
strncpy(cpPixelsStore, cpPixels8, sPixels.length);
unsigned int r,g,b,a;
for(int j = 0; j < sPixels.length; j += 4)
{
r = cpPixelsStore[j+0];
g = cpPixelsStore[j+1];
b = cpPixelsStore[j+2];
a = cpPixelsStore[j+3];
printf("r:0x%X g:0x%X b:0x%X a:0x%X\n", r, g, b, a);
}
int width = 2;
int height = 1;
int bytesPerRow = 4 * width;
int bitsPerComponent = 8;
int bitsPerPixel = 32;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host | kCGImageAlphaLast;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, cpPixelsStore, (bytesPerRow * height), NULL);
CGImageRef imRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
CGDataProviderRelease(provider);
UIImage *imNewTemp = [UIImage imageWithCGImage:imRef];
NSData *datPNG = UIImagePNGRepresentation(imNewTemp);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *sFile = [documentsDirectory stringByAppendingPathComponent:@"Pic.png"];
[datPNG writeToFile:sFile atomically:YES];
CGImageRelease(imRef);
// Cross verify save
UIImage *imTemp = [UIImage imageWithContentsOfFile:sFile];
NSData *datImagePixels = (__bridge NSData *)CGDataProviderCopyData(CGImageGetDataProvider(imTemp.CGImage));
unsigned char *ucpPixelBytes = (unsigned char *)[datImagePixels bytes];
for(int j = 0; j < datImagePixels.length; j += 4)
{
r = ucpPixelBytes[j+0];
g = ucpPixelBytes[j+1];
b = ucpPixelBytes[j+2];
a = ucpPixelBytes[j+3];
printf("r:0x%X g:0x%X b:0x%X a:0x%X\n", r, g, b, a);
}
初始printf在创建期间返回: r:0x31 g:0x32 b:0x33 a:0x34 r:0x35 g:0x36 b:0x37 a:0x38
保存并检索文件后,printf给出了这个输出: r:0xA g:0xA b:0xA a:0x31 r:0xC g:0xB b:0xB a:0x35
我在翻译中迷失了。请帮忙。
答案 0 :(得分:0)
NSData是不可变的 - 您需要一个NSMutableData对象,然后使用&#39; mutableBytes&#39;得到指针。 NSMutableData * nData = [NSMutableData dataWithData:datImagePixels];
现在您可以根据修改创建新图像。您可以使用Quartz方法CGImageCreate()来获取CGImageRef,并从中获取UIImage。