callstack / react-native-image-editor

A library providing an API for cropping images from the web and the local file system.
MIT License
376 stars 118 forks source link

Support cropping transparent images #37

Closed TimMun closed 4 years ago

TimMun commented 4 years ago

Feature Request

Support cropping transparent images. Currently, if you crop a partially transparent image, all the transparent pixels become white.

Why it is needed

I'm upgrading my app from RN 0.59 to 0.61. The old ImageEditor bundled with RN 0.59 supported cropping transparent images.

Possible implementation

Use UIImagePNGRepresentation instead of UIImageJPEGRepresentation? Not sure about Android

Code sample

// localFilePath contains a PNG with partially transparent image. Maybe cropData can take an extra flag to use png

let cropped = await ImageEditor.cropImage(localFilePath, {usePNG: true} )

// cropped should contain a uri with the transparency preserved
jordangrant commented 3 years ago

For others that run into this. I really needed PNGs to maintain their transparency and this cropper was causing me to lose transparency.

https://github.com/react-native-community/react-native-image-editor/pull/44 I was getting nothing back for:

NSString *urlPath = [url path];
NSString *extension = [urlPath pathExtension];

and the url of the

NSURL *url = [imageRequest URL];
NSString *urlstring = url.absoluteString;

was rct-image-store://0 So it always defaulted to JPG.

I decided to force PNG. ->>>> Meaning I removed:

if([extension isEqualToString:@"png"]){
} else {
} 

in iOS/RNCImageEditor.m and user the png logic only I question if https://github.com/react-native-community/react-native-image-editor/pull/44 ever worked.

Now, my complete solution - I detect the image type (uri includes jpg, png) before passing it to the cropper, crop it and force png, then resave it with the appropriate extension to the app ~/Documents folder.

 function cropperDone(croppedImageUri) {
        let filetype = imageBeforeCrop.includes('png') ? 'png' : 'jpg';

        helpers.saveImageToDocuments(croppedImageUri, filetype).then((uri) => {
            // Continue
        });
    }