Search code examples
androidimagecordovabase64transparency

android cordova-plugin-camera adds black background on PNG


Tested on: Android 4.2 & Android 5.1.1

Plugin: https://github.com/apache/cordova-plugin-camera

When we import a PNG with an alpha (transparent) layer from library it adds a black background automatically.

Do you know how to replace that black background to a white one in base64 string returned by the plugin?

Code used:

var options = {
                        quality: 95,
                        destinationType: Camera.DestinationType.DATA_URL,
                        sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
                        allowEdit: true,
                        encodingType: Camera.EncodingType.PNG,
                        saveToPhotoAlbum: false
                    };

Solution

  • I found a way to do it reading Android Bitmap: Convert transparent pixels to a color

    Then applied to our code you have to update CameraLauncher.java:

    Add libs to edit:

    import android.graphics.Canvas; 
    import android.graphics.Color; 
    

    Then add around line 595 (if you have added the two imports) this code taken and adapted from the other thread:

    Bitmap imageWithBG = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),bitmap.getConfig());  // Create another image the same size
    imageWithBG.eraseColor(Color.WHITE);  // set its background to white, or whatever color you want
    Canvas canvas = new Canvas(imageWithBG);  // create a canvas to draw on the new image
    canvas.drawBitmap(bitmap, 0f, 0f, null); // draw old image on the background
    bitmap.recycle();  // clear out old image
    bitmap = imageWithBG;
    

    I made a pull request, maybe it will be integrated in next updates.