iphone - 崩溃: UIImage style crash with code for iOS 6?

标签 iphone objective-c ios6 uiimageview uiimage

这是我用于设置图像样式的代码。在iOS4.3及以上版本中,代码工作正常,但在iOS 6中,它崩溃了。

enter image description here

-(UIImage *)grayImage:(UIImage *)image
{
    CGImageRef img= image.CGImage;//imageSelected.CGImage;//self.originalPhoto.CGImage;

    CFDataRef dataref=CGDataProviderCopyData(CGImageGetDataProvider(img));

    int length=CFDataGetLength(dataref);
    UInt8 *data=(UInt8 *)CFDataGetBytePtr(dataref);

    for(int index=0;index<length;index+=4){
        Byte grayScale =
        (Byte)(data[index+3]*.11  +
               data[index + 2] * .59  +
               data[index + 1] * .3);

        //set the new image's pixel to the grayscale version
        data[index+1] = grayScale;// Code Crash here , By SIGABRAT (Exe_Bad_Access)
        data[index+2] = grayScale;
        data[index+3] = grayScale;
    }
    // .. Take image attributes
    size_t width=CGImageGetWidth(img);
    size_t height=CGImageGetHeight(img);
    size_t bitsPerComponent=CGImageGetBitsPerComponent(img);
    size_t bitsPerPixel=CGImageGetBitsPerPixel(img);
    size_t bytesPerRow=CGImageGetBytesPerRow(img);

    // .. Do the pixel manupulation
    CGColorSpaceRef colorspace=CGImageGetColorSpace(img);
    CGBitmapInfo bitmapInfo=CGImageGetBitmapInfo(img);
    CFDataRef newData=CFDataCreate(NULL,data,length);
    CGDataProviderRef provider=CGDataProviderCreateWithCFData(newData);

    // .. Get the Image out of this raw data
    CGImageRef newImg=CGImageCreate(width,height,bitsPerComponent,bitsPerPixel,bytesPerRow,colorspace,bitmapInfo,provider,NULL,true,kCGRenderingIntentDefault);

    // .. Prepare the image from raw data
    UIImage* rawImage = [[UIImage alloc] initWithCGImage:newImg] ;

    // .. done with all,so release the references
    CFRelease(newData);
    CGImageRelease(newImg);
    CGDataProviderRelease(provider);
    CFRelease(dataref);

    return rawImage;

}

这段代码有什么问题?

最佳答案

请使用 CFMutableDataRef 代替 CFDataRef,如下所示

CFDataRef m_DataRef = CGDataProviderCopyData(CGImageGetDataProvider(inImage)); 
//->write this:
CFMutableDataRef m_DataRef = CFDataCreateMutableCopy(0, 0, CGDataProviderCopyData(CGImageGetDataProvider(inImage)));

UInt8 * m_PixelBuf = (UInt8 *) CFDataGetBytePtr(m_DataRef); 
//->write this
UInt8 *m_PixelBuf=(UInt8 *)CFDataGetMutableBytePtr(m_DataRef);

关于iphone - 崩溃: UIImage style crash with code for iOS 6?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14099482/

相关文章:

iphone - Storyboard在 View 之间传递图像

ios - 为什么将我的对象添加到NSMutableArray无法正常工作?

iphone - 从ios中的应用程序转到应用程序商店时如何返回应用程序

objective-c - 如何仅流式传输来自 YouTube 的视频的声音?

ios - 如何在corePlote中制作圆形图例?

ios - UIWebview : How to notify UIViewController if any of the already loaded link in the web view fails to open

iphone - 为 iPhone 开发人员学习 Mac OS X 开发的好资源

iphone - 多个 NSUrlConnection 同时运行

objective-c - Swift 编译器错误 : "non-modular header inside framework module"

ios - 无法从 Xcode 崩溃日志确定崩溃原因