我是cocoa的新手,我正在尝试做的是调整NSImage的大小,但看起来我做错了,因为我的图像没有调整大小。我看了看其他问题,这种方法看起来应该有效:
- (void)scaleIcons:(NSString *)outputPath{
NSImage *anImage;
NSSize imageSize;
NSString *finalPath;
anImage = [self image];
imageSize = [anImage size];
imageSize.width = 512;
imageSize.height = 512;
[anImage setSize:imageSize];
finalPath = [outputPath stringByAppendingString:@"/icon_512x512.png"];
NSData *imageData = [anImage TIFFRepresentation];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageData];
NSData *dataToWrite = [rep representationUsingType:NSPNGFileType properties:nil];
[dataToWrite writeToFile:finalPath atomically:NO];
}
一切都有效,除了我的图像没有缩放的事实。有人可以帮忙吗?
答案 0 :(得分:6)
因此,您的代码段忽略了缩放/转换图像所需的操作。在尝试保存之前,请通过此方法传递图像:
- (NSImage *)scaleImage:(NSImage *)image toSize:(NSSize)targetSize
{
if ([image isValid])
{
NSSize imageSize = [image size];
float width = imageSize.width;
float height = imageSize.height;
float targetWidth = targetSize.width;
float targetHeight = targetSize.height;
float scaleFactor = 0.0;
float scaledWidth = targetWidth;
float scaledHeight = targetHeight;
NSPoint thumbnailPoint = NSZeroPoint;
if (!NSEqualSizes(imageSize, targetSize))
{
float widthFactor = targetWidth / width;
float heightFactor = targetHeight / height;
if (widthFactor < heightFactor)
{
scaleFactor = widthFactor;
}
else
{
scaleFactor = heightFactor;
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
if (widthFactor < heightFactor)
{
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}
else if (widthFactor > heightFactor)
{
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
NSImage *newImage = [[NSImage alloc] initWithSize:targetSize];
[newImage lockFocus];
NSRect thumbnailRect;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[image drawInRect:thumbnailRect
fromRect:NSZeroRect
operation:NSCompositeSourceOver
fraction:1.0];
[newImage unlockFocus];
}
return newImage;
}
如果将其整合到现有方法中:
- (void)scaleIcons:(NSString *)outputPath{
NSSize outputSize = NSMakeSize(512.0f,512.0f);
NSImage *anImage = [self scaleImage:[self image] toSize:outputSize];
NSString *finalPath = [outputPath stringByAppendingString:@"/icon_512x512.png"];
NSData *imageData = [anImage TIFFRepresentation];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageData];
NSData *dataToWrite = [rep representationUsingType:NSPNGFileType properties:nil];
[dataToWrite writeToFile:finalPath atomically:NO];
}
答案 1 :(得分:2)
关于Parag Bafana的回答,为了调整大小,应该是“重新采样”而不是“裁剪”:
sips --resampleHeightWidth 10 10 input.png --out output.png
答案 2 :(得分:0)
您还可以使用sips
(可编写脚本的图像处理系统)命令。
sips --cropToHeightWidth 10 10 input.png --out output.png