Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using UIImagePickerController to get image -- how to know whether to save PNG or JPEG?

I've got a UIImagePickerController letting the user pick an image out of the image library, and am getting its results via the didFinishPickingMediaWithInfo method.

I need to be able to save the resulting image to disk (in the app's documents folder), and reload it later.

The issue is that I can't tell whether to store it as a PNG or JPEG. I can't just always store it as a PNG, because for larger photos it's interminably slow (not to mention then I have to deal with storing the image orientation separately). I can't just always store it as a JPEG, because in some cases the images have transparency, which will get lost if I do that.

I've examined the UIImagePickerControllerMediaType key in the info dictionary returned by the image picker, and regardless of whether I've selected a PNG or JPEG, what gets returned is "image.public".

So...

Is there some way to know whether the user has chosen a PNG? Maybe some method of just checking if the image has any transparency or something?

Thanks.

like image 813
DanM Avatar asked Jun 29 '12 23:06

DanM


2 Answers

OK, so I figured it out. This may not work for every scenario, but it's sufficient for me:

    CGImageAlphaInfo imgAlpha = CGImageGetAlphaInfo(theImage.CGImage);

    // Is this an image with transparency (i.e. do we need to save as PNG?)
    if ((imgAlpha == kCGImageAlphaNone) || (imgAlpha == kCGImageAlphaNoneSkipFirst) || (imgAlpha == kCGImageAlphaNoneSkipLast)) {
         // save as a JPEG
    } else {
         // save as a PNG
    }

...of course you need to remember which type of image you saved, give it the appropriate file extension, and load the right one back in... but basically this takes care of it. Images with transparency will be saved as PNGs, everything else as JPEGs.

If anyone has any better methods, I'd love to hear them. Thanks!

like image 168
DanM Avatar answered Sep 24 '22 12:09

DanM


in the dictionary the key UIImagePickerControllerReferenceURL will give you informations about the type

(gdb) po info

{
    UIImagePickerControllerMediaType = "public.image";
    UIImagePickerControllerOriginalImage = "<UIImage: 0x5cfd00>";
    UIImagePickerControllerReferenceURL = "assets-library://asset/asset.JPG?id=EFC44C3C-9C82-4669-924B-A2B9DE6F1F45&ext=JPG";
}

In this case it is a jpg as shown by ext=JPG

like image 35
terrinecold Avatar answered Sep 23 '22 12:09

terrinecold