0

I have an app that generates ImageViews. I added a button to download it but I don't know how to make it. Already looked everywhere but I couldn't find anything. Can you help me. I want to download the imageview to gallery when button pressed.

  • 1
    Does this answer your question? [Saving and Reading Bitmaps/Images from Internal memory in Android](https://stackoverflow.com/questions/17674634/saving-and-reading-bitmaps-images-from-internal-memory-in-android) – Omar Shawky Oct 05 '21 at 18:40
  • @OmarShawky No, because I am getting the Image from ImageView. –  Oct 05 '21 at 18:49
  • well it would be the same if you used `Bitmap bitmap = imageView.getDrawable().getBitmap();`, that would get you the bitmap to continue the previously proposed question. - https://stackoverflow.com/q/26865787/10485156 – Omar Shawky Oct 05 '21 at 18:54
  • @OmarShawky .getBitmap() gives error when I make it. –  Oct 05 '21 at 19:00

1 Answers1

0

This is what you want :

//saveToGalleryButton is the id of the button that you will click to save the image to gallery
saveToGalleryButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View _view) {
        try {
            java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(path));
//path is a String file path where your image will be saved
//for example : "/storage/emulated/0/DCIM/your image.jpg"
((android.graphics.drawable.BitmapDrawable)yourImageView.getDrawable()).getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, fos);
//yourImageView is the id of ImageView that you want to get the image from
            fos.flush().close();
        } catch (Exception e){
            //to do something with the exception
        } }
}
});

Edit : Don't forget to add this to your AndroidManifest.xml file :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Omar Hemaia
  • 188
  • 10
  • .close() is giving error and when i delete it, its not working. –  Oct 06 '21 at 14:35
  • This code works fine with me, so I don't think that the problem is from the code itself. Try to add the permission in AndroidManifest file using this : – Omar Hemaia Oct 06 '21 at 15:49
  • What do you write in path? Program gives exception. @OmarHemaia –  Oct 06 '21 at 16:04
  • path is a String that determinants where will the image be saved, you can write something like this : "/storage/emulated/0/"+String.valueOf((long)(System.currentTimeMillis()))+".jpg" – Omar Hemaia Oct 06 '21 at 21:02