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();
			}
    	}
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值