如何下载图像并将其保存在Android图库 [英] How to download image and save it to gallery on android

查看:157
本文介绍了如何下载图像并将其保存在Android图库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的图像链接从服务器和它应该下载并保存到库中的链接点击,我对如何做到这一点毫无头绪。请帮助我在此,先谢谢了。

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

推荐答案

试试这个code,呼叫 mDownloadAndSave()为节省SD卡图像的方法,它会解决你的问题。

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) {

    }
}

和不要忘了下面的权限加入到AndroidManifest.xml中

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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

这篇关于如何下载图像并将其保存在Android图库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆