我正在使用此代码将大小更改为图像,然后创建一个具有新尺寸的新文件。一切正常,但它改变了图像 dpi 分辨率,我不希望这样......初始图像 dpi res 为 328,调整大小后变为 72......如何保持原始 dpi 分辨率?这是我的代码:
- (void)scaleIcons:(NSString *)outputPath :(NSURL *)nomeImmagine
{
NSImage *image = [[NSImage alloc] initWithContentsOfFile:[nomeImmagine path]];
if (!image)
image = [[NSWorkspace sharedWorkspace] iconForFile:[nomeImmagine path]];
NSSize outputSize = NSMakeSize(512.0f,512.0f);
NSImage *anImage = [self scaleImage: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];
}
- (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;
}
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;
}
任何帮助将不胜感激!谢谢... 马西