获取网上图片压缩显示

从网上获取图片并显示比较容易,只需要通过http获取输入流,然后解码输入流即可,但是有些图片还是比较大,在解码显示之前需要压缩,

压缩方式都一样,计算设置采样率大小即可;

但是在获取图片宽高的时候会先读取一次图片数据,采用流的话这次已经把数据读走了,所以在后面再真正解码图片的时候始终是null;

解决办法就是将输入流转为字节数组保存下来,对这个数组进行操作,问题得到解决,模块代码如下:

public static Bitmap decodeNetWork(String fileUrl, int width, int height)
	{
		if(fileUrl == null || !fileUrl.startsWith(Constant.HTTP_TAG))
			return null;
		
		URL url = null;
		try
		{
			url = new URL(fileUrl);
		} catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		HttpURLConnection conn = null;
		InputStream inputStream = null;
		Bitmap bm1 = null;
		try
		{
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true); 
			conn.connect(); 
			inputStream = conn.getInputStream(); 
			
			final BitmapFactory.Options options = new BitmapFactory.Options();
			/*只加载基础信息,并不真正解码图片*/
			options.inJustDecodeBounds = true;
			
			byte[] data = MyFileUtils.getBytes(inputStream);
			bm1 = BitmapFactory.decodeByteArray(data, 0, data.length, options);
			if (options.outWidth < 1 || options.outHeight < 1) 
			{
				return null;
			}
			int[] size = calculateSize(options.outWidth, options.outHeight, width, height);
			/*计算缩放率*/
			options.inSampleSize = getSampleSize(options, size[0], size[1]);
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = false;
			
			bm1 = BitmapFactory.decodeByteArray(data, 0, data.length, options);
			conn.disconnect();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (OutOfMemoryError e) 
		{
		}
		
		try
		{
			if(inputStream != null)
				inputStream.close();
		} 
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bm1;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值