Android 通过网络图片路径查看图片实例详解
Android通过网络图片路径查看图片实例详解
1.在项目清单中添加网络访问权限
2.获取网络图片数据
/**
*获取网络图片的数据
*@parampath网络图片路径
*@return
*@throwsException
*/
publicstaticbyte[]getImage(Stringpath)throwsException{
URLurl=newURL(path);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();//得到基于HTTP协议的连接对象
conn.setConnectTimeout(5000);//设置超时时间
conn.setRequestMethod("GET");//请求方式
if(conn.getResponseCode()==200){//判断是否请求成功
InputStreaminputStream=conn.getInputStream();
returnread(inputStream);
}
returnnull;
}
/**
*读取流中的数据
*/
publicstaticbyte[]read(InputStreaminputStream)throwsIOException{
ByteArrayOutputStreamoutputStream=newByteArrayOutputStream();
byte[]b=newbyte[1024];
intlen=0;
while((len=inputStream.read(b))!=-1){
outputStream.write(b);
}
inputStream.close();
returnoutputStream.toByteArray();
}
3.处理查看图片的控制
publicclassNetimageActivityextendsActivity{
privateEditTextpathText;
privateImageViewimageView;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pathText=(EditText)this.findViewById(R.id.imagepath);//图片路径
imageView=(ImageView)this.findViewById(R.id.imageView);//显示图片控件
Buttonbutton=(Button)this.findViewById(R.id.button);//查看图片按钮
button.setOnClickListener(newButtonClickListener());//注册查看图片按钮事件
}
/**
*处理查看图片按钮事件
*/
privatefinalclassButtonClickListenerimplementsView.OnClickListener{
@Override
publicvoidonClick(Viewv){
//取得图片路径
Stringpath=pathText.getText().toString();
try{
//获取图片数据
byte[]data=ImageService.getImage(path);
//使用数组的所有数据构建位图对象
Bitmapbitmap=BitmapFactory.decodeByteArray(data,0,data.length);
imageView.setImageBitmap(bitmap);//显示图片
}catch(Exceptione){
e.printStackTrace();
Toast.makeText(getApplicationContext(),R.string.error,1).show();
}
}
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!