【问题标题】:set url image to image view [duplicate]将网址图像设置为图像视图[重复]
【发布时间】:2011-06-24 03:01:34
【问题描述】:

可能重复:
Is it possible to use BitmapFactory.decodeFile method to decode a image from http location?

我在将 url 图像设置为图像视图时遇到问题。我尝试了以下方法

方法一:

Bitmap bimage=  getBitmapFromURL(bannerpath);
image.setImageBitmap(bimage);

 public static Bitmap getBitmapFromURL(String src) {
        try {
            Log.e("src",src);
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            Log.e("Bitmap","returned");
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("Exception",e.getMessage());
            return null;
        }
    }

方法二:

    Drawable drawable = LoadImageFromWebOperations(bannerpath);
    image.setImageDrawable(drawable);

     private Drawable LoadImageFromWebOperations(String url)
    {
         try
         {
             InputStream is = (InputStream) new URL(url).getContent();
             Drawable d = Drawable.createFromStream(is, "src name");
             return d;
         }catch (Exception e) {
             System.out.println("Exc="+e);
             return null;
         }
     }

我尝试了以上两种方法,但都不起作用。两者都显示 DEBUG/skia(266): --- decoder->decode returned false 。我使用了有效的演示 url 图像路径。但这条路行不通。所以请告诉我出了什么问题,我会怎么做

提前谢谢你。

最好的问候。

【问题讨论】:

标签: android url imageview


【解决方案1】:

刚刚在我的应用中测试了您的“方法 1”,它工作得很好。

您可能在 AndroidManifest.xml 文件中忘记了这一行:

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

【讨论】:

  • 方法 1 在 ImageView 上使用 setImageBitmap(bimage) 的 INTERNET 权限可以正常工作。
  • 我的应用程序不断崩溃,出现android.os.NetworkOnMainThreadException 异常(在清单中添加了 INTERNET 权限后)。我做错了什么?
  • NetworkOnMainThreadException 不应该崩溃,它只是通知您您在 UI 线程上进行网络通信。
  • @Deminetix 这是一个例外。当然会崩溃!无论如何,这可以通过在AsyncTask 中加载图像来解决(并在onPostExecute() 中显示图像
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 2013-10-28
  • 2011-08-12
  • 2016-10-08
相关资源
最近更新 更多