给出EXC_BAD_ACCESS的UIImageJPEGRepresentation

时间:2011-08-21 02:59:23

标签: objective-c ios uiimage nsdata uiimagejpegrepresentation

在我的应用程序中,我使用相机和照片库来获取UIImage,
然后将这个UIImage缩小大约正常大小的20倍 然后我根据UIImage设置一个NSData对象。

_regularImage = [self resizeImage:_takenImage width:100 height:100];


-(UIImage *)resizeImage:(UIImage *)anImage width:(int)width height:(int)height
{

    CGImageRef imageRef = [anImage CGImage];

    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);

    if (alphaInfo == kCGImageAlphaNone)
        alphaInfo = kCGImageAlphaNoneSkipLast;


    CGContextRef bitmap = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(imageRef), 4 * width, CGImageGetColorSpace(imageRef), alphaInfo);

    CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), imageRef);

    CGImageRef ref = CGBitmapContextCreateImage(bitmap);
    UIImage *result = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);
    CGImageRelease(ref);

    return result;      
}

NSData *image1Data = UIImageJPEGRepresentation(_regularImage, 1);

我似乎无法想出任何可能导致此问题的其他内容

谢谢

LittleRy

1 个答案:

答案 0 :(得分:2)

这里的问题可能是您正在以错误的方式创建位图上下文或UIImage。尝试调试并检查_regularImage是否为零,或者它是否无效。为了缩放图像,我建议使用名为ANImageBitmapRep的第三方库。它是一小组类,允许在iPhone上轻松裁剪,调整大小,旋转等图像。缩放UIImage可以这样做:

ANImageBitmapRep * irep = [ANImageBitmapRep imageBitmapRepWithImage:myImage];
[irep setSize:BMPointMake(myWidth, myHeight)]; // scale the image
UIImage * theImage = [irep image];
[irep release];
NSData * jpeg = UIImageJPEGRepresentation(theImage, 1);

有了这种代码,我怀疑UIImageJPEGRepresentation是否会成为问题。 ANImageBitmapRep类本身在内部处理CGContextRef内容,使您的工作变得更加轻松。

相关问题