save picture byte data to file - Android Media

Android examples for Media:Picture

Description

save picture byte data to file

Demo Code


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

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;

import android.graphics.Paint;

public class Main {
    /**//ww  w.  jav  a2 s.  c o m
     * save picture byte data to file
     * 
     * @param dir
     *            directory name
     * @param name
     *            file name
     * @param data
     *            picture data
     * @throws IOException
     */
    public static void saveToFile(File dir, String name, byte[] data)
            throws IOException {
        File photo = new File(dir, name);
        FileOutputStream fos = new FileOutputStream(photo);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
        bm = convertToGrayscale(bm);
        bm.compress(CompressFormat.JPEG, 50, bos);
        bos.close();
        fos.flush();
        fos.close();
    }

    /**
     * save bitmap to file
     * 
     * @param dir
     *            directory name
     * @param name
     *            file name
     * @param bitmap
     *            picture
     * @throws IOException
     */
    public static void saveToFile(File dir, String name, Bitmap bitmap)
            throws IOException {
        File photo = new File(dir, name);
        FileOutputStream fos = new FileOutputStream(photo);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bitmap.compress(CompressFormat.JPEG, 90, bos);
        bos.close();
        fos.flush();
        fos.close();
    }

    /**
     * convert bitmap to grey scale
     * 
     * @param bm
     *            bitmap we want to convert
     * @return bitmap in greyscale
     */
    public static Bitmap convertToGrayscale(Bitmap bm) {
        Bitmap result = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(),
                Bitmap.Config.RGB_565);
        Canvas c = new Canvas(result);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bm, 0, 0, paint);
        bm.recycle();
        return result;
    }
}

Related Tutorials