我正在尝试访问已使用此块调整大小的某个图像的像素:
-(UIImage *)imageResize:(UIImage *)imageResizable scaledToSize:(CGSize)newSize
{
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[imageResizable drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
...其中newSize 是UIView 的大小,我试图在其中适合此图像。
现在,我应该访问该图像的像素,并对其进行一些过滤。我使用以下代码块:
-(UIImage*) filter : (UIImage *) image
{
CGImageRef imageBuffTarget = [image CGImage];
CFMutableDataRef pixelDataTarget = CFDataCreateMutableCopy(0, 0, CGDataProviderCopyData(CGImageGetDataProvider(imageBuffTarget)));
NSUInteger width2 = CGImageGetWidth(imageBuffTarget);
NSUInteger height2 = CGImageGetHeight(imageBuffTarget);
UInt8 *target_image = (UInt8 *)CFDataGetMutableBytePtr(pixelDataTarget);
// Going forward, I want to do some processing here, on the *target_image data.
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo1 = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
CGContextRef context = CGBitmapContextCreate(target_image, CGImageGetWidth(imageBuffTarget), CGImageGetHeight(imageBuffTarget), CGImageGetBitsPerComponent(imageBuffTarget), CGImageGetBytesPerRow(imageBuffTarget), colorSpaceRef, bitmapInfo1);
CGImageRef imageRef = CGBitmapContextCreateImage (context);
UIImage *newimage = [UIImage imageWithCGImage:imageRef];
CGColorSpaceRelease(colorSpaceRef);
CGContextRelease(context);
CFRelease(imageRef);
return newimage;
}
我从 UIView 获取图像,将其传递给“过滤器”方法并将其设置回视图。
但是,在执行此操作时,应用程序崩溃并且我在控制台中收到以下错误:
<Error>: CGBitmapContextCreate: invalid data bytes/row: should be at least 1280 for 8 integer bits/component, 3 components, kCGImageAlphaPremultipliedLast.
<Error>: CGBitmapContextCreateImage: invalid context 0x0
当我改变时:
CGContextRef context = CGBitmapContextCreate(target_image, CGImageGetWidth(imageBuffTarget), CGImageGetHeight(imageBuffTarget), CGImageGetBitsPerComponent(imageBuffTarget), CGImageGetBytesPerRow(imageBuffTarget), colorSpaceRef, bitmapInfo1);
至
CGContextRef context = CGBitmapContextCreate(target_image, CGImageGetWidth(imageBuffTarget), CGImageGetHeight(imageBuffTarget), CGImageGetBitsPerComponent(imageBuffTarget), 2*CGImageGetBytesPerRow(imageBuffTarget), colorSpaceRef, bitmapInfo1);
(2 乘以“每行字节数”,确实超过了 1280)
该应用程序不会崩溃,但视图上的输出结果是原始图像的扭曲和倾斜版本。
请注意,当我调用 CGImageGetHeight(imageBuffTarget) 和 CGImageGetWidth(imageBuffTarget) 时,我得到了我传递给 imageResize 方法的 ImageView 的确切高度和宽度。
你能帮我找出这段代码中的错误吗?
提前致谢。