hanachan1026
hanachan1026

Reputation: 335

imagewithcgimage always returns bad access memory error in objective-c

What I'm doing is create CGImage from bitmap data and convert it to UIImage.

I have code below

 - (UIImage *)imageWithBitmapBytes:(Byte *)imageBytes width:(size_t)width height:(size_t)height pixelCount:(NSUInteger)pixelCount {
    NSUInteger imageBufferSize = width * height * pixelCount;
    CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(nil, imageBytes, imageBufferSize, nil);
    NSUInteger bitsPerComponent = 8;
    NSUInteger bitsPerPixel = bitsPerComponent * pixelCount;
    NSUInteger bytesPerRow = width * pixelCount;
    CGImageRef cgImage = CGImageRetain(CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, CGColorSpaceCreateDeviceGray(), kCGImageAlphaLast, dataProviderRef, nil, false, kCGRenderingIntentDefault));
    CGDataProviderRelease(dataProviderRef);
    UIImage *image =[UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);

    return image;
}

I tested this code on both condition ARC turned on and turned off.

I always get Bad access memory error on this line

UIImage *image =[UIImage imageWithCGImage:cgImage];

Upvotes: 0

Views: 101

Answers (1)

Mahir Tayir
Mahir Tayir

Reputation: 61

I think problem is :

NSUInteger imageBufferSize = width * height * pixelCount;

because , imageBufferSize should be length of imageBytes ...

hope it helps you

Upvotes: 1

Related Questions