How to download image and save it to gallery on an

2019-09-08 23:36发布

I get image link from the server and on click of the link it should download and save it to the gallery, I have no clue on how to do it. please help me on this, thanks in advance

2条回答
smile是对你的礼貌
2楼-- · 2019-09-08 23:47
**combine the below code to store image at a particula path**

File storagePath = new File(Environment
                    .getExternalStorageDirectory()
                    + "/com.logistics.herestethiparty/images/");
            storagePath.mkdirs();
            File file = new File(storagePath, fileImageName);    

**i have used the below code in asyncclass for image download**

    URL url = new URL(imageUrl);
                    HttpURLConnection urlConnection = (HttpURLConnection) url
                            .openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setDoOutput(true);
                    urlConnection.connect();
                    FileOutputStream fileOutput = new FileOutputStream(file);
                    InputStream inputStream = urlConnection.getInputStream();
                    int downloadedSize = 0;

                    byte[] buffer = new byte[1024];
                    int bufferLength = 0;
                    while ((bufferLength = inputStream.read(buffer)) > 0) {
                        fileOutput.write(buffer, 0, bufferLength);
                        downloadedSize += bufferLength;
                    }
                    // close the output stream when done
                    fileOutput.close();
查看更多
Viruses.
3楼-- · 2019-09-08 23:48

Try this code, Call mDownloadAndSave() method for save image on SDCard, it will solve your problem.

public void mDownloadAndSave() {
    // Setting up file to write the image to.
    File f = new File("/mnt/sdcard/img.png");

    // Open InputStream to download the image.
    InputStream is;
    try {
        is = new URL("http://www.tmonews.com/wp-content/uploads/2012/10/androidfigure.jpg").openStream();

        // Set up OutputStream to write data into image file.
        OutputStream os = new FileOutputStream(f);

        CopyStream(is, os);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static void CopyStream(InputStream is, OutputStream os) {
    final int buffer_size = 1024;
    try {
        byte[] bytes = new byte[buffer_size];
        for (;;) {
            int count = is.read(bytes, 0, buffer_size);
            if (count == -1)
            break;
            os.write(bytes, 0, count);
        }
    } catch (Exception ex) {

    }
}

And Don't forget to add below permission into Androidmanifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
查看更多
登录 后发表回答