0

I tried to save an image from an ImageView into the gallery. I tried it like this:

Bitmap bitmap = imageView.getDrawingCache();  

MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "" , "");

But it won't work :/ No errong, nothing :/ Can someone help me?

Phil
  • 23
  • 5
  • there is a good sample here http://stackoverflow.com/questions/9078715/how-to-save-a-bitmap-image-with-imageview-onclick –  Jun 26 '13 at 17:50
  • Mhm it just saves it to the sd card, not that I can see it in the gallery and the file is created but you can't view the picture :/ – Phil Jun 26 '13 at 18:20
  • Check [this](http://stackoverflow.com/questions/19462213/android-save-images-to-internal-storage/38904356#38904356). I have given the solution. Hope this helps! – Shravan DG Aug 11 '16 at 19:31

1 Answers1

0

Try this:

FileOutputStream fos= null;
File file = getDisc();
if(!file.exists() && !file.mkdirs()) {
    //Toast.makeText(this, "Can't create directory to store image", Toast.LENGTH_LONG).show();
    //return;
    print("file not created");
    return;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmsshhmmss");
String date = simpleDateFormat.format(new Date());
String name = "FileName"+date+".jpg";
String file_name = file.getAbsolutePath()+"/"+name;
File new_file = new File(file_name);
print("new_file created");
try {
    fos= new FileOutputStream(new_file);
    Bitmap bitmap = viewToBitmap(iv, iv.getWidth(), iv.getHeight() );
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    Toast.makeText(this, "Save success", Toast.LENGTH_LONG).show();
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    print("FNF");
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
refreshGallery(new_file);

Helpers:

public void refreshGallery(File file){
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}

private File getDisc(){
String t= getCurrentDateAndTime();
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(file, "ImageDemo");
}

private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;

public static Bitmap viewToBitmap(View view, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Shravan DG
  • 527
  • 1
  • 5
  • 16