swift - tiffRepresentation 和 bitmapRepresentation 在 Base64 字符串编码方面的区别?

标签 swift cocoa bitmap base64 nsimage

我正在尝试将 NSImage 转换为 base64 字符串编码。

extension NSImage{
    // Convert NSImage self to a string of base64 encoding
    func getBase64String() -> String{
        guard let tiffData = self.tiffRepresentation else {
            printError("Failed to get tiffRepresentation")
            exit(-1)
        }
        guard let bitmap: NSBitmapImageRep = NSBitmapImageRep(data: tiffData) else {
            printError("Failed to get Bitmap representation from tiffRepresentation")
            exit(-1)
        }
        guard let data = bitmap.representation(using: .png, properties: [:]) else {
            printError("Failed to make image data with PNG type")
            exit(-1)
        }
        let tiff_base64 = "data:image/png;base64,"  + tiffData.base64EncodedString()
        let bitmap_base64 = "data:image/png;base64,"  + data.base64EncodedString()
        return bitmap_base64
    }
}

我使用结果将图像嵌入到 html 文件中,我发现 tiff_base64bitmap_base64 都可以工作。但是,同一图像的字符串看起来有些不同。

tiff_base64 bitmap_base64

Stack Overflow 上许多将图像转换为 base64 的示例都是从位图数据调用 base64EncodedString()。我想知道使用 tiff_base64bitmap_base64 真的很重要吗?

最佳答案

TIFF 和 PNG 是两种不同的图像格式。使用 Base 64 与您的问题确实无关。

首先决定您需要哪种图像格式(这取决于您对结果执行的操作。一旦您决定是否需要将图像表示为 PNG 或 TIFF(或 JPEG 或任何其他支持的格式),则可以应用该数据的 Base64 编码。

关于swift - tiffRepresentation 和 bitmapRepresentation 在 Base64 字符串编码方面的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48694846/

相关文章:

android - 为什么会为此位图抛出空指针异常?

swift - 未使用选择器操作调用函数

cocoa - 核心数据和线程

c++ - 在 Cocoa/Objective-C 项目中包含 C++ 代码时出现未知类型名称 'class'

android - 如何将缩略图保存为 JPEG 文件?

android - 无法显示网址图片(位图)

swift - Swift 3 中的 UIView isKindOfClass

ios - Swift 中的 appearanceWhenContainedIn

swift - 在 Swift 中使用选择器有什么理由吗?

macos - 创建具有 Retina 背景支持的 dmg?