开发者

cocoa render bitmap to file

I would like to create a bitmap in memory, set some of the pixel values, then save that image to disk.

So far I have the NSBitmapImageRep:

image = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
                                                pixelsWide:width
                                    开发者_高级运维        pixelsHigh:height
                                             bitsPerSample:8
                                           samplesPerPixel:4
                                                  hasAlpha:YES
                                                  isPlanar:NO
                                            colorSpaceName:NSDeviceRGBColorSpace
                                               bytesPerRow:0
                                              bitsPerPixel:0];

Then simply add some pixels like so:

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


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

And eventually save the image (as a tiff, which is not ideal but a good start)

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

The image saved from this code is actually empty and only shows a few pixels in the top left corner. I'm not sure where the wheels are coming off, but it seems obvious that I am going out this the wrong way?


I'm not sure what exactly is wrong with your sample, but I would approach the problem like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜