尝试调整 NSImage 的大小,使其变成 NSData

2024-03-09

我有一个 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 可以解决这个问题,但事实并非如此。

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

提前致谢, 瑞奇。


我发现这篇博文对于调整图像大小非常有帮助:http://weblog.scifihifi.com/2005/06/25/how-to-resize-an-nsimage/ 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];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试调整 NSImage 的大小,使其变成 NSData 的相关文章

随机推荐