compress Bitmap To File - Android Graphics

Android examples for Graphics:Bitmap File

Description

compress Bitmap To File

Demo Code


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

import android.graphics.Bitmap;

import android.graphics.Bitmap.CompressFormat;

public class Main {

    public static File compressBitmapToFile(Bitmap originalBitmap,
            String path, int quality) {
        File file = new File(path);
        File filePath = file.getParentFile();
        if (!filePath.exists()) {
            filePath.mkdirs();//from   w  w  w  .j  a v a 2 s. com
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        originalBitmap.compress(CompressFormat.JPEG, quality, baos);
        byte[] imageData = baos.toByteArray();
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(imageData);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (originalBitmap != null && !originalBitmap.isRecycled()) {
            originalBitmap.recycle();
        }
        return file;
    }
}

Related Tutorials