IPhone BitmapImageRep

cocoaiphone

I have a buffer which has JPEG image data. I need to display this image in UIImageView. I need to convert this image buffer into an object of UIImage and use it as follows

NSData *data = [NSData dataWithContentsOfFile:appFile];
UIImage *theImage = [[UIImage alloc] initWithData:data];

I get the image displayed but with a low resolution as compared to the actual resolution. Do I need to convert it into a Bitmap first and then use it with UIImage? I don't seem to be able to use NSBitmapImageRep. Any ideas on how can this be achieved?

Best Answer

If the UIImageView frame dimensions are different than the source image dimensions, you'll get a resized version of the image. The quality can be pretty rough depending on how much of a conversion is being performed.

I found this code on the net somewhere (sorry original author - I've lost the attribution) that performs a smoother resize:

UIImage* resizedImage(UIImage *inImage, CGRect thumbRect)
{
    CGImageRef          imageRef = [inImage CGImage];
    CGImageAlphaInfo    alphaInfo = CGImageGetAlphaInfo(imageRef);

    // There's a wierdness with kCGImageAlphaNone and CGBitmapContextCreate
    // see Supported Pixel Formats in the Quartz 2D Programming Guide
    // Creating a Bitmap Graphics Context section
    // only RGB 8 bit images with alpha of kCGImageAlphaNoneSkipFirst, kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedFirst,
    // and kCGImageAlphaPremultipliedLast, with a few other oddball image kinds are supported
    // The images on input here are likely to be png or jpeg files
    if (alphaInfo == kCGImageAlphaNone)
        alphaInfo = kCGImageAlphaNoneSkipLast;

    // Build a bitmap context that's the size of the thumbRect
    CGContextRef bitmap = CGBitmapContextCreate(
                                                NULL,
                                                thumbRect.size.width,       // width
                                                thumbRect.size.height,      // height
                                                CGImageGetBitsPerComponent(imageRef),   // really needs to always be 8
                                                4 * thumbRect.size.width,   // rowbytes
                                                CGImageGetColorSpace(imageRef),
                                                alphaInfo
                                                );

    // Draw into the context, this scales the image
    CGContextDrawImage(bitmap, thumbRect, imageRef);

    // Get an image from the context and a UIImage
    CGImageRef  ref = CGBitmapContextCreateImage(bitmap);
    UIImage*    result = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);   // ok if NULL
    CGImageRelease(ref);

    return result;
}
Related Topic