【问题标题】:Saving NSBitmapImageRep as image将 NSBitmapImageRep 保存为图像
【发布时间】:2015-05-05 05:13:39
【问题描述】:

我已经对此进行了详尽的搜索,并且我知道之前已经发布过关于 NSBitmapImageRep 的类似问题,但它们似乎都不是针对我正在尝试做的事情,这很简单:

  1. 从桌面读取图像(但不显示)
  2. 创建该图像的 NSBitmap 表示
  3. 遍历像素以更改某些颜色
  4. 将修改后的位图表示另存为单独的文件

因为我从来没有使用过位图,所以我想我会先尝试创建并保存一个,然后再担心以后修改像素。这看起来很简单,但我只是无法让它工作。除了文件保存方面,大部分代码都是从 StackOverflow 上的另一个答案中借用的,如下所示:

-(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];
}

虽然我喜欢这段代码的简单性,但未来的另一个潜在问题可能是 Apple 文档建议我们将使用“initWithCGImage”返回的位图视为只读对象……

谁能告诉我这段代码哪里出了问题,以及如何修改它才能工作。虽然整体概念在我的非专家眼中看起来不错,但我怀疑我犯了一个愚蠢的错误并忽略了一些非常基本的东西。在此先感谢:-)

【问题讨论】:

    标签: objective-c macos nsimage


    【解决方案1】:

    这是创建NSBitmapImageRep 的一种相当迂回的方式。尝试像这样创建它:

    NSBitmapImageRep* imageRep = [NSBitmapImageRep imageRepWithContentsOfFile:aFilepath];
    

    当然,上面并没有给你图像rep对象的所有权,所以不要在最后释放它。

    【讨论】:

    • 啊,这是一个让事情变得更简单的好方法。谢谢肯。
    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 2012-07-01
    • 2021-08-01
    相关资源
    最近更新 更多