我正在调整大小并使用这些方法将图像保存到documents directory
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
CGSize reSize = [self imageResizeCalculationWithAspectRatio:chosenImage.size];
UIImage *resizedImage = [self resizeImage:chosenImage withAspectRatio:reSize];
[picker dismissViewControllerAnimated:YES completion:NULL];
UIImageWriteToSavedPhotosAlbum(resizedImage, nil, nil, nil);
[self save:resizedImage];
}
-(CGSize)imageResizeCalculationWithAspectRatio:(CGSize)originalSize {
float maxWidth = 2048;
float maxHeight = 2048;
float ratio = 0;
float width = originalSize.width;
float height = originalSize.height;
if(width > maxWidth) {
ratio = maxWidth / width;
height = height * ratio;
width = width * ratio;
}
if(height > maxHeight) {
ratio = maxHeight / height;
width = width * ratio;
height = height * ratio;
}
return CGSizeMake(width, height);
}
- (UIImage *)resizeImage:(UIImage*)image withAspectRatio:(CGSize)ratio {
CGRect scaledRect = AVMakeRectWithAspectRatioInsideRect(image.size, CGRectMake(0, 0, ratio.width, ratio.height));
UIGraphicsBeginImageContextWithOptions(ratio, NO, 0);
[image drawInRect:scaledRect];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
-(void)save:(UIImage*)image {
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"New Folder"];
// New Folder is your folder name
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *fileName = [stringPath stringByAppendingFormat:@"/image.jpg"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
[data writeToFile:fileName atomically:YES];
}
我的11000 x 5000 dimension image A from gallery
我的方法正在调整<UIImage: 0x12ea72490> size {2048, 931} orientation 0 scale 3.000000
,但保存为6144 × 2793 dimension
和8.6 mb in size
我的720 x 480 dimension image B from gallery
我的方法正在调整<UIImage: 0x12ea9a360> size {720, 480} orientation 0 scale 3.000000
,但保存为2160 × 1440 dimension
和123 kb in size
为什么图像尺寸超出了我的方法计算的尺寸,我想将图像保存为调整尺寸的尺寸。
我怎样才能实现它?
答案 0 :(得分:2)
这是预期的行为。您调整大小的图片的scale
为3. 3倍2048 x 931为6144×2793。
如果您不希望调整后的图片的scale
为3,那么为什么要说
UIGraphicsBeginImageContextWithOptions(ratio, NO, 0);
??您在三分辨率屏幕上运行,因此您可以获得三分辨率图像。如果这不是你想要的,你应该说
UIGraphicsBeginImageContextWithOptions(ratio, NO, 1);