我有一些大小的文件(例如1000x1000)。
我想加载它并使其变小
UIImage *newImage = [UIImage imageWithCGImage:[UIImage imageWithContentsOfFile:filename].CGImage scale:(1.0f / scale) orientation:UIImageOrientationUp];
NSLog(newImage size: %f, %f", newImage.size.width, newImage.size.height);
// shows correct scaled size -> 50, 50
然后我想保存这个缩放的图像
NSData* imageData = UIImageJPEGRepresentation(newImage, 1.0);
[imageData writeToFile:otherFileName atomically:NO];
我很困惑地看到新图像以第一个起始大小(1000x1000)保存。
怎么可能以及如何做到这一点?
答案 0 :(得分:2)
只需制作一种方法:
-(UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize {
float width = newSize.width;
float height = newSize.height;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect: CGRectMake(0, 0, width, height)];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return smallImage;
}
并设置所需的大小:
UIImage *resizedImg = [self scaleImage:[UIImage imageWithData:imageData] toSize:CGSizeMake(150.0f,150.0f)]; // i have taken 150 you can change value here
答案 1 :(得分:1)
您可以使用Bellow方法创建具有较小尺寸的图像,并使用Bellow方法: -
您可以调用以下方法: -
newImage=[self scaleImage:newImage toSize:CGSizeMake(250, 250)];
- (UIImage*) scaleImage:(UIImage*)image toSize:(CGSize)newSize {
CGSize scaledSize = newSize;
float scaleFactor = 2.0;
if( image.size.width > image.size.height ) {
scaleFactor = image.size.width / image.size.height;
scaledSize.width = newSize.width;
scaledSize.height = newSize.height / scaleFactor;
}
else {
scaleFactor = image.size.height / image.size.width;
scaledSize.height = newSize.height;
scaledSize.width = newSize.width / scaleFactor;
}
UIGraphicsBeginImageContextWithOptions( scaledSize, NO, 0.0 );
CGRect scaledImageRect = CGRectMake( 0.0, 0.0, scaledSize.width, scaledSize.height );
[image drawInRect:scaledImageRect];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}