保存在文档目录中时,调整后的图像宽度和高度不相同

Resized width and height of image is not same when saved in documents directory

我正在使用这些方法

调整图像大小并将其保存到 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 dimension8.6 mb in size

我的 720 x 480 dimension image B from gallery 通过我的方法调整大小为 <UIImage: 0x12ea9a360> size {720, 480} orientation 0 scale 3.000000 但保存为 2160 × 1440 dimension123 kb in size

为什么图片尺寸超出了我的方法计算的尺寸,我想以调整后的尺寸保存图片。

如何实现?

这是预期的行为。您调整大小后的图像的 scale 为 3。3 乘以 2048 x 931 为 6144∼∼∼2793。

如果您不希望调整后的图片的 scale 为 3,您为什么说

UIGraphicsBeginImageContextWithOptions(ratio, NO, 0);

??您在三倍分辨率屏幕上 运行,因此您获得了三倍分辨率图像。如果那不是你想要的,你应该说

UIGraphicsBeginImageContextWithOptions(ratio, NO, 1);