【问题标题】:cocoa render bitmap to file可可将位图渲染到文件
【发布时间】:2010-12-08 12:47:24
【问题描述】:

我想在内存中创建一个位图,设置一些像素值,然后将该图像保存到磁盘。

到目前为止,我有 NSBitmapImageRep:

image = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
                                                pixelsWide:width
                                            pixelsHigh:height
                                             bitsPerSample:8
                                           samplesPerPixel:4
                                                  hasAlpha:YES
                                                  isPlanar:NO
                                            colorSpaceName:NSDeviceRGBColorSpace
                                               bytesPerRow:0
                                              bitsPerPixel:0];

然后像这样简单地添加一些像素:

NSColor *color = [NSColor colorWithDeviceRed:1.0
                                       green:1.0
                                        blue:1.0
                                       alpha:1.0];


[image setColor:color
            atX:x
              y:y];

并最终保存图像(作为 tiff,这并不理想但一个好的开始)

NSData* TIFFData = [image TIFFRepresentation];
[TIFFData writeToFile:@"/temp/image.tiff" atomically:YES];

此代码保存的图像实际上是空的,仅在左上角显示几个像素。我不确定车轮从哪里脱落,但很明显我走错了路?

【问题讨论】:

    标签: cocoa bitmap


    【解决方案1】:

    我不确定您的示例到底有什么问题,但我会这样处理问题:

    NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(width, height)];
    [image lockFocus]; // All drawing commands until unlockFocus target this image.
    [[NSColor redColor] set];
    NSRectFillUsingOperation(NSMakeRect(x, y, 1, 1), NSCompositeSourceOver);
    [image unlockFocus];
    NSData *data = [image TIFFRepresentation];
    [data writeToFile:@"/temp/image.tiff" atomically:YES];
    [image release];
    

    【讨论】:

    • 我会试试这个。有没有办法在不使用填充操作的情况下打印单个像素?我确信这种方法有开销。
    • 我不这么认为。但是,如果您担心这种性能水平,“[image setColor:color atX:x y:y]”可能也会太慢。此时,您需要自己将位图图像代表的数据分配为 malloc 缓冲区,然后直接写入其中,然后从中创建图像代表并立即保存。
    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2014-12-03
    相关资源
    最近更新 更多