怎么获取网络图片呢? android 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 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; } } 基本上和获取源码差不多,注意图片的格式,用相应的函数转换下就好! |
|