3

在我的应用程序中,我使用相机和照片库来获取 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);

我似乎无法弄清楚可能导致这种情况的其他任何事情

谢谢

小瑞

4

1 回答 1

2

这里的问题可能是您以错误的方式创建位图上下文或 UIImage。尝试调试并检查是否_regularImage为 nil,或者它是否无效。对于缩放图像,我建议使用名为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,使您的工作变得非常容易。

于 2011-08-21T03:45:09.717 回答