2010-12-08 57 views
0

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

到目前为止,我有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]; 

从此代码保存的图像实际上是空的,只显示几个左上角的像素。我不确定车轮在哪里脱落,但似乎很明显我以错误的方式出去了?

回答

0

我不知道究竟是什么不对您的样品,但我会处理这个问题是这样的:

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]; 
+0

我会试试这个。有没有办法在不使用填充操作的情况下打印单个像素?我确信这种方法会有开销。 – Nippysaurus 2010-12-09 01:50:16