起源:前兩天有人說(shuō)使用SDWebImage下載圖片后保存到相冊(cè)發(fā)現(xiàn)圖片被壓縮了察藐,原圖2.2M歪脏,保存到相冊(cè)后傳到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];
}
}];
然后到相冊(cè)里一查還真是變成了500多k、首先查看data.length淮摔,大小和原圖一致,確定了不是SDWebImage 框架的問(wèn)題始赎。那么一定是這個(gè)函數(shù)對(duì)圖片進(jìn)行了壓縮:
// 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
來(lái)存儲(chǔ)圖片以解決這個(gè)問(wèn)題和橙,代碼如下:
[[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();
//圖片存儲(chǔ)的沙盒路徑
NSString * Pathimg = [path stringByAppendingString:@"/Documents/test.png"];
[UIImagePNGRepresentation(imgsave) writeToFile:Pathimg atomically:YES];
//使用url存儲(chǔ)到相冊(cè)
NSURL *imagePathUrl = [NSURL fileURLWithPath:Pathimg];
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {//權(quán)限判斷
PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
[library performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:imagePathUrl];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (success) NSLog(@"保存成功");
else NSLog(@"保存失敗");
}];
}
}];
}
}];