简体   繁体   中英

UIImage Resize with aspect ratio -> SAVE JPG -> LOAD -> image loaded twice bigger

im using this code to resize image.

- (UIImage*)resizeToSize:(CGSize)size {

float height    = self.size.height;
float width     = self.size.width;


if (width > size.width) {
    width   = size.width;
    height  = size.width / (self.size.width / self.size.height);
}

if (height > size.height) {
    height  = size.height;
    width   = size.height / (self.size.height / self.size.width);
}

NSLog(@"Resize to size %@",NSStringFromCGSize(size));

if (height == self.size.height && width == self.size.width) {
    return self;
}    
CGSize newSize = CGSizeMake(width, height);

UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.0);

[self drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSLog(@"Resized %@",NSStringFromCGSize(newImage.size));
return newImage;
}

The image is resized and in next step i save it via [UIImageJPEGRepresentation(image, 1.0) writeToFile:pngPath atomically:YES];.

After that i load the file, and the image size is twice bigger, any hint why?

Thank you!

I suspect what is happening here is that you have an image with scale 2.0 (on a Retina device) but you are saving it without @2x in the filename, so when you reopen it, it is a scale 1.0 image with dimensions twice as large as you want.

If that's the case, there are two solutions: you can fix your filename, or you can re-open the file by reading the file into an NSData object and then use UIImage +imageWithData:scale: to get a properly-scaled image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM