【问题标题】:Why are my AVCapturePhotoOutput file outputs so large?为什么我的 AVCapturePhotoOutput 文件输出这么大?
【发布时间】:2020-04-05 11:04:37
【问题描述】:

我正在创建一个相机应用程序,一切正常,但上传到 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)
} 

【问题讨论】:

    标签: swift avcaptureoutput


    【解决方案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)
    }
    

    希望对你有所帮助

    【讨论】:

    • 谢谢,这在委托中是哪里去了?
    • 那种工作谢谢你,我不得不更新你的解决方案来使用我的代码:让 image = UIImage(data: photoData!) 和 let smallImage = UIImageJPEGRepresentation(image!, 0.8) - jpegData 已弃用。它似乎并没有使图像文件大小变得非常小,但它确实加载得更快并且文件大小减少了大约 20%。
    • 我使用的是 swift 5,这里不推荐使用 jpegData。但是当我尝试使用UIImageJPEGRepresentation XCode 时显示错误'UIImageJPEGRepresentation' has been replaced by instance method 'UIImage.jpegData(compressionQuality:)' 你使用哪个版本的swift?
    • 奇怪,与我相反:“UIImage.jpegData(compressionQuality:) 已被 UIImageJPEGRepresentation 取代”现在我要闭上眼睛假装一切都很好:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多