How do I make an exact copy of a UIImage returned from a UIImagePickerController?

我们两清 提交于 2019-11-29 00:10:28
Cameron Lowell Palmer

Copy backing data and rotate it

This question asks a common question about UIImage in a slightly different way. Essentially, you have two related problems - deep copying and rotation. A UIImage is just a container and has an orientation property that is used for display. A UIImage can contain its backing data as a CGImage or CIImage, but most often as a CGImage. The CGImage is a struct of information that includes a pointer to the underlying data and if you read the docs, copying the struct does not copy the data. So...

Deep copying

As I'll get to in the next paragraph deep copying the data will leave the image rotated because the image is rotated in the underlying data.

UIImage *newImage = [UIImage imageWithData:UIImagePNGRepresentation(oldImage)];

This will copy the data but will require setting the orientation property before handing it to something like UIImageView for proper display.

Another way to deep copy would be to draw into the context and grab the result. Assume a zebra.

UIGraphicsBeginImageContext(zebra!.size)
zebra!.drawInRect(CGRectMake(0, 0, zebra!.size.width, zebra!.size.height))
let copy = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Deep copy and Rotation

Rotating a CGImage has been already been answered. It also happens that this rotated image is a new CGImage that can be used to create a UIImage.

This seems to work but you might face some memory problems depending on what you do with newImage:

CGImageRef newCgIm = CGImageCreateCopy(oldImage.CGImage);
UIImage *newImage = [UIImage imageWithCGImage:newCgIm scale:oldImage.scale orientation:oldImage.imageOrientation];
jklapwyk

This should work:

UIImage *newImage = [UIImage imageWithCGImage:oldImage.CGImage];
UIImage *newImage = [UIImage imageWithData:UIImagePNGRepresentation(oldImage)];

I think you need to create an image context (CGContextRef). Draw the UIImage.CGImage into the context with method CGContextDrawImage(...), then get the image from the context with CGBitmapContextCreateImage(...). With such routine, I'm sure you can get the real copy of the image you want. Hope it's helped you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!