Objective c 将NSBitmapImageRep另存为图像
我已经对此进行了详尽的搜索,我知道之前也有关于NSBitmapImageRep的类似问题发布过,但没有一个问题是针对我要做的事情的,即:Objective c 将NSBitmapImageRep另存为图像,objective-c,macos,nsimage,Objective C,Macos,Nsimage,我已经对此进行了详尽的搜索,我知道之前也有关于NSBitmapImageRep的类似问题发布过,但没有一个问题是针对我要做的事情的,即: 从桌面读入图像(但不显示) 创建该图像的位图表示形式 迭代像素以更改某些颜色 将修改后的位图表示保存为单独的文件 因为我以前从未使用过位图,所以我想我应该先创建并保存一个位图,然后再修改像素。这看起来很简单,但我就是不能让它工作。除了文件保存方面,大部分代码都是从StackOverflow上的另一个答案中借用的,如下所示: -(void)processBitm
-(void)processBitmapImage:(NSString*)aFilepath
{
NSImage *theImage = [[NSImage alloc] initWithContentsOfFile:aFilepath];
if (theImage)
{
CGImageRef CGImage = [theImage CGImageForProposedRect:nil context:nil hints:nil];
NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:CGImage];
NSInteger width = [imageRep pixelsWide];
NSInteger height = [imageRep pixelsHigh];
long rowBytes = [imageRep bytesPerRow];
// above matches the original size indicating NSBitmapImageRep was created successfully
printf("WIDE pix = %ld\n", width);
printf("HIGH pix = %ld\n", height);
printf("Row bytes = %ld\n", rowBytes);
// We'll worry about this part later...
/*
unsigned char* pixels = [imageRep bitmapData];
int row, col;
for (row=0; row < height; row++)
{
// etc ...
for (col=0; col < width; col++)
{
// etc...
}
}
*/
// So, let's see if we can just SAVE the (unmodified) bitmap first ...
NSData *pngData = [imageRep representationUsingType: NSPNGFileType properties: nil];
NSString *destinationStr = [self pathForDataFile];
BOOL returnVal = [pngData writeToFile:destinationStr atomically: NO];
NSLog(@"did we succeed?:%@", (returnVal ? @"YES": @"NO")); // the writeToFile call FAILS!
[imageRep release];
}
[theImage release];
}
-(void)processBitmapImage:(NSString*)文件路径
{
NSImage*theImage=[[NSImage alloc]initWithContentsOfFile:aFilepath];
如果(图像)
{
CGImageRef CGImage=[图像CGImageForProposedRect:nil上下文:nil提示:nil];
NSBitmapImageRep*imageRep=[[NSBitmapImageRep alloc]initWithCGImage:CGImage];
NSInteger宽度=[imageRep像素宽度];
NSInteger高度=[imageRep pixelsHigh];
长行字节=[imageRep bytesPerRow];
//以上匹配原始大小,表明NSBitmapImageRep已成功创建
printf(“宽像素=%ld\n”,宽度);
printf(“高像素=%ld\n”,高度);
printf(“行字节=%ld\n”,行字节);
//我们稍后会担心这部分。。。
/*
无符号字符*像素=[imageRep bitmapData];
int row,col;
用于(行=0;行<高度;行++)
{
//等等。。。
用于(列=0;列<宽度;列++)
{
//等等。。。
}
}
*/
//那么,让我们看看是否可以先保存(未修改的)位图。。。
NSData*pngData=[imageRep representationUsingType:NSPNGFileType属性:nil];
NSString*destinationStr=[self-pathForDataFile];
BOOL returnVal=[pngData writeToFile:destinationStr atomicaly:NO];
NSLog(@“我们成功了吗?”:%@,(returnVal?@“是”:@“否”);//writeToFile调用失败!
[imageRep发布];
}
[图像释放];
}
虽然我喜欢这段代码的简单性,但另一个潜在的问题可能是Apple docs建议我们将返回“initWithCGImage”的位图视为只读对象
谁能告诉我这段代码哪里出了问题,以及如何修改它以使其正常工作。虽然总体概念在我的非专家眼中看起来不错,但我怀疑我犯了一个愚蠢的错误,忽略了一些非常基本的东西。提前感谢:-)这是创建
NSBitmapImageRep
的一种相当迂回的方法。尝试这样创建它:
NSBitmapImageRep* imageRep = [NSBitmapImageRep imageRepWithContentsOfFile:aFilepath];
当然,上面的内容并没有赋予您对image rep对象的所有权,因此不要在最后发布它。啊,这是一个让事情变得更简单的好技巧。谢谢你,肯。