获取网上图片压缩显示

来源:互联网 发布:软件特征码是什么 编辑:程序博客网 时间:2024/04/30 07:00

从网上获取图片并显示比较容易,只需要通过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 blocke.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 blocke.printStackTrace();} catch (OutOfMemoryError e) {}try{if(inputStream != null)inputStream.close();} catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();}return bm1;}


0 0