我想修改 .png 图像并将其保存到文件夹中。
- 将 uiimage 转换为 NSData
- 修改一些像素
- 从修改后的 NSData 创建一个新的 UIImage
- 将此 UIImage 保存到文件夹
- 将相同的 UIImage 设置为 ImageView 的图像属性
如果我检查 UIImage 的图像,像素数据是正确的,但如果我加载保存的图像,像素数据与修改后的值有点不同。
例如:
- 107 -76 -43 -1 //RGBA888格式原始图像的一个像素
- 93 -89 -56 -1 // 修改后的像素值
- 93 -89 -56 -1 //像素值,在我将它设置为imageView的图像并读回之后
- 95 -91 -57 -1 //像素值,我从stroage加载回来后
我的图像保存方法:
- (void) saveImage: (UIImage*) image toFolder: (NSString*) folder
{
[self.library saveImage: image toAlbum: folder withCompletionBlock:^(NSError *error) {
if (error!=nil) {
NSLog(@"Error: %@", [error description]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message: [error description]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Image saved!"
message: nil
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}];
}
像素修改方法:
CGImageRef cRef = CGImageRetain(_imageView.image.CGImage);
NSData* pixelData = (NSData*) CFBridgingRelease(CGDataProviderCopyData(CGImageGetDataProvider(cRef)));
// image raw data
signed char* pixelBytes = (signed char *)[pixelData bytes];
// MODIFY SOME PIXEL HERE
NSData* newPixelData = [NSData dataWithBytes:pixelBytes length:[pixelData length]];
// cast NSData as CFDataRef
CFDataRef imgData = (CFDataRef)CFBridgingRetain(newPixelData);
// Make a data provider from CFData
CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData(imgData);
// get PNG properties from cRef
size_t width = CGImageGetWidth(cRef);
size_t height = CGImageGetHeight(cRef);
size_t bitsPerComponent = CGImageGetBitsPerComponent(cRef);
size_t bitsPerPixel = CGImageGetBitsPerPixel(cRef);
size_t bytesPerRow = CGImageGetBytesPerRow(cRef);
CGColorSpaceRef colorSpace = CGImageGetColorSpace(cRef);
CGBitmapInfo info = CGImageGetBitmapInfo(cRef);
CGFloat *decode = NULL;
BOOL shouldInteroplate = NO;
CGColorRenderingIntent intent = CGImageGetRenderingIntent(cRef);
// cRef PNG properties + imgDataProvider's data
CGImageRef throughCGImage = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, info, imgDataProvider, decode, shouldInteroplate, intent);
CGDataProviderRelease(imgDataProvider);
// make UIImage with CGImage
UIImage* newImage = [UIImage imageWithCGImage:throughCGImage];
CGImageRelease(throughCGImage);
[self saveImage:newImage toFolder:@"DEMOFOLDER"];
_imageView.image = newImage;