Add support for PNG compression on iOS (#43)

This commit is contained in:
Luke Fanning 2016-09-12 18:57:49 +01:00 committed by Florian Rival
parent 1f4514937b
commit 9b3d0fd29b
3 changed files with 24 additions and 7 deletions

View File

@ -40,7 +40,7 @@ Option | Description
path | Path of image
maxWidth | Image max width (ratio is preserved)
maxHeight | Image max height (ratio is preserved)
compressFormat | Can be either JPEG, PNG (android only) or WEBP (android only).
compressFormat | Can be either JPEG, PNG or WEBP (android only).
quality | A number between 0 and 100. Used for the JPEG compression.
rotation | Rotation to apply to the image, in degrees, for android only. On iOS, the resizing is done such that the orientation is always up.
outputPath | The resized image path. If null, resized image will be stored in cache folder. To set outputPath make sure to add option for rotation too (if no rotation is needed, just set it to 0).

View File

@ -4,12 +4,12 @@ import {
export default {
createResizedImage: (path, width, height, format, quality, rotation = 0, outputPath) => {
if (format !== 'JPEG') {
throw new Error('Only JPEG format is supported by createResizedImage');
if (format !== 'JPEG' && format !== 'PNG') {
throw new Error('Only JPEG and PNG format are supported by createResizedImage');
}
return new Promise((resolve, reject) => {
NativeModules.ImageResizer.createResizedImage(path, width, height, quality, outputPath, (err, resizedPath) => {
NativeModules.ImageResizer.createResizedImage(path, width, height, format, quality, outputPath, (err, resizedPath) => {
if (err) {
return reject(err);
}

View File

@ -15,11 +15,22 @@
RCT_EXPORT_MODULE();
void saveImage(NSString * fullPath, UIImage * image, float quality)
bool saveImage(NSString * fullPath, UIImage * image, NSString * format, float quality)
{
NSData* data = UIImageJPEGRepresentation(image, quality / 100.0);
NSData* data = nil;
if ([format isEqualToString:@"JPEG"]) {
data = UIImageJPEGRepresentation(image, quality / 100.0);
} else if ([format isEqualToString:@"PNG"]) {
data = UIImagePNGRepresentation(image);
}
if (data == nil) {
return NO;
}
NSFileManager* fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
return YES;
}
NSString * generateFilePath(NSString * ext, NSString * outputPath)
@ -43,6 +54,7 @@ NSString * generateFilePath(NSString * ext, NSString * outputPath)
RCT_EXPORT_METHOD(createResizedImage:(NSString *)path
width:(float)width
height:(float)height
format:(NSString *)format
quality:(float)quality
outputPath:(NSString *)outputPath
callback:(RCTResponseSenderBlock)callback)
@ -71,7 +83,12 @@ RCT_EXPORT_METHOD(createResizedImage:(NSString *)path
return;
}
saveImage(fullPath, scaledImage, quality);
// Compress and save the image
if (!saveImage(fullPath, scaledImage, format, quality)) {
callback(@[@"Can't save the image. Check your compression format.", @""]);
return;
}
callback(@[[NSNull null], fullPath]);
}];
}