Android从URL加载图像视图

6
我正在从URL下载一张图片,但是下载完成后图片没有发生变化。 我在下面输入了代码,请问有人遇到过同样的问题吗?
Java文件
public class MyImgActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ImageView imgView =(ImageView)findViewById(R.id.imageView1);
    Drawable drawable = LoadImageFromWebOperations("http://www.gophoto.it/view.php?i=http://1.bp.blogspot.com/-2LTvCCufBKc/T3L3KgcTj2I/AAAAAAAABbQ/Ki60e1LU9sE/s1600/Sachin%2BTendulkar.png");

    imgView.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;
      }
}
}

XML文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ImageView 
    android:id="@+id/imageView1"
    android:layout_height="match_parent" 
    android:layout_width="match_parent"></ImageView>
</LinearLayout>

清单文件
<uses-permission android:name="android.permission.INTERNET"/>

2
“更改图像URL后无法显示图像”是什么意思?您能换个说法吗? - Andro Selva
你尝试加载jpg格式的图片而不是png了吗? - user948620
在Logcat中有任何异常吗?您正在使用哪个Android操作系统? - Mohsin Naeem
@M Mohsin Naeem 在 logcat 中没有显示异常。我正在使用 2.2 版本。 - Kumar
为什么不能使用 "imgView.setImageURI(yourURL);"? - Dinesh Anuruddha
显示剩余3条评论
4个回答

17
请使用以下代码下载并显示图像到ImageView中。
public class image extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Bitmap bitmap = DownloadImage("http://www.gophoto.it/view.php?i=http://1.bp.blogspot.com/-2LTvCCufBKc/T3L3KgcTj2I/AAAAAAAABbQ/Ki60e1LU9sE/s1600/Sachin%2BTendulkar.png");
        ImageView img = (ImageView) findViewById(R.id.img);
        img.setImageBitmap(bitmap);
    }

    private InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

    private Bitmap DownloadImage(String URL) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return bitmap;
    }
}

在logcat中显示此消息08-29 14:04:53.046:D / dalvikvm(132):GC_EXPLICIT在163ms中释放了743个对象/ 42080字节 08-29 14:04:58.096:D / dalvikvm(266):GC_EXPLICIT在182ms中释放了362个对象/ 19720字节 08-29 14:05:05.196:D / dalvikvm(291):GC_EXPLICIT在76ms中释放了274个对象/ 12920字节 08-29 14:09:21.957:D / SntpClient(59):请求时间失败:java.net.SocketException:协议不支持的地址族 - Kumar
@Kumar 这段代码可以在其他任何网址上运行,所以问题可能出在图片大小或者你的网址上。 - Dipak Keshariya
如果我使用这段代码,我的应用程序将会在图片加载完成之前暂停。我是对的吗?一个解决方案是在AsyncTask中运行openHttpConnection? - WitaloBenicio

3
以下代码可以使用以下URL正常工作,但是在您的URL上无法正常工作。问题出在您的图片大小上,请尝试另一个URL,它将起作用。
public class MyImgActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ImageView imgView =(ImageView)findViewById(R.id.imageView1);
        URL url = null;
        Bitmap bmp = null;
        try {
            url = new URL("http://www.seobook.com/images/smallfish.jpg");
            bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        } catch (MalformedURLException e) {

        }catch (IOException e) {

        }
       imgView.setImageBitmap(bmp); 
      }

    }

imgView.setImageURI(yourURL);中的yourURL是Uri类型,只接受Uri类型的参数。所以我将代码更改为Uri uri=Uri.parse(url);imgView.setImageURI(uri);,但仍然无法获取。 - Kumar
好的Kumar,我已经编辑了代码,它现在可以正常工作了。如果你的图片超过位图限制,它将无法显示。希望代码没有问题。你的问题在于你的图片。 - Dinesh Anuruddha

1
 try
  {

   URL murl = new URL(url)
  URLConnection ucon = murl.openConnection();
  InputStream is = ucon.getInputStream();
   Drawable d = Drawable.createFromStream(is, "src name");
   return d;
  }catch (Exception e) {
   System.out.println("Exc="+e);
   return null;
  }

在您的下载方法中使用此代码,如果连接速度较慢,请使用线程进行下载,并使用处理程序发布图像...如@Hiren所解释的那样


0

尝试以下代码,

只需将您的URL更改为,

URL

在onCreate中

new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            drawable = LoadImageFromWebOperations("http://1.bp.blogspot.com/-2LTvCCufBKc/T3L3KgcTj2I/AAAAAAAABbQ/Ki60e1LU9sE/s1600/Sachin%2BTendulkar.png");
            handler.sendEmptyMessage(0);
        }
    }).start();

使用处理程序下载图像后设置图像。
Handler handler = new Handler(){
    @Override
    public void handleMessage(android.os.Message msg) {
        imgView.setImageDrawable(drawable);
        Log.i("System out","after set the image...");
    }
};

希望能对你有所帮助...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接