简体   繁体   English

从 web 获取图像并将其保存到手机 memory?

[英]Get image from web and save it to phones memory ?

I need to get image from the web and store it in the phone for later use.我需要从 web 获取图像并将其存储在手机中以备后用。

I tryed this:我试过这个:

 public Drawable grabImageFromUrl(String url) throws Exception
    {
     return Drawable.createFromStream((InputStream)new URL(url).getContent(), "src");
    }

So this my function to grab image from Url, i just need a proccess to get the returned drawable and save.所以我的 function 从 Url 抓取图像,我只需要一个过程来获取返回的可绘制对象并保存。

How can i do that?我怎样才能做到这一点?

Based off here , you can actually download the image using a different method.基于此处,您实际上可以使用不同的方法下载图像。 Is it absolutely necessary that you store it as a drawable before saving it?在保存之前将其存储为可绘制对象是否绝对必要? Because I think you could save it first, and THEN open it, if need be.因为我认为您可以先保存它,然后在需要时打开它。

URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
    //The sdcard directory e.g. '/sdcard' can be used directly, or 
    //more safely abstracted with getExternalStorageDirectory()
    String storagePath = Environment.getExternalStorageDirectory();
    OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
    try {
        byte[] buffer = new byte[aReasonableSize];
        int bytesRead = 0;
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
            output.write(buffer, 0, bytesRead);
        }
    } finally {
        output.close();
    }
} finally {
    input.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM