【问题标题】:Resize an Image from PNG format to PNG format in cocoa dev在可可开发中将图像从PNG格式调整为PNG格式
【发布时间】:2010-07-30 16:09:45
【问题描述】:

我在可可应用程序中有这段代码,可以将 PNG 文件调整到某个尺寸,但我希望格式仍然是 PNG,但是 NSImage 没有 PNGRepresentation 方法。 我该怎么做?

NSData *sourceData = [NSData dataWithContentsOfFile:fileName];

NSImage *sourceImage = [[NSImage alloc] initWithData: sourceData];

NSSize originalSize = [sourceImage size];
float resizeWidth = originalSize.width - 10;
float resizeHeight = originalSize.height - 10;
NSImage *resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(resizeWidth, resizeHeight)];

[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, resizeWidth, resizeHeight) fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];

NSData *resizedData = [resizedImage TIFFRepresentation];
[resizedData writeToFile:@"~/playground/resized.tif" atomically:YES];
[sourceImage release];
[resizedImage release]; 

【问题讨论】:

    标签: cocoa image-processing


    【解决方案1】:

    您需要一个位图图像代表来请求它的 PNG 表示。

    当您将焦点锁定在调整大小的图像上时,创建并init a bitmap image rep with the focused “view”,传递图像的边界(原点NSZeroPoint,矩形大小 = 图像大小)。然后向那个代表询问its representation as a PNG file

    请注意,您将丢失 DPI、伽玛、颜色配置文件等属性。如果您想保留这些属性,则需要使用 Core Graphics 来完成整个工作,从读取文件开始(使用 CGImageSource)通过调整图像大小(使用CGBitmapContext)来写入新文件(使用CGImageDestination)。

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 2016-04-06
      • 1970-01-01
      • 2016-03-25
      • 2023-04-01
      • 2011-05-11
      • 2017-05-11
      • 1970-01-01
      相关资源
      最近更新 更多