Android Bitmap Save writeToFile(Bitmap bitmap, String filePath, int quality)

Here you can find the source of writeToFile(Bitmap bitmap, String filePath, int quality)

Description

write To File

Declaration

public static void writeToFile(Bitmap bitmap, String filePath,
        int quality) 

Method Source Code

//package com.java2s;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.graphics.Matrix;

import java.io.File;
import java.io.FileOutputStream;

public class Main {

    public static void writeToFile(Bitmap bitmap, String filePath,
            int quality) {
        File f = new File(filePath);
        FileOutputStream fOut = null;
        try {/*  w ww .  ja  va  2 s  . co  m*/
            f.createNewFile();
            fOut = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Bitmap compress(String filePath, int width, int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

        int bmpWidth = options.outWidth;
        int bmpHeight = options.outHeight;

        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(filePath, options);

        float scaleWidth = bmpWidth;
        float scaleHeight = bmpHeight;

        //????????
        if (bmpWidth > width) {
            scaleWidth = width / scaleWidth;
        } else {
            scaleWidth = 1;
        }

        //????????
        if (bmpHeight > height) {
            scaleHeight = height / scaleHeight;
        } else {
            scaleHeight = 1;
        }

        Matrix matrix = new Matrix();

        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth,
                bmpHeight, matrix, false);

        //????scaleWidth?scaleHeight??1???,????????,createBitmap???????bitmap.
        //?????????bitmap,??????bitmap???,????????????bitmap??????.
        if (bitmap != resizeBitmap) {
            bitmap.recycle();
        }
        return resizeBitmap;
    }
}

Related

  1. saveBitmapToPath(Context ctxt, String path, String filename, Bitmap bm)
  2. saveJPEGBitmap(Bitmap bmp, String path)
  3. saveJpegFile(String fileName, Bitmap bitmap)
  4. savePNGBitmap(Bitmap bmp, String path)
  5. storeBitmapToFile(Bitmap bitmap, String filePath)