我正在尝试将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_base64
和bitmap_base64
都有效。但是,字符串看起来与同一图像有所不同。
在Stack Overflow上将图像转换为base64的许多示例都是从位图数据调用base64EncodedString()
。我想知道使用tiff_base64
或bitmap_base64
真的很重要吗?
答案 0 :(得分:2)
TIFF和PNG是两种不同的图像格式。 base 64的使用与你的问题无关。
首先确定您需要哪种图像格式(这取决于您对结果的处理方式。一旦您确定是否需要将图像表示为PNG或TIFF(或JPEG或任何其他支持的格式),那么您将base64编码应用于该数据。