NSImage到Base64字符串质量下降 [英] NSImage to Base64 string loses quality

查看:60
本文介绍了NSImage到Base64字符串质量下降的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将NSImage从NSImageView转换为Base64字符串,但最终在解码输出时会损失一半的质量.

I'm trying to convert an NSImage from an NSImageView to a Base64 string but end up losing half the quality when decoding the output.

要转换为Base64的代码似乎足够简单,我已将其放入NSString扩展中:

The code to convert to Base64 seems straightforward enough which I've put into an NSString extension:

extension NSImage {

    func base64String() -> String? {
        guard
            let bits = self.representations.first as? NSBitmapImageRep,
            let data = bits.representation(using: .JPEG, properties: [:])
        else {
            return nil
        }

        return "data:image/jpeg;base64,\(data.base64EncodedString())"
    }
}

尝试将39KB的测试JPG图像解码回20KB.我尝试使用在线工具转换相同的图像,并获得完美的编码->解码.

Trying that with a test JPG image that's 39KB gets decoded back to 20KB. I've tried converting the same image using online tools and get a perfect encode -> decode.

我尝试过的其他代码:

func base64String() -> String? {
    let cgImgRef = self.cgImage(forProposedRect: nil, context: nil, hints: nil)
    let bmpImgRef = NSBitmapImageRep(cgImage: cgImgRef!)
    let data = bmpImgRef.representation(using: NSBitmapImageFileType.JPEG, properties: [:])!
    return "data:image/jpeg;base64,\(data.base64EncodedString())"
}

这将产生一个17KB的文件.

Which results in a 17KB file.

由于我已经花了数小时来绞尽脑汁,任何帮助都将不胜感激.

Any help would be very much appreciated as I've racked my brain with this for hours.

推荐答案

根据文档 NSBitmapImageRep 呈现图像.您的代码似乎再次将图像重新编码为 jpeg .由于 jpeg 是一种模糊的算法,因此会导致质量下降.您可以尝试:

According to the documentation, NSBitmapImageRep renders the image. Your code seems to re-encode the image as jpeg again. As jpeg is a loosy algorithm, this will result in loss of quality. You can try to:

  • 使用 png 作为表示形式
  • jpeg 使用高(或1.0)压缩系数.
  • use png as representation
  • use a high (or 1.0) compression factor for jpeg.

这篇关于NSImage到Base64字符串质量下降的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆