[从相机捕获照片后,我正在对图像进行压缩(400kb和1 Mb),在iPhone 6中看起来差不多3秒,而在iPhone 6s中不到1秒。是否有任何方法无需手动压缩即可获取缩略图和原始图像?
用于图像压缩的代码
extension UIImage {
// MARK: - UIImage+Resize
func compressTo(_ expectedSizeInMb:Int) -> Data? {
let sizeInBytes = expectedSizeInMb * 1024 * 1024
var needCompress:Bool = true
var imgData:Data?
var compressingValue:CGFloat = 1.0
while (needCompress && compressingValue > 0.0) {
if let data:Data = jpegData(compressionQuality: compressingValue) {
if data.count < sizeInBytes {
needCompress = false
imgData = data
} else {
compressingValue -= 0.1
}
}
}
if let data = imgData {
if (data.count < sizeInBytes) {
return data
}
}
return nil
}
}
if let imageData = image.compressTo(1) {
print(imageData)
}
尝试使用“ AssetLibrary.framework”将图像写入相机胶卷,它将自动为您创建缩略图。而且,由于此过程是异步的,因此肯定会提高该应用程序的性能。
尝试以下操作:
Swift 5
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
/////.........
let img = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
let library = ALAssetsLibrary()
if let image = ALAssetOrientation(rawValue: img?.imageOrientation.rawValue) {
library.writeImage(toSavedPhotosAlbum: img?.cgImage, orientation: image, completionBlock: { assetURL, error in
if error != nil {
print("error")
return
}
library.asset(for: assetURL, resultBlock: { asset in
if let aspect = asset?.aspectRatioThumbnail() {
self.imageViewer.image = UIImage(cgImage: aspect)
} //self.imageViewer is a UIImageView to display thumbnail
}, failureBlock: { error in
print("Failed to load captured image.")
})
})
}
//................
}
目标c
#import <AssetsLibrary/AssetsLibrary.h>
////.........your code
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
/////.........
UIImage* img = info[UIImagePickerControllerOriginalImage];
ALAssetsLibrary *library = [ALAssetsLibrary new];
[library writeImageToSavedPhotosAlbum:[img CGImage] orientation:(ALAssetOrientation)[img imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(@"error");
return;
}
[library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
[self.imageViewer setImage:[UIImage imageWithCGImage:[asset aspectRatioThumbnail]]]; //self.imageViewer is a UIImageView to display thumbnail
} failureBlock:^(NSError *error) {
NSLog(@"Failed to load captured image.");
}];
}];
[library release];
//................
}
////......rest of your code
我尚未测试代码,但我希望它能够实现您的目的。在尝试尝试之前,请确保将“ AssetLibrary.framework”引用添加到您的项目中,并让我知道它是否对您有用。
尝试:
let phAsset = info[UIImagePickerController.InfoKey.phAsset] as! PHAsset
let options = PHImageRequestOptions()
options.deliveryMode = .fastFormat
// you can change your target size to CGSize(width: Int , height: Int) any number you want.
PHImageManager.default().requestImage(for: phAsset, targetSize: PHImageManagerMaximumSize, contentMode: .default, options: options, resultHandler: { image , _ in
let thumbnail = image
// use tour thumbnail
})