我正在创建一个相机应用程序,并且一切正常,但是要上传到Firebase的照片的文件大小太大。它们属于3MB类别,我希望它们属于±600KB类别。
我已将 AVCapturePhotoSettings.isHighResolutionPhotoEnabled 设置为 false ,但这似乎无济于事,并且 AVCapturePhotoOutput.quality.balanced 仅适用于iOS13 +不适用于我的情况。
这是将图像发送到我的imageArray的委托函数
extension NewPostFromPhoto: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let error = error {
debugPrint (error)
} else {
photoData = photo.fileDataRepresentation()
UIImageWriteToSavedPhotosAlbum(UIImage(data: photoData!)!, nil, nil, nil)
self.imageArray.insert((UIImage(data: photoData!)?.fixOrientation())!, at:0)
self.recentMediaCollection.reloadData()
}
}
}
这是我的takePhoto()方法:
func takeNewPhoto () {
let settings = AVCapturePhotoSettings ()
settings.isHighResolutionPhotoEnabled = false
photoOutput?.capturePhoto(with: settings, delegate: self)
}
答案 0 :(得分:1)
使用您的代码,我得到了大约20 MB的pngData。但是当我们使用jpegData()时,我们得到了约2.2 MB。
image.jpegData(compressionQuality: 0.8)
这里有代表的完整代码
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
guard let imageData = photo.cgImageRepresentation() else {
self.captureFailed(error: error?.localizedDescription ?? "Can't take image from output")
return
}
let cgimage = imageData.takeUnretainedValue()
let orientation: UIImage.Orientation = captureDevice?.position == .front ? .leftMirrored : .right
let image = UIImage(cgImage: cgimage, scale: 1, orientation: orientation)
let data = image?.jpegData(compressionQuality: 0.8)
}
希望它的帮助