获取网络图片

来源:互联网 发布:常熟市东张镇淘宝地址 编辑:程序博客网 时间:2024/06/05 11:39
<img src="http://img.blog.csdn.net/20150703195239222?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" width="300" height="500" alt="" />
1.访问网络要注意加上访问权限
<uses-permission android:name="android.permission.INTERNET"/>
2.将图片转化为流
public class MainActivity extends Activity {    private EditText etImageUrl;    private ImageView ivImage;    public static final int SHOWIMAGE=1;    private Handler handler=new Handler(){    public void handleMessage(android.os.Message msg) {    switch (msg.what) {case SHOWIMAGE:Bitmap bitmap=(Bitmap) msg.obj;ivImage.setImageBitmap(bitmap);break;default:break;}    };    };

3.主要代码

public void viewImage(View view){final String imageUrl=etImageUrl.getText().toString();if(TextUtils.isEmpty(imageUrl)){Toast.makeText(this, "图片路径不能为空", Toast.LENGTH_LONG).show();}else{new Thread(){public void run() {try {URL url=new URL(imageUrl);HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();    httpURLConnection.setRequestMethod("GET");    httpURLConnection.setConnectTimeout(5000);    int responseCode=httpURLConnection.getResponseCode();    if(responseCode==200){    InputStream inputStream=httpURLConnection.getInputStream();    Bitmap bitmap=BitmapFactory.decodeStream(inputStream);    Message message=new Message();    message.what=SHOWIMAGE;    message.obj=bitmap;    //ivImage.setImageBitmap(bitmap);    handler.sendMessage(message);    }else{    Toast.makeText(MainActivity.this, "显示图片失败", Toast.LENGTH_LONG).show();    }} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}.start();}}}


0 0
原创粉丝点击