Control image quality with UIImageWriteToSavedPhot

2019-09-01 02:58发布

问题:

This question already has an answer here:

  • UIImageWriteToSavedPhotosAlbum saves to wrong size and quality 2 answers

I'm using code like the following to save the current screen to the photos library:

UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* result = UIGraphicsGetImageFromCurrentImageContext();     
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(result, nil,nil, nil);

This works, but the quality looks a lot like a compressed JPG (and the file name saved is in the standard IMG_XXXX.JPG format), even though nowhere in this code is the type of image or its quality specified. Is there a way to control quality? I.e. could I have it saved as an uncompressed PNG instead?

回答1:

You can save it as a PNG by utilizing the UIImagePNGRepresentation() method for NSData, do something like this:

....
UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData* data =  UIImagePNGRepresentation ( result );
UIImage* pngImage = [UIImage imageWithData:data];
UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, nil);

Hope this helps.