在base64字符串编码方面,tiffRepresentation和bitmapRepresentation之间的区别?

时间:2018-02-08 21:11:01

标签: 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真的很重要吗?

1 个答案:

答案 0 :(得分:2)

TIFF和PNG是两种不同的图像格式。 base 64的使用与你的问题无关。

首先确定您需要哪种图像格式(这取决于您对结果的处理方式。一旦您确定是否需要将图像表示为PNG或TIFF(或JPEG或任何其他支持的格式),那么您将base64编码应用于该数据。