How to save a bitmap image with imageview onclick

2019-01-14 20:24发布

问题:

Am developing a coloring of images in android. So after applying colors to my image when i click another imageview like save, then i have to save that image to gallery.

回答1:

To get Bitmap from imageView:

imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();

To save it in a file:

OutputStream fOut = null;
Uri outputFileUri;
try {
    File root = new File(Environment.getExternalStorageDirectory()
        + File.separator + "folder_name" + File.separator);
    root.mkdirs();
    File sdImageMainDirectory = new File(root, "myPicName.jpg");
    outputFileUri = Uri.fromFile(sdImageMainDirectory);
    fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
    Toast.makeText(this, "Error occured. Please try again later.",
    Toast.LENGTH_SHORT).show();
}
try {
    bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
    fOut.flush();
    fOut.close();
} catch (Exception e) {
}


回答2:

You have to

  1. Save the image to your persistent storage.
  2. Add an entry to the MediaStore content provider.

First one can be achieved using the following code:

FileOutputStream out = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);

Second,

MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, imagePath, name, description);


回答3:

First get the drawingCache(bitmap) of the imageView and then save the bitmap to the SDCard.

File folder = new File(Environment.getExternalStorageDirectory()+"/folder/"); if(!folder.exists()) folderAppointment.mkdirs();

try {
    this.setDrawingCacheEnabled(true);
    FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/folder/file"));
    Bitmap bitmap = YOUR_IMAGE_VIEW.getDrawingCache();
    bitmap.compress(CompressFormat.JPEG, 100, fos);
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}