2

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

在此处输入图像描述

-(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;

}

这段代码有什么问题?

4

1 回答 1

1

请使用 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);
于 2013-01-03T15:09:37.640 回答