From e90e6b3ed6b7ca2b69018c4eba70e2eb50a5558f Mon Sep 17 00:00:00 2001 From: Adam Wong Date: Sat, 17 Aug 2024 12:43:42 +0800 Subject: [PATCH] fix: Fix image compression on iOS and make it respect to image scale factor --- ios/src/Compression.m | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/ios/src/Compression.m b/ios/src/Compression.m index 4f8e6800d..307713b28 100644 --- a/ios/src/Compression.m +++ b/ios/src/Compression.m @@ -41,25 +41,31 @@ - (ImageResult*) compressImageDimensions:(UIImage*)image CGFloat oldWidth = image.size.width; CGFloat oldHeight = image.size.height; - int newWidth = 0; - int newHeight = 0; + int width = oldWidth; + int height = oldHeight; - if (maxWidth < maxHeight) { - newWidth = maxWidth; - newHeight = (oldHeight / oldWidth) * newWidth; - } else { - newHeight = maxHeight; - newWidth = (oldWidth / oldHeight) * newHeight; + if (width > maxWidth) { + height = height * (maxWidth / width); + width = maxWidth; + } + + if (height > maxHeight) { + width = width * (maxHeight / height); + height = maxHeight; } - CGSize newSize = CGSizeMake(newWidth, newHeight); - UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:newSize]; + CGSize newSize = CGSizeMake(width, height); + + UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init]; + format.scale = image.scale; + + UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:newSize format:format]; UIImage *resizedImage = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) { [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; }]; - result.width = [NSNumber numberWithFloat:newWidth]; - result.height = [NSNumber numberWithFloat:newHeight]; + result.width = [NSNumber numberWithFloat:width]; + result.height = [NSNumber numberWithFloat:height]; result.image = resizedImage; return result; }