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

Swift: Image size is increasing after writing that image to folder even after compressing the image

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

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

为什么会这样?如果有人能帮忙解释一下,我将不胜感激。

找了一整天,我找到了这个场景的答案。

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图片