读取网络上的图片

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class mainActivity extends Activity {
    ImageView iv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        iv = (ImageView) findViewById(R.id.iv1);
        iv.setImageBitmap(GetNetBitmap("http://10.0.2.2:8080/dem/tuya_color_003_01.png"));
    }

    private Bitmap GetNetBitmap(String url) {
        URL imageUrl = null;
        Bitmap bitmap = null;
        try {
            imageUrl = new URL(url);
        }
        catch(Exception e) {
            Log.e("", e.getMessage());
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setDoInput(true);
            // 连接
            conn.connect();
            // 将请求转换为InputStream
            InputStream is = conn.getInputStream();
            // 把InputStream转换为BitMap
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        }
        catch(Exception e) {
            Log.e("", e.getMessage());
        }
        return bitmap;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(exception,网络,String,null,url)