views:

1713

answers:

1

I'm using UIImageWriteToSavedPhotosAlbum to save a UIImage to the user's photo album. The problem is that the image doesn't have transparency and is a JPG. I've got the pixel data set correctly to have transparency, but there doesn't seem to be a way to save in a transparency-supported format. Ideas?

EDIT: There is no way to accomplish this, however there are other ways to deliver PNG images to the user. One of which is to save the image in the Documents directory (as detailed below). Once you've done that, you can email it, save it in a database, etc. You just can't get it into the photo album (for now) unless it is a lossy non-transparent JPG.

+5  A: 

This is a problem I have noticed before and reported on the Apple Developer Forums about a year ago. As far as I know it is still an open issue.

If you have a moment, please take the time to file a feature request at Apple Bug Report. If more people report this issue, it is more likely that Apple will fix this method to output non-lossy, alpha-capable PNG.

EDIT

If you can compose your image in memory, I think something like the following would work or at least get you started:

- (UIImage *) composeImageWithWidth:(NSInteger)_width andHeight:(NSInteger)_height {
    CGSize _size = CGSizeMake(_width, _height);
    UIGraphicsBeginImageContext(_size);

    // Draw image with Quartz 2D routines over here...

    UIImage *_compositeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return _compositeImage;
}

//
// cf. https://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/FilesandNetworking/FilesandNetworking.html#//apple_ref/doc/uid/TP40007072-CH21-SW20
//

- (BOOL) writeApplicationData:(NSData *)data toFile:(NSString *)fileName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    if (!documentsDirectory) {
        NSLog(@"Documents directory not found!");
        return NO;
    }
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    return ([data writeToFile:appFile atomically:YES]);
}

// ...

NSString *_imageName = @"myImageName.png";
NSData *_imageData = [NSData dataWithData:UIImagePNGRepresentation([self composeImageWithWidth:100 andHeight:100)];

if (![self writeApplicationData:_imageData toFile:_imageName]) {
    NSLog(@"Save failed!");
}
Alex Reynolds
Done and done. I've heard there is a way to save images to the documents folder in a non-lossy format. Any idea how to do that?
Eli
I have updated my answer. Hopefully this helps get you started.
Alex Reynolds
Beautiful! Worked wonders. The image is a PNG and has transparency, I just needed to find it and that was it.
Eli