Android - Saving a downloaded image from URL onto SD card

前端 未结 2 1136
遥遥无期
遥遥无期 2020-12-30 15:21

I am loading an image from an URL on button click, and storing it as a Bitmap. Now i want to know how to save that downloaded image into sd card as well as in system.

<
相关标签:
2条回答
  • 2020-12-30 16:00

    You will need to first create the directories and sub-directories where you want to create the files. I see that you used the mkdir() method. Try mkdirs(), and it should work.

    0 讨论(0)
  • 2020-12-30 16:02

    Add WRITE_EXTERNAL_STORAGE android permission in your Manifest:

    Then

    BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
    Bitmap bitmap = drawable.getBitmap();
    

    Get to directory (a File object) from SD Card such as:

    File sdCardDirectory = Environment.getExternalStorageDirectory();
    

    Create your specific file for image storage:

    File image = new File(sdCardDirectory, "download.png");
    

    Then,

    boolean success = false;
    
    // Encode the file as a PNG image.
    FileOutputStream outStream;
    try {
    
        outStream = new FileOutputStream(image);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
        /* 100 to keep full quality of the image */
    
        outStream.flush();
        outStream.close();
        success = true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    if (success) {
        //Display Downloaded
    } else {
       // display Error in Downloading
    }
    
    0 讨论(0)
提交回复
热议问题