首页 > 其他 > 详细

获取网上图片压缩显示

时间:2014-02-13 00:33:03      阅读:419      评论:0      收藏:0      [点我收藏+]

从网上获取图片并显示比较容易,只需要通过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;
	}


获取网上图片压缩显示

原文:http://blog.csdn.net/fireworkburn/article/details/19120443

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!