gpt4 book ai didi

ios - 如何从UIImagePickerViewcontroller获取缩略图和原始图像?

转载 作者:行者123 更新时间:2023-12-01 16:13:13 25 4
gpt4 key购买 nike

从相机中捕获照片后,我进行了图像压缩(400kb和1 Mb),在iPhone 6中看起来将近3秒,而在iPhone 6s中则不到一秒。
有什么方法可以在不进行手动压缩的情况下获取缩略图和原始图像?

用于图像压缩的代码

UIImage的扩展

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)
}

最佳答案

对于保存在照片库中的图像:

尝试:

  let phAsset = info[UIImagePickerController.InfoKey.phAsset] as! PHAsset
let options = PHImageRequestOptions()
options.deliveryMode = .fastFormat
options.isSynchronous = false

// 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 your thumbnail
})

对于从“相机”捕获的图像,您可以获取图像像素,而无需重新计算数据计数:
 let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage

// pixels are the same on each device’s camera
let widthPixels = image.size.width * image.scale
let heightPixels = image.size.height * image.scale
let sizeInBytes = 1024 * 1024

var thumbnail : UIImage! = nil

if Int(widthPixels * heightPixels) > sizeInBytes {
// assign custom width and height you need
let rect = CGRect(x: 0.0, y: 0.0, width: 100, height: 100)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 1)
let context = UIGraphicsGetCurrentContext()
context?.interpolationQuality = .low
image.draw(in: rect)
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
thumbnail = resizedImage

} else {

thumbnail = image

}

关于ios - 如何从UIImagePickerViewcontroller获取缩略图和原始图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59530252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com