android 通過網絡圖片路徑查看圖片

1.在項目清單中添加網絡訪問權限

<!--訪問網絡的權限-->
<uses-permission android:name="android.permission.INTERNET"/>
2.獲取網絡圖片數據

/**
	 * 獲取網絡圖片的數據
	 * @param path 網絡圖片路徑
	 * @return
	 * @throws Exception 
	 */
	public static byte[] getImage(String path) throws Exception {
		URL url=new URL(path);
		HttpURLConnection conn=(HttpURLConnection)url.openConnection();//得到基於HTTP協議的連接對象
		conn.setConnectTimeout(5000);//設置超時時間
		conn.setRequestMethod("GET");//請求方式
		if(conn.getResponseCode()==200){//判斷是否請求成功
			InputStream inputStream=conn.getInputStream();
			return read(inputStream);
		}
		return null;
	}
	/**
	 * 讀取流中的數據
	 */
	public static byte[] read(InputStream inputStream) throws IOException {
		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
		byte[] b=new byte[1024];
		int len=0;
		while((len=inputStream.read(b))!=-1){
			outputStream.write(b);
		}
		inputStream.close();
		return outputStream.toByteArray();
	}
3.處理查看圖片的控制

public class NetimageActivity extends Activity {
	private EditText pathText;
	private ImageView imageView;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        pathText=(EditText)this.findViewById(R.id.imagepath);//圖片路徑
        imageView=(ImageView)this.findViewById(R.id.imageView);//顯示圖片控件
        Button button=(Button)this.findViewById(R.id.button);//查看圖片按鈕
        button.setOnClickListener(new ButtonClickListener());//註冊查看圖片按鈕事件
    }
    /**
     * 處理查看圖片按鈕事件
     */
    private final class ButtonClickListener implements View.OnClickListener{
    	@Override
    	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();
			}
    	}
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章