NSI映像到Base64

时间:2009-06-01 13:58:20

标签: cocoa base64

我需要创建一个NSImage可可对象的base64字符串表示。处理这个问题的最佳方法是什么,苹果文档似乎在这个主题上有点简短(或者我无法找到它)。从外部看,Base64编码看起来相当复杂。

非常感谢任何帮助。

干杯 亚历

修改

NSArray *keys = [NSArray arrayWithObject:@"NSImageCompressionFactor"];
NSArray *objects = [NSArray arrayWithObject:@"1.0"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSImage *image = [[NSImage alloc] initWithContentsOfFile:[imageField stringValue]];
NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithData:[image TIFFRepresentation]];
NSData *tiff_data = [imageRep representationUsingType:NSPNGFileType properties:dictionary];

NSString *base64 = [tiff_data encodeBase64WithNewlines:NO];

6 个答案:

答案 0 :(得分:4)

NSImage是一个非常抽象的对象。 NSImage并不关心它是光栅图像还是矢量图像; NSImage对象甚至可以同时具有栅格,矢量,甚至编程表示 - 这是一般的。

在生成Base64数据之前,您必须决定要编码的

第一步是决定是否要对栅格或矢量进行编码。前者很简单,我猜它可能就是你的意思。但是,NSImage可能来自矢量源,例如PDF文档。

如果您知道从光栅源创建了图像,则可以只编码该源数据。

如果它来自矢量源,你仍然可以编码,如果你知道解码端的应用程序将能够处理它(例如,如果它是另一个Cocoa或Cocoa Touch应用程序)。另一方面,如果解码端的app可能无法处理矢量数据,那么你应该避免这种策略。

适用于所有情况的解决方案是使用图片的NSBitmapImageRepcreate a raster capture。将焦点锁定在图像上,然后使用该方法创建NSBitmapImageRep,然后解锁焦点。然后,使用representationUsingType:properties:生成图像的PNG(或任何适当的格式)数据。然后Base64编码PNG(或任何格式)数据。

答案 1 :(得分:2)

Apple在此处没有提供任何特别的帮助,因此您必须以某种方式解决自身的复杂性。

幸运的是,有一些资源可以让这更容易。第一种方法是自己进行编码和解码。 Google Toolbox for Mac就是这种方法的一个很好的例子,您可以按原样使用此源文件:

http://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/GTMBase64.m

如果你只为可以使用OpenSSH库的Mac构建,那么你可以利用这些库中的一些函数来进行编码和解码:

http://www.dribin.org/dave/blog/archives/2006/03/12/base64_cocoa/

答案 2 :(得分:2)

我有一堆代码,包括my toolkit on github中基于OmniFoundation实现的Base64解析。特别是,请查看Extensions / NSData + Base64.h。

答案 3 :(得分:1)

这是一个Swift 2扩展,用于将NSImage转换为base64字符串:

private extension NSImage {
    var base64String:String? {
    guard let rep = NSBitmapImageRep(
        bitmapDataPlanes: nil,
        pixelsWide: Int(size.width),
        pixelsHigh: Int(size.height),
        bitsPerSample: 8,
        samplesPerPixel: 4,
        hasAlpha: true,
        isPlanar: false,
        colorSpaceName: NSDeviceRGBColorSpace,
        bytesPerRow: 0,
        bitsPerPixel: 0
        ) else {
            print("Couldn't create bitmap representation")
            return nil
    }

    NSGraphicsContext.saveGraphicsState()
    NSGraphicsContext.setCurrentContext(NSGraphicsContext(bitmapImageRep: rep))
    drawAtPoint(NSZeroPoint, fromRect: NSZeroRect, operation: .CompositeSourceOver, fraction: 1.0)
    NSGraphicsContext.restoreGraphicsState()

    guard let data = rep.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [NSImageCompressionFactor: 1.0]) else {
        print("Couldn't create PNG")
        return nil
    }
    return data.base64EncodedStringWithOptions([])
}
}

答案 4 :(得分:1)

Swift 3

choices

答案 5 :(得分:1)

快捷键4

extension NSImage {
    var base64String: String? {
        guard let rep = NSBitmapImageRep(
            bitmapDataPlanes: nil,
            pixelsWide: Int(size.width),
            pixelsHigh: Int(size.height),
            bitsPerSample: 8,
            samplesPerPixel: 4,
            hasAlpha: true,
            isPlanar: false,
            colorSpaceName: .calibratedRGB,
            bytesPerRow: 0,
            bitsPerPixel: 0
            ) else {
                print("Couldn't create bitmap representation")
                return nil
        }

        NSGraphicsContext.saveGraphicsState()
        NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
        draw(at: NSZeroPoint, from: NSZeroRect, operation: .sourceOver, fraction: 1.0)
        NSGraphicsContext.restoreGraphicsState()

        guard let data = rep.representation(using: NSBitmapImageRep.FileType.png, properties: [NSBitmapImageRep.PropertyKey.compressionFactor: 1.0]) else {
            print("Couldn't create PNG")
            return nil
        }

        // With prefix
        // return "data:image/png;base64,\(data.base64EncodedString(options: []))" 
        // Without prefix
        return data.base64EncodedString(options: []))
    }
}