分享

获取网页图片

 IceCivet 2014-10-31
怎么获取网络图片呢?   0.0
android  4.4版本
P.s  清单文件中,要加入网络访问权限。

public class MainActivity extends ActionBarActivity {
private ImageView show;
private EditText edit;
private final int LOAD_SUCCESS=1;
private final int LOAD_ERROR=-1;
private  Handler handler=new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case LOAD_SUCCESS:
show.setImageBitmap((Bitmap) msg.obj);
break;
case LOAD_ERROR:
Toast.makeText(getApplicationContext(), R.string.error, 1).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bn=(Button) findViewById(R.id.bn);
edit=(EditText)findViewById(R.id.imagePath);
show=(ImageView)findViewById(R.id.image);
}
public void show(View view){
new Thread(new Runnable(){
public void run(){
try {
byte []data=getPic();
Bitmap bitMap=BitmapFactory.decodeByteArray(data, 0, data.length);
Message msg=new Message();
msg.what=LOAD_SUCCESS;
msg.obj=bitMap;
handler.sendMessage(msg);
} catch (Exception e) {
handler.sendEmptyMessage(LOAD_ERROR);
e.printStackTrace();
}
}
}).start();
}
protected byte[] getPic() throws Exception{
String path=edit.getText().toString();
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection(); // 基于HTTP协议的连接对象
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){ // 状态码判断是否请求成功
InputStream is=conn.getInputStream(); //输入流对象接受来自网络的数据,但一定是正确的数据。
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
byte []buffer=new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){
outStream.write(buffer);
}
is.close();
outStream.close();
return outStream.toByteArray();
}
return null;
}
}

基本上和获取源码差不多,注意图片的格式,用相应的函数转换下就好!  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多