如何从android中的url获取位图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11831188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:59:01  来源:igfitidea点击:

How to get bitmap from a url in android?

android

提问by Chandra Sekhar

I have a uri like which has an image

我有一个像 uri 这样的图像

file:///mnt/...............

How to use this uri to get the image but it returns null, please tell me where i am wrong.

如何使用这个uri获取图像但它返回null,请告诉我我错在哪里。

Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath());
Bitmap bitmap = BitmapFactory.decodeFile(uri.toString());

回答by brthornbury

This is a simple one line way to do it:

这是一种简单的单行方式:

    try {
        URL url = new URL("http://....");
        Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    } catch(IOException e) {
        System.out.println(e);
    }

回答by Luke Taylor

This should do the trick:

这应该可以解决问题:

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
} // Author: silentnuke

Don't forget to add the internet permission in your manifest.

不要忘记在清单中添加互联网权限。

回答by brthornbury

Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:

好的,所以您正在尝试从文件中获取位图?标题表示 URL。无论如何,当您从 Android 中的外部存储获取文件时,您永远不应该使用直接路径。而是像这样调用 getExternalStorageDirectory() :

File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);

getExternalStorageDirectory() gives you the path to the SD card. Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.

getExternalStorageDirectory() 为您提供 SD 卡的路径。您还需要在 Manifest 中声明 WRITE_EXTERNAL_STORAGE 权限。