我的应用程序在控制台上出现这些错误:
<Error>: CGBitmapContextCreateImage: invalid context 0xdf12000
Program received signal: “EXC_BAD_ACCESS”.
来自以下代码:
- (UIImage *)pureBlackAndWhiteImage:(UIImage *)image {
//CGImageRef imageR = [image CGImage];
CGColorSpaceRef colorSpac = CGColorSpaceCreateDeviceGray();
//CGRect rect = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);
CGContextRef contex = CGBitmapContextCreate(NULL, image.size.width,
image.size.height, 8, 1*image.size.width, colorSpac, kCGImageAlphaNone);
contex = malloc(image.size.height * image.size.width * 4);
CGColorSpaceRelease(colorSpac);
// Draw the image into the grayscale context
//CGContextDrawImage(contex, rect, NULL);
CGImageRef grayscale = CGBitmapContextCreateImage(contex);
CGContextRelease(contex);
NSUInteger width = CGImageGetWidth(grayscale);
NSUInteger height = CGImageGetHeight(grayscale);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CFDataRef datare=CGDataProviderCopyData(CGImageGetDataProvider(grayscale));
unsigned char *dataBitmap=(unsigned char *)CFDataGetBytePtr(datare);
dataBitmap = malloc(height * width * 4);
NSUInteger bytesPerPixel = 1;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(dataBitmap, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaNoneSkipLast);
//unsigned char *dataBitmap = [self bitmapFromImage:image];
for (int i = 0; i < image.size.width * image.size.height * 4; i += 4) {
// if ((dataBitmap[i + 1] + dataBitmap[i + 2] + dataBitmap[i + 3]) < (255 * 3 / 2)) {
if(dataBitmap[i+1]>128 && dataBitmap[i+2]>128 && dataBitmap[i+3]>128)
{
dataBitmap[i + 1] = 0;
dataBitmap[i + 2] = 0;
dataBitmap[i + 3] = 0;
} else {
dataBitmap[i + 1] = 255;
dataBitmap[i + 2] = 255;
dataBitmap[i + 3] = 255;
}
}
//CFDataRef newData=CFDataCreate(NULL,dataBitmap,length);
CGColorSpaceRef colorSpa = CGColorSpaceCreateDeviceRGB();
CGContextRef bitmapcontext = CGBitmapContextCreate(dataBitmap,
image.size.width,
image.size.height,
8,
1*image.size.width,
colorSpa,
kCGImageAlphaNone);
CFRelease(colorSpace);
CFRelease(colorSpa);
CGImageRef cgImage = CGBitmapContextCreateImage(bitmapcontext);
CFRelease(cgImage);
CFRelease(bitmapcontext);
CGContextRelease(context);
free(dataBitmap);
//CFRelease(imageR);
UIImage *newImage = [UIImage imageWithCGImage:cgImage];
return newImage;
}
可能导致这些错误的原因是什么?
答案 0 :(得分:0)
您尝试使用每行4个字节创建上下文,此时图像的宽度远远大于此值。
如果每个像素有1个字节,那么应该使用1 * image.size.width
而不是4个字节,就像第二次和第三次创建位图上下文一样。
除此之外,我不认为传递imageR
作为第一个参数是一个好主意。如果您要部署iOS 4或更高版本,则可以改为NULL
否则,我认为你必须分配内存来存储位图上下文数据。