我想在内存中创建一个位图,设置一些像素值,然后将该图像保存到磁盘。
到目前为止,我有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 :(得分: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];