调整大小并保存 NSI​​mage?

发布于 2024-10-21 01:42:06 字数 136 浏览 2 评论 0原文

我有一个 NSImageView,我从 NSOpenPanel 获取图像。效果很好。

现在,我怎样才能将 NSImage 的大小减半,并将其以相同的格式保存在与原始文件相同的目录中?

如果您能提供任何帮助,我将不胜感激,谢谢。

I have an NSImageView which I get an image for from an NSOpenPanel. That works great.

Now, how can I take that NSImage, half its size and save it as the same format in the same directory as the original as well?

If you can help at all with anything I'd appreciate it, thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

顾铮苏瑾 2024-10-28 01:42:06

检查 Matt Gemmell 的 ImageCrop 示例项目:
http://mattgemmell.com/source/

很好的示例如何调整大小/裁剪图像。
最后,您可以使用类似的方法来保存结果(脏样本):

// Write to TIF
[[resultImg TIFFRepresentation] writeToFile:@"/Users/Anne/Desktop/Result.tif" atomically:YES];

// Write to JPG
NSData *imageData = [resultImg  TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.9] forKey:NSImageCompressionFactor];
imageData = [imageRep representationUsingType:NSJPEGFileType properties:imageProps];
[imageData writeToFile:@"/Users/Anne/Desktop/Result.jpg" atomically:NO];

Check the ImageCrop sample project from Matt Gemmell:
http://mattgemmell.com/source/

Nice example how to resize / crop images.
Finally you can use something like this to save the result (dirty sample):

// Write to TIF
[[resultImg TIFFRepresentation] writeToFile:@"/Users/Anne/Desktop/Result.tif" atomically:YES];

// Write to JPG
NSData *imageData = [resultImg  TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.9] forKey:NSImageCompressionFactor];
imageData = [imageRep representationUsingType:NSJPEGFileType properties:imageProps];
[imageData writeToFile:@"/Users/Anne/Desktop/Result.jpg" atomically:NO];
握住我的手 2024-10-28 01:42:06

由于 NSImage 对象是不可变的,您必须:

  1. 创建一个新图像大小的 Core Graphics 上下文。
  2. 将 NSImage 绘制到 CGContext 中。它应该会自动为您缩放。
  3. 从该上下文创建一个 NSImage
  4. 写出新的 NSImage
  5. 不要忘记释放您分配的任何临时对象。

肯定还有其他选择,但这是我想到的第一个选择。

Since NSImage objects are immutable you will have to:

  1. Create a Core Graphics context the size of the new image.
  2. Draw the NSImage into the CGContext. It should automatically scale it for you.
  3. Create an NSImage from that context
  4. Write out the new NSImage
  5. Don't forget to release any temporary objects you allocated.

There are definitely other options, but this is the first one that came to mind.

紧拥背影 2024-10-28 01:42:06
+(NSImage*) resize:(NSImage*)aImage scale:(CGFloat)aScale
{
    NSImageView* kView = [[NSImageView alloc] initWithFrame:NSMakeRect(0, 0, aImage.size.width * aScale, aImage.size.height* aScale)];
    [kView setImageScaling:NSImageScaleProportionallyUpOrDown];
    [kView setImage:aImage];

    NSRect kRect = kView.frame;
    NSBitmapImageRep* kRep = [kView bitmapImageRepForCachingDisplayInRect:kRect];
    [kView cacheDisplayInRect:kRect toBitmapImageRep:kRep];

    NSData* kData = [kRep representationUsingType:NSJPEGFileType properties:nil];
    return [[NSImage alloc] initWithData:kData];
}
+(NSImage*) resize:(NSImage*)aImage scale:(CGFloat)aScale
{
    NSImageView* kView = [[NSImageView alloc] initWithFrame:NSMakeRect(0, 0, aImage.size.width * aScale, aImage.size.height* aScale)];
    [kView setImageScaling:NSImageScaleProportionallyUpOrDown];
    [kView setImage:aImage];

    NSRect kRect = kView.frame;
    NSBitmapImageRep* kRep = [kView bitmapImageRepForCachingDisplayInRect:kRect];
    [kView cacheDisplayInRect:kRect toBitmapImageRep:kRep];

    NSData* kData = [kRep representationUsingType:NSJPEGFileType properties:nil];
    return [[NSImage alloc] initWithData:kData];
}
往事随风而去 2024-10-28 01:42:06

这是一个具体的实现

-(NSImage*)resizeImage:(NSImage*)input by:(CGFloat)factor
{    
    NSSize size = NSZeroSize;      
    size.width = input.size.width*factor;
    size.height = input.size.height*factor; 

    NSImage *ret = [[NSImage alloc] initWithSize:size];
    [ret lockFocus];
    NSAffineTransform *transform = [NSAffineTransform transform];
    [transform scaleBy:factor];  
    [transform concat]; 
    [input drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];    
    [ret unlockFocus];        

    return [ret autorelease];
}

请记住,这是基于像素的,使用 HiDPI 必须考虑缩放,很容易获得:

-(CGFloat)pixelScaling
{
    NSRect pixelBounds = [self convertRectToBacking:self.bounds];
    return pixelBounds.size.width/self.bounds.size.width;
}

Here is a specific implementation

-(NSImage*)resizeImage:(NSImage*)input by:(CGFloat)factor
{    
    NSSize size = NSZeroSize;      
    size.width = input.size.width*factor;
    size.height = input.size.height*factor; 

    NSImage *ret = [[NSImage alloc] initWithSize:size];
    [ret lockFocus];
    NSAffineTransform *transform = [NSAffineTransform transform];
    [transform scaleBy:factor];  
    [transform concat]; 
    [input drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];    
    [ret unlockFocus];        

    return [ret autorelease];
}

Keep in mind that this is pixel based, with HiDPI the scaling must be taken into account, it is simple to obtain :

-(CGFloat)pixelScaling
{
    NSRect pixelBounds = [self convertRectToBacking:self.bounds];
    return pixelBounds.size.width/self.bounds.size.width;
}
别挽留 2024-10-28 01:42:06

苹果有缩小和保存图像的源代码在这里找到
http://developer.apple.com/library/mac/ #samplecode/Reducer/Introduction/Intro.html

Apple has source code for downscaling and saving images found here
http://developer.apple.com/library/mac/#samplecode/Reducer/Introduction/Intro.html

蛮可爱 2024-10-28 01:42:06

这是一些比其他答案更广泛地使用 Core Graphics 的代码。它是根据Mark Thalman对此问题的回答中的提示制作的。

此代码根据目标图像宽度缩小NSImage。它有点令人讨厌,但作为一个额外的示例仍然很有用,用于记录如何在 CGContext 中绘制 NSImage 以及如何编写 CGBitmapContext 的内容和 CGI​​mage 到一个文件中。

您可能需要添加额外的错误检查。我的用例不需要它。

- (void)generateThumbnailForImage:(NSImage*)image atPath:(NSString*)newFilePath forWidth:(int)width
{
    CGSize size = CGSizeMake(width, image.size.height * (float)width / (float)image.size.width);
    CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();

    CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
    CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, size.width * 4, rgbColorspace, bitmapInfo);
    NSGraphicsContext * graphicsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO];
    [NSGraphicsContext setCurrentContext:graphicsContext];

    [image drawInRect:NSMakeRect(0, 0, size.width, size.height) fromRect:NSMakeRect(0, 0, image.size.width, image.size.height) operation:NSCompositeCopy fraction:1.0];

    CGImageRef outImage = CGBitmapContextCreateImage(context);
    CFURLRef outURL = (CFURLRef)[NSURL fileURLWithPath:newFilePath];
    CGImageDestinationRef outDestination = CGImageDestinationCreateWithURL(outURL, kUTTypeJPEG, 1, NULL);
    CGImageDestinationAddImage(outDestination, outImage, NULL);
    if(!CGImageDestinationFinalize(outDestination))
    {
        NSLog(@"Failed to write image to %@", newFilePath);
    }
    CFRelease(outDestination);
    CGImageRelease(outImage);
    CGContextRelease(context);
    CGColorSpaceRelease(rgbColorspace);
}

Here is some code that makes a more extensive use of Core Graphics than other answers. It's made according to hints in Mark Thalman's answer to this question.

This code downscales an NSImage based on a target image width. It's somewhat nasty, but still useful as an extra sample for documenting how to draw an NSImage in a CGContext, and how to write contents of CGBitmapContext and CGImage into a file.

You may want to add extra error checking. I didn't need it for my use case.

- (void)generateThumbnailForImage:(NSImage*)image atPath:(NSString*)newFilePath forWidth:(int)width
{
    CGSize size = CGSizeMake(width, image.size.height * (float)width / (float)image.size.width);
    CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();

    CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
    CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, size.width * 4, rgbColorspace, bitmapInfo);
    NSGraphicsContext * graphicsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO];
    [NSGraphicsContext setCurrentContext:graphicsContext];

    [image drawInRect:NSMakeRect(0, 0, size.width, size.height) fromRect:NSMakeRect(0, 0, image.size.width, image.size.height) operation:NSCompositeCopy fraction:1.0];

    CGImageRef outImage = CGBitmapContextCreateImage(context);
    CFURLRef outURL = (CFURLRef)[NSURL fileURLWithPath:newFilePath];
    CGImageDestinationRef outDestination = CGImageDestinationCreateWithURL(outURL, kUTTypeJPEG, 1, NULL);
    CGImageDestinationAddImage(outDestination, outImage, NULL);
    if(!CGImageDestinationFinalize(outDestination))
    {
        NSLog(@"Failed to write image to %@", newFilePath);
    }
    CFRelease(outDestination);
    CGImageRelease(outImage);
    CGContextRelease(context);
    CGColorSpaceRelease(rgbColorspace);
}
毅然前行 2024-10-28 01:42:06

调整图像大小

- (NSImage *)scaleImage:(NSImage *)anImage newSize:(NSSize)newSize
{
    NSImage *sourceImage = anImage;
    if ([sourceImage isValid])
    {
        if (anImage.size.width == newSize.width && anImage.size.height == newSize.height && newSize.width <= 0 && newSize.height <= 0) {
            return anImage;
        }

        NSRect oldRect = NSMakeRect(0.0, 0.0, anImage.size.width, anImage.size.height);
        NSRect newRect = NSMakeRect(0,0,newSize.width,newSize.height);
        NSImage *newImage = [[NSImage alloc] initWithSize:newSize];

        [newImage lockFocus];
        [sourceImage drawInRect:newRect fromRect:oldRect operation:NSCompositeCopy fraction:1.0];
        [newImage unlockFocus];

        return newImage;
    }
}

To resize image

- (NSImage *)scaleImage:(NSImage *)anImage newSize:(NSSize)newSize
{
    NSImage *sourceImage = anImage;
    if ([sourceImage isValid])
    {
        if (anImage.size.width == newSize.width && anImage.size.height == newSize.height && newSize.width <= 0 && newSize.height <= 0) {
            return anImage;
        }

        NSRect oldRect = NSMakeRect(0.0, 0.0, anImage.size.width, anImage.size.height);
        NSRect newRect = NSMakeRect(0,0,newSize.width,newSize.height);
        NSImage *newImage = [[NSImage alloc] initWithSize:newSize];

        [newImage lockFocus];
        [sourceImage drawInRect:newRect fromRect:oldRect operation:NSCompositeCopy fraction:1.0];
        [newImage unlockFocus];

        return newImage;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文