【问题标题】:How to get bitmap from a url in android? [duplicate]如何从android中的url获取位图? [复制]
【发布时间】:2012-08-03 14:17:47
【问题描述】:

我有一个类似图片的 uri

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

如何使用此 uri 获取图像但返回 null,请告诉我我哪里错了。

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

【问题讨论】:

  • 我的完美解决方案:val imageBitmap = Picasso.get().load(imageUrl).get()

标签: android


【解决方案1】:

这应该可以解决问题:

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

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

【讨论】:

  • 我的网址有 https 连接怎么样?
  • @LukeTaylor 这不再起作用了,它会导致应用程序崩溃。
【解决方案2】:

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

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

【讨论】:

  • 这不是单行的,因为创建你的 url 对象应该被 try-catch 包围。
  • 这个想法是一种获取位图的单行方式,因为您已经定义了一个 url。
  • url.openConnection().getInputStream() 可以简单地替换为url.openStream()
  • 这个抛出 android.os.NetworkOnMainThreadException
  • 必须是一个新的 android 功能(并且是一个很好的功能),您可以暂时尝试针对较低的 android 版本,或者将这一行放在单独的线程中。
【解决方案3】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2018-10-28
    • 2019-06-20
    • 2012-09-17
    • 2020-09-05
    • 2012-07-26
    相关资源
    最近更新 更多