从网络上获取一张图片,然后显示在手机上

来源:互联网 发布:小米5突然没有网络 编辑:程序博客网 时间:2024/04/29 10:02
package com.example.netimage;

public class MainActivity extends Activity {
private EditText pathText;
private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pathText=(EditText) this.findViewById(R.id.imagepath); 
        imageView=(ImageView) this.findViewById(R.id.imageView1);
        Button button = (Button) this.findViewById(R.id.button1);       //找到按钮
        button.setOnClickListener(new ButtonOnClickListener());    //为按钮设置一个点击事件存储事件 
    }
    private final class ButtonOnClickListener implements View.OnClickListener{
public void onClick(View v) {
String path = pathText.getText().toString();    //得到图片路径
try{
byte[] data=ImageService.getImage(path);   //以字节数组来存放图片数据  , 将实现代码放到业务类中实现
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap);    //显示图片
}catch (Exception e){
e.printStackTrace();  //将例外往空台打印出来
Toast.makeText(getApplicationContext(),R.string.error,1).show();
}
}  
    }

}


package com.example.service;
public class ImageService {
/**
* 获取网络图片的数据
* @param path 网络图片路径
* @return
*/
public static byte[] getImage(String path) throws Exception{
URL url=new URL(path);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();  //得到一个基于HTTP协议连接对象
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");     //请求网络图片的方式
if(conn.getResponseCode()==200){
InputStream inStream = conn.getInputStream();    //输入流
return StreamTool.read(inStream);          //返回从流中读到的数据
}
return null;
}
}



package com.example.utils;
public class StreamTool {
/**
* 读取流中的数据
* @param inStream
* @return
* @throws Exception
*/
public static byte[] read(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = inStream.read(buffer)) !=-1){
outStream.write(buffer,0,len);
}
inStream.close();
return outStream.toByteArray();
}
}



<!-- 访问internet权限 -->
  <uses-permission android:name="android.permission.INTERNET"/>

0 0
原创粉丝点击