起源:前两天有人说使用SDWebImage下载图片后保存到相册发现图片被压缩了,原图2.2M,保存到相册后传到Mac上显示图片大小只有500K左右。于是尝试了一下,代码如下:
NSURL *imgUrl = [NSURL URLWithString:@"https://xxxx.png"];
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:imgUrl completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
if (image) {
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//清除sd缓存,防止图片被sdwebimage缓存
// [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
// [[SDImageCache sharedImageCache] clearMemory];
}
}];
然后到相册里一查还真是变成了500多k、首先查看data.length,大小和原图一致,确定了不是SDWebImage 框架的问题。那么一定是这个函数对图片进行了压缩:
// Adds a photo to the saved photos album. The optional completionSelector should have the form:
// - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
UIKIT_EXTERN void UIImageWriteToSavedPhotosAlbum(UIImage *image, __nullable id completionTarget, __nullable SEL completionSelector, void * __nullable contextInfo) __TVOS_PROHIBITED;
于是乎使用Photos
框架中的PHPhotoLibrary
来存储图片以解决这个问题,代码如下:
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:imgUrl completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
NSLog(@"dataLen:%lu",data.length);
if (finished)
{
UIImage * imgsave = image;
NSString * path = NSHomeDirectory();
//图片存储的沙盒路径
NSString * Pathimg = [path stringByAppendingString:@"/Documents/test.png"];
[UIImagePNGRepresentation(imgsave) writeToFile:Pathimg atomically:YES];
//使用url存储到相册
NSURL *imagePathUrl = [NSURL fileURLWithPath:Pathimg];
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {//权限判断
PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
[library performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:imagePathUrl];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (success) NSLog(@"保存成功");
else NSLog(@"保存失败");
}];
}
}];
}
}];