使用URL设置ImageView

问题描述 投票:1回答:4

我的服务器上有一个图像。图像的URL类似于:http://www.mydomain.com/123456uploaded_image.jpg

我正在尝试将此图像设置为我的ImageView。这是我试过的代码:

    try{
            String url1 = myeventimagearray[position];
            URL ulrn = new URL(url1);
            HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
            InputStream is = (InputStream) con.getInputStream();
            Bitmap bmp = BitmapFactory.decodeStream(is);
            if (null != bmp)
                iveventimg.setImageBitmap(bmp);
            else
                Log.i("Image","Not set");

        } catch(Exception e) {
            e.printStackTrace();
        }

当我尝试这个时,我的imageview是空的,即它没有设置图像视图,我在我的logcat中得到这个系统错误:

java.lang.ClassCastException:libcore.net.http.FixedLengthInputStream无法强制转换为com.example.eventnotifier.Base64 $ InputStream

Base46.java是我从互联网上找到的一个文件,它对Base64表示法进行编码和解码。

知道为什么我得到这个System.error?

谢谢

android imageview base64 android-imageview bitmapimage
4个回答
1
投票

使用URlImageViewHelper,它将负责将url加载到imageview中。

Refer this

它将自己处理缓存,加载背景等。


0
投票

这不是一个简单的答案,但您应该使用缓存系统。

请参阅https://github.com/chrisbanes/Android-BitmapCache一个优秀的!

只需将ImageView换成NetworkCacheableImageView,然后使用loadImage( "http://....", true );


0
投票

您可能会遇到异常,因为您正在尝试在主线程上执行网络io。考虑使用加载程序或AsyncTask来加载图像。

检查你的日志,我打赌你在自动生成的catch块中打印堆栈跟踪。

 new Thread(new Runnable() {
   public void run() {
     final Bitmap b = bitmap = BitmapFactory.decodeStream((InputStream)new URL(myeventimagearray[position]).getContent());
     iveventimg.post(new Runnable() {
       public void run() {
         iveventimg.setImageBitmap(b);
       }
    });
  }
}).start();

0
投票

使用毕加索从网址获取图片。在'com.squareup.picasso:picasso:2.71828'和java中实现build.gradle

Picasso.get()
  .load(url) // http://www.example.com/123456uploaded_image.jpg
  .resize(50, 50)
  .centerCrop()
  .into(imageView)
© www.soinside.com 2019 - 2024. All rights reserved.