Save PNG image with background color - Android Graphics

Android examples for Graphics:PNG Image

Description

Save PNG image with background color

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.graphics.Bitmap;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;

public class Main {

    public static boolean saveBitmapPNGWithBackgroundColor(
            String strFileName, Bitmap bitmap, int nBackgroundColor) {
        boolean bSuccess1 = false;
        boolean bSuccess2 = false;
        boolean bSuccess3;
        File saveFile = new File(strFileName);

        if (saveFile.exists()) {
            if (!saveFile.delete())
                return false;
        }/*from   www  . j av  a 2s  .  co m*/

        int nA = (nBackgroundColor >> 24) & 0xff;

        if (nA == 0)
            nBackgroundColor = 0xFFFFFFFF;

        Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(nBackgroundColor);
        canvas.drawBitmap(bitmap, rect, rect, new Paint());

        OutputStream out = null;

        try {
            bSuccess1 = saveFile.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        try {
            out = new FileOutputStream(saveFile);
            bSuccess2 = newBitmap.compress(CompressFormat.PNG, 100, out);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (out != null) {
                out.flush();
                out.close();
                bSuccess3 = true;
            } else
                bSuccess3 = false;

        } catch (IOException e) {
            e.printStackTrace();
            bSuccess3 = false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return (bSuccess1 && bSuccess2 && bSuccess3);
    }
}

Related Tutorials