Saturday, April 5, 2014

Save & Display image in Gallery in Android

Save & Display image in Gallery

This method can use any where in your save image.
Just call  this image and pass params image name and Bitmap,
Then after,call this method addImageToGallery(file path, mcontex);
  
public static String saveImage(String image_name, Bitmap image_) {
        FileOutputStream image = null;
        // External sdcard location
        File mediaStorageDir = new File(
                Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "Your dir");
        File mediaStorageDir = new File(
                Environment.getExternalStorageDirectory()
                        + "/Pictures/Your dir");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {   
                mediaStorageDir.mkdir();               
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        mediaFile = new File(
                          mediaStorageDir, ""
                      + image_name + timeStamp  + ".png");
        try {        
            image = new FileOutputStream(mediaFile);
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        image_.compress(CompressFormat.PNG, 100, image);
        return mediaFile.getPath();
    }



public static void addImageToGallery(final String filePath, final Context context) {
        ContentValues values = new ContentValues();
        values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATA, filePath);
        context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
    }