试图调整NSImage的大小,后者变成NSData

时间:2010-03-28 03:39:05

标签: cocoa nsdata nsimage

我有一个NSImage,我试图像这样调整大小;

NSImage *capturePreviewFill = [[NSImage alloc] initWithData:previewData];
NSSize newSize;
newSize.height = 160;
newSize.width = 120;
[capturePreviewFill setScalesWhenResized:YES];
[capturePreviewFill setSize:newSize];

NSData *resizedPreviewData = [capturePreviewFill TIFFRepresentation]; 
resizedCaptureImageBitmapRep = [[NSBitmapImageRep alloc] initWithData:resizedPreviewData];
saveData = [resizedCaptureImageBitmapRep representationUsingType:NSJPEGFileType properties:nil];
[saveData writeToFile:@"/Users/ricky/Desktop/Photo.jpg" atomically:YES];

我的第一个问题是,当我尝试调整大小并且不符合宽高比时,我的图像会被压扁。我读到使用-setScalesWhenResized会解决这个问题,但事实并非如此。

我的第二个问题是,当我尝试将图像写入文件时,图像实际上根本没有调整大小。

提前致谢, 瑞奇。

3 个答案:

答案 0 :(得分:10)

我发现此博客文章对于调整图片大小非常有用:http://weblog.scifihifi.com/2005/06/25/how-to-resize-an-nsimage/

您需要在自己调整大小的图像上强制执行宽高比,不会为您完成。当我试图将图像放入默认纸张上的可打印区域时,我就是这样做的:

NSImage *image = ... // get your image
NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
NSSize paperSize = printInfo.paperSize;
CGFloat usablePaperWidth = paperSize.width - printInfo.leftMargin - printInfo.rightMargin;
CGFloat resizeWidth = usablePaperWidth;
CGFloat resizeHeight = usablePaperWidth * (image.size.height / image.size.width);

以下是博客中代码的略微修改版本:

NSData *sourceData = [image TIFFRepresentation];
float resizeWidth = ... // your desired width;
float resizeHeight = ... // your desired height;

NSImage *sourceImage = [[NSImage alloc] initWithData: sourceData];
NSImage *resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(resizeWidth, resizeHeight)];

NSSize originalSize = [sourceImage size];

[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];

[sourceImage release];
[resizedImage release];

答案 1 :(得分:1)

如果您需要Mac OS X 10.6或更高版本send your image a CGImageForProposedRect:context:hints: message,请使用CGImageDestination对象写出CGImage。

矩形应以NSZeroPoint为原点,其大小应为您想要的大小。

这仍然不会按比例缩放图像(保持纵横比);你必须自己做。

答案 2 :(得分:0)

10.6之前的方法(不经过TIFF表示)是将焦点锁定在已调整大小的图像create an NSBitmapImageRep for the extent of the image上(即原点为零的矩形和图像大小),解锁焦点,然后询问位图图像代表JPEG数据。