gpt4 book ai didi

objective-c - 如何压缩和缩小 NSImage?

转载 作者:行者123 更新时间:2023-12-03 16:24:00 24 4
gpt4 key购买 nike

这是我的压缩代码

NSBitmapImageRep* tmpRep = [[_image representations] objectAtIndex:0];
[tmpRep setPixelsWide:512];
[tmpRep setPixelsHigh:512];
[tmpRep setSize:NSMakeSize(SmallThumbnailWidth, SmallThumbnailHeight)];
NSDictionary* imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.3] forKey:NSImageCompressionFactor];
NSData* outputImageData = [tmpRep
representationUsingType:NSJPEGFileType properties:imageProps];
NSString* imageFilePath = [NSString stringWithFormat:@"%@/thumbnail.jpg",imagePath];
[outputImageData writeToFile:imageFilePath atomically:YES];

原图大小是960*960,我想把原图压缩成512*512,但是我在finder中查看输出图片的大小是960*960,位置大小与原图相比确实有很大差距被压缩了。有人能告诉我为什么吗?谢谢

最佳答案

试试这个:

这将减少保存的大小(以 kbs 为单位):

-(NSImage *)imageCompressedByFactor:(float)factor{
NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithData:[self TIFFRepresentation]];
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:factor] forKey:NSImageCompressionFactor];
NSData *compressedData = [imageRep representationUsingType:NSJPEGFileType properties:options];
return [[NSImage alloc] initWithData:compressedData];
}

这将减少文件大小(以像素为单位):复制自 here

@implementation NSImage (ProportionalScaling)

- (NSImage*)imageByScalingProportionallyToSize:(NSSize)targetSize{
NSImage* sourceImage = self;
NSImage* newImage = nil;

if ([sourceImage isValid]){
NSSize imageSize = [sourceImage 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 ) == NO )
{

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;
[sourceImage drawInRect: thumbnailRect
fromRect: NSZeroRect
operation: NSCompositeSourceOver
fraction: 1.0];
[newImage unlockFocus];
}
return [newImage autorelease];
}
@end

关于objective-c - 如何压缩和缩小 NSImage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15475525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com