尝试调整NSImage的大小变成NSData [英] Trying to resize an NSImage which turns into NSData
问题描述
我有一个NSImage我试图调整大小这样;
I have an NSImage which I am trying to resize like so;
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将解决这个问题,但它没有。
My first issue is that my image gets squashed when I try to resize it and don't conform to the aspect ratio. I read that using -setScalesWhenResized would resolve this problem but it didn't.
我的第二个问题是,当我尝试将图像写入文件时,图像实际上没有调整大小。
My second issue is that when I try to write the image to a file, the image isn't actually resized at all.
提前感谢,
Ricky。
Thanks in advance, Ricky.
推荐答案
我发现这篇博文非常有帮助调整图片大小: http://weblog.scifihifi.com/2005/ 06/25 / how-to-resize-an-nsimage /
I found this blog post to be very helpful for resizing my image: http://weblog.scifihifi.com/2005/06/25/how-to-resize-an-nsimage/
您需要在图片上强制显示长宽比,为你做。这是我在尝试将图像放入默认纸张上的可打印区域时的方法:
You will need to enforce the aspect ratio on the image resizing yourself, it won't be done for you. This is how I did it when I was trying to fit the image into the printable area on the default paper:
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);
这是他的博客中稍微修改的代码版本:
Here is a slightly modified version of his code from the blog:
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];
这篇关于尝试调整NSImage的大小变成NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!