Method to store an image on the SD card - Android Hardware

Android examples for Hardware:SD Card

Description

Method to store an image on the SD card

Demo Code


//package com.java2s;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.graphics.Bitmap.CompressFormat;
import android.media.MediaScannerConnection;
import android.os.Environment;

public class Main {
    /**//from   www  .jav  a  2s .co  m
     * Method to store an image on the SD card
     * 
     * @param imageData
     * @param quality
     * @return
     */
    public static boolean StoreByteImage(Bitmap image, int quality,
            Context ctx) {

        File sdImageMainDirectory = Environment
                .getExternalStorageDirectory();
        File cuttingDirectoy = new File(sdImageMainDirectory.getPath()
                + "/cuttingRoom/");
        cuttingDirectoy.mkdirs();

        FileOutputStream fileOutputStream = null;
        String fileName = "/IMG_CUT_" + UUID.randomUUID().toString()
                + ".jpg";
        try {

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;

            fileOutputStream = new FileOutputStream(
                    cuttingDirectoy.toString() + fileName);

            BufferedOutputStream bos = new BufferedOutputStream(
                    fileOutputStream);

            image.compress(CompressFormat.JPEG, 100, bos);

            bos.flush();
            bos.close();

            String[] paths = new String[1];
            paths[0] = cuttingDirectoy.toString() + fileName;
            //start media scanner to send pic to gallery
            MediaScannerConnection.scanFile(ctx, paths, null, null);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

Related Tutorials