Search code examples
objective-ciosuiimagecalayer

Saving UIImage with UIImagePNGRepresentation not preserving my layer modification


I'm loading an image from NSData. The original image was created as a JPG. When I attempt to set a corner radius and save to disk, I'm losing the changes I made. I'm saving to disk as a PNG as I presumed that an alpha channel would be created on the layers which needs to be preserved.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];
[imageView.layer setMasksToBounds:YES];
[imageView.layer setCornerRadius:10.0f];
data = UIImagePNGRepresentation(imageView.image);
// save data to file with .png extension

The issue is that when I reload the image from the file system back into a UIImage, the corner radius is not visible.


Solution

  • CGContext can take a "screenshot".

    UIGraphicsBeginImageContext(self.frame.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Now I use the "screenshot"
    NSString *path = [NSHomeDirectory() stringByAppendingString:@"/image.jpg"];
    if ([UIImageJPEGRepresentation(image, 1) writeToFile:path atomically:YES]) {
        NSLog(@"save ok");
    }
    else {
        NSLog(@"save failed");
    }