Swift:将图像写入文件夹后,即使压缩图像,图像大小仍在增加

时间:2019-01-04 09:32:56

标签: ios swift uiimagepickercontroller nsfilemanager

我要将从“照片”中拾取的图像保存在“文档”文件夹中。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    guard let selectedImage = info[.originalImage] as? UIImage else {
        fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
    }
    selectedImage.jpegData(compressionQuality: 0.0).fileSize() //Printing size as 4284217 bytes|4.3 MB
    if let imageData = selectedImage.jpeg(.lowest) {
        imageData.fileSize() //Printing size as 4284217 bytes|4.3 MB
        let compressedImage = UIImage(data: imageData)?.fixOrientation()
        saveImageInDocuments(compressedImage!)
    }
    picker.dismiss(animated: true, completion: nil)
}

选择图像并压缩到最小尺寸后,我打印了图像的尺寸。下一步是将图像保存到文档文件夹。

func saveImageInDocuments(_ image: UIImage) {
    let imageName = String(Date().toMillis())
    let fileURL = documentsDirectoryURL.appendingPathComponent("\(CUST_APP_DOC)/\(imageName).png")
    print(fileURL.path)

    if !FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            try image.pngData()!.write(to: fileURL)                
            print("Saved filename: \(imageName).png size: \(calculateFileSize(path: String(describing: fileURL)).0)")
        } catch {
            print(error)
        }
    } else {
        print("Image Not Added")
    }
}

用于获取图像大小并计算路径中保存的图像大小的方法

 func calculateFileSize(path: String) -> (String, Double) {
    let absolutePath = path.replacingOccurrences(of: "file://", with: "")
    let fileAttributes = try! FileManager.default.attributesOfItem(atPath: absolutePath)
    let fileSizeNumber = fileAttributes[FileAttributeKey.size] as! NSNumber
    let fileSize = fileSizeNumber.int64Value
    var sizeMB = Double(fileSize / 1024)
    sizeMB = Double(sizeMB / 1024)
    print(String(format: "%.2f", sizeMB) + " MB")
    return (String(format: "%.2f", sizeMB) + " MB", sizeMB)
}

extension Data {
    func fileSize() {
        let bcf = ByteCountFormatter()
        bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
        bcf.countStyle = .file
        let string = bcf.string(fromByteCount: Int64(self.count))
        print("Printing size as \(self.count) bytes|\(string) MB")
    }
}

问题是选择图像后,图像文件大小为4.3 MB,但是将图像保存在文件夹中后。图片大小即将到来“ 保存的文件名:1546593850872.png大小:29.86 MB

为什么会这样?如果有人可以帮助解释这一点,我将非常感谢该人。

1 个答案:

答案 0 :(得分:0)

搜索了整整一天之后,我找到了这种情况的答案。

didFinishPickingMediaWithInfo中,我将图像压缩为JPEG,从而减小了图像尺寸。然后,当将图像写入目录saveImageInDocuments时,我使用这一行代码将JPEG图像再次转换为PNG。

try image.pngData()!.write(to: fileURL)

将图像转换为PNG会增加其大小。

对于解决方案,我修改了此方法:

func saveImageInDocuments(_ imageData: Data) {
    let imageName = String(Date().toMillis())
    let fileURL = documentsDirectoryURL.appendingPathComponent("\(CUST_APP_DOC)/\(imageName).png")
    print(fileURL.path)

    if !FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            try imageData.write(to: fileURL)                
         } catch {
            print(error)
        }
    } else {
        print("Image Not Added")
    }
}

直接保存压缩的JPEG图像。