我正在使用 UIImageWriteToSavedPhotosAlbum 将 UIImage 保存到用户的相册。问题是图像没有透明度并且是JPG。我已经正确设置了像素数据以具有透明度,但似乎没有办法以支持透明度的格式保存。想法?
编辑:没有办法做到这一点,但是还有其他方法可以将 PNG 图像传递给用户。其中之一是将图像保存在 Documents 目录中(如下所述)。完成此操作后,您可以通过电子邮件发送它,将其保存在数据库中等。除非它是有损非透明 JPG,否则您无法将其放入相册(目前)。
我正在使用 UIImageWriteToSavedPhotosAlbum 将 UIImage 保存到用户的相册。问题是图像没有透明度并且是JPG。我已经正确设置了像素数据以具有透明度,但似乎没有办法以支持透明度的格式保存。想法?
编辑:没有办法做到这一点,但是还有其他方法可以将 PNG 图像传递给用户。其中之一是将图像保存在 Documents 目录中(如下所述)。完成此操作后,您可以通过电子邮件发送它,将其保存在数据库中等。除非它是有损非透明 JPG,否则您无法将其放入相册(目前)。
正如在这个SO question 中指出的那样,有一种简单的方法可以将 png 保存在您的相册中:
UIImage* image = ...; // produce your image
NSData* imageData = UIImagePNGRepresentation(image); // get png representation
UIImage* pngImage = [UIImage imageWithData:imageData]; // rewrap
UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, nil); // save to photo album
这是我之前注意到的一个问题,大约一年前在Apple Developer Forums上进行了报告。据我所知,这仍然是一个悬而未决的问题。
如果您有时间,请花时间在Apple Bug Report上提交功能请求。如果更多人报告此问题,Apple 更有可能修复此方法以输出无损、支持 alpha 的 PNG。
编辑
如果您可以在内存中构图,我认为以下内容会起作用,或者至少可以帮助您入门:
- (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!");
}
在 Swift 5 中:
func pngFrom(image: UIImage) -> UIImage {
let imageData = image.pngData()!
let imagePng = UIImage(data: imageData)!
return imagePng
}
我使用安全展开创建了 UIImage 的扩展:
延期
extension UIImage {
func toPNG() -> UIImage? {
guard let imageData = self.pngData() else {return nil}
guard let imagePng = UIImage(data: imageData) else {return nil}
return imagePng
}
}
用法:
let image = //your UIImage
if let pngImage = image.toPNG() {
UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, nil)
}
作为为 UIImageWriteToSavedPhotosAlbum 创建辅助 UIImage 的替代方法,可以使用 PHPhotoLibrary 直接写入 PNG 数据。
这是一个名为“saveToPhotos”的 UIImage 扩展,它执行此操作:
extension UIImage {
func saveToPhotos(completion: @escaping (_ success:Bool) -> ()) {
if let pngData = self.pngData() {
PHPhotoLibrary.shared().performChanges({ () -> Void in
let creationRequest = PHAssetCreationRequest.forAsset()
let options = PHAssetResourceCreationOptions()
creationRequest.addResource(with: PHAssetResourceType.photo, data: pngData, options: options)
}, completionHandler: { (success, error) -> Void in
if success == false {
if let errorString = error?.localizedDescription {
print("Photo could not be saved: \(errorString))")
}
completion(false)
}
else {
print("Photo saved!")
completion(true)
}
})
}
else {
completion(false)
}
}
}
要使用:
if let image = UIImage(named: "Background.png") {
image.saveToPhotos { (success) in
if success {
// image saved to photos
}
else {
// image not saved
}
}
}