缩小全屏图像的大小

时间:2018-12-19 05:01:15

标签: swift uiimage firebase-storage image-resizing uiimagejpegrepresentation

我有一个带有“ Snapchat式相机”的应用程序(即您先拍照,然后覆盖文字和表情符号)。我目前将分辨率降低为1080 x 2040,然后转换为质量为0.75的jpegRepresentation。

这仍然使我的文件大小> 2mb似乎很高。关于如何减小文件大小而不放弃太多质量的任何建议?我仍然希望图片在全屏尺寸下看起来不错。

调整图像大小,然后发送到存储空间

override func post() {
    // convert overlayed text and emojis to image and resize to 1080 x 2040
    guard let image = mediaView.asImage().resized(to: IMAGE_SIZE) else { return }

    //generate unique name for each image
    let imageId = NSUUID().uuidString
    let storageRef = Storage.storage().reference().child("post_images/\(imageId).jpeg")

    storageManager.upload(image: image, to: storageRef) { (err) in
        if let err = err {
            // TODO: Handle Error
            print("Error uploading image: \(err.localizedDescription)")
        } else {
            storageRef.downloadURL { (url, err) in
                guard let url = url else {
                    // TODO: Handle Error
                    print("Error getting image url: \(err?.localizedDescription)")
                    return
                }

                print("SUCCESSFULLY SAVED IMAGE")
            }
        }
    }
}

Storage Manager:将映像转换为jpeg并进行压缩。然后上传

func upload(image: UIImage, to storageRef: StorageReference, then handler: @escaping UploadHandler) {
    // upload to storage
    if let uploadData = image.jpegData(compressionQuality: 0.75) {
        let metadata = StorageMetadata()
        metadata.contentType = ContentTypeEnum.jpegImage.rawValue // "image/jpeg"

        storageRef.putData(uploadData, metadata: metadata) { (metadata, err) in
            if let err = err {
                handler(err)
            } else {
                handler(nil)
            }
        }
    }
}

用于将UIView转换为图像的扩展

extension UIView {
    func asImage() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
}

扩展以调整UIImage的大小

extension UIImage {
    func resized(to size: CGSize) -> UIImage? {
        let canvasSize = CGSize(width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(origin: .zero, size: canvasSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

0 个答案:

没有答案