swift - 为什么我的 AVCapturePhotoOutput 文件输出这么大?

标签 swift avcaptureoutput

我正在创建一个相机应用程序,一切运行良好,但上传到 Firebase 的照片的文件大小太大。它们属于 3MB 类别,我希望它们属于 ±600KB 类别。

我设置了 AVCapturePhotoSettings.isHighResolutionPhotoEnabled 但这似乎没有任何作用, AVCapturePhotoOutput.quality.balanced 仅适用于 iOS13+,这在我的情况下不起作用。

这是将图像发送到我的 imageArray 的委托(delegate)函数

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

最佳答案

使用您的代码,我得到了大约 20 MB 的 pngData。但是当我们使用 jpegData() 时,我们得到了大约 2.2 MB。

image.jpegData(compressionQuality: 0.8)

这里是委托(delegate)的完整代码
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)
}

希望它的帮助

关于swift - 为什么我的 AVCapturePhotoOutput 文件输出这么大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59298092/

相关文章:

ios - 如何在 TableView 中调整 cell.imageView 的大小并在 Swift 中应用 tintColor

swift - AVCapturePhotoOutput 不提供预览缓冲区

swift - 如何测试 Swift 枚举与关联值的相等性

ios - 如何在 CAShapeLayer 中制作动态 strokeColor?在 swift

swift - AVCaptureMetadataObjectDelegate 未收到回调

ios - iPhone 7+,ios 11.2 : Depth data delivery is not supported in the current configuration

iOS:__connection_block_invoke_2 错误:连接中断

ios - 表/ Collection View 的水平滚动

swift - 是否可以在 Firebase 数据库中进行软写入?