How can I save a Bitmap Image, represented by a CGContextRef, to the iPhone's hard drive?

ぃ、小莉子 提交于 2019-12-21 06:27:00

问题


I have a little sketch program that I've managed to throw together using Quartz2D, but I'm very new to the iOS platform and I'm having trouble figuring out how to allow the user to save their sketch. I have a CGContextRef that contains the sketch, how can I save it so that it can later be retrieved? Once it's saved, how can I retrieve it?

Thanks so much in advance for your help! I'm going to continue reading up on this now...


回答1:


There are different types of CGContexts. You are most likely having a screen based context, but you would need either a bitmapContext or a pdfContext, to create a bitmap or a pdf file.

See the UIKit Functions Reference. Functions that should be of interest are:

  • UIGraphicsBeginImageContext()
  • UIGraphicsGetImageFromCurrentImageContext()
  • UIGraphicsEndImageContext()
  • UIImageJPEGRepresentation()
  • UIImageWriteToSavedPhotosAlbum()
  • UIGraphicsBeginPDFContextToFile()
  • UIGraphicsEndPDFContext()



回答2:


Here's how I did it...

Saving

CGImageRef imageRef = CGBitmapContextCreateImage(bitmapContext);
UIImage* image = [[UIImage alloc] initWithCGImage:imageRef];
NSData* imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];

Retrieving

UIImage* image = [UIImage imageWithContentsOfFile:filePath];
CGImageRef imageRef = [image CGImage];


来源:https://stackoverflow.com/questions/3488338/how-can-i-save-a-bitmap-image-represented-by-a-cgcontextref-to-the-iphones-ha

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