How to resize NSImage?

前端 未结 10 1700
萌比男神i
萌比男神i 2020-12-02 21:21

I have an NSBitmapImageRep which is WxH size.

I create NSImage and call addRepresentation:. Then I n

10条回答
  •  余生分开走
    2020-12-02 21:46

    EDIT You can resize image using below function:

    - (NSImage *)imageResize:(NSImage*)anImage
             newSize:(NSSize)newSize 
    {
     NSImage *sourceImage = anImage;
     [sourceImage setScalesWhenResized:YES];
    
     // Report an error if the source isn't a valid image
     if (![sourceImage isValid])
     {
        NSLog(@"Invalid Image");
     } else
     {
        NSImage *smallImage = [[[NSImage alloc] initWithSize: newSize] autorelease];
        [smallImage lockFocus];
        [sourceImage setSize: newSize];
        [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
        [sourceImage compositeToPoint:NSZeroPoint operation:NSCompositeCopy];
        [smallImage unlockFocus];
        return smallImage;
     }
     return nil;
    }
    

    Secondly like this:

    NSData *imageData = [yourImg  TIFFRepresentation]; // converting img into data
    NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData]; // converting into BitmapImageRep 
    NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.9] forKey:NSImageCompressionFactor]; // any number betwwen 0 to 1
    imageData = [imageRep representationUsingType:NSJPEGFileType properties:imageProps]; // use NSPNGFileType if needed
    NSImage *resizedImage = [[NSImage alloc] initWithData:imageData]; // image created from data
    

提交回复
热议问题