图片二次采样
2017-10-25 18:58
148 查看
/* img即你要获得图片的控件 path即你要从网络上获取的图片 destHight你要采样的图片高度 deWeight你要采样的图片宽度 */ private void loadImage( ImageView img, String path, final int destHight, final int destWeight) { new AsyncTask<String, Void, Bitmap>() { @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); if (bitmap != null) img.setImageBitmap(bitmap); else img.setImageResource(R.mipmap.ic_launcher); } @Override protected Bitmap doInBackground(String... params) { try { String path = params[0]; URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); int code = connection.getResponseCode(); if (code == 200) { //得到图片数据 InputStream is = connection.getInputStream(); //BitmapFactory.decodeStream(is);//ARGB_888 一个像素占 4个字节 ARGB_565 一个像素占 2 个字节 Alpha Red、Green、Blue(颜色) BitmapFactory.Options options = new BitmapFactory.Options(); //在图片真正解析之前,不要解析图片数据,只需要告诉一下转换器,只要获取图片的像素(宽高) options.inJustDecodeBounds = true;//告诉BitmapFactory转换工厂不去真正解析图片只需要拿到图片宽高就行 //假解析 API 有bug BitmapFactory.decodeStream(is, null, options); //压缩,根据图片采样率进行二次采样 100 * 100 是你所期望的具体图片尺寸 //options.inSampleSize = 2; //采样用来计算图片的宽高(1920 * 1080 -> 1920 / 2 1080 / 2) //获取图片宽高,注意:图片的原始宽高 int width = options.outWidth; int height = options.outHeight; System.out.println("宽:" + width + "高 : " + height); //定义一个变量去记住我们采样率 int inSampleSize = 1;//默认是1 ,即不对图片进行任何压缩 if (width > destWeight || height > destHight) { int halfWidth = width / 2; int halfHeight = height / 2; while ((halfWidth / inSampleSize) >= destWeight && (halfHeight / inSampleSize) >= destHight) { //计算采样率 inSampleSize *= 2; } } //采样率改变了 options.inSampleSize = inSampleSize;// 8 //图片压缩完之后,放行图片解析 options.inJustDecodeBounds = false;//告诉图片转换工厂,可以解析图片了 //关闭之前的流 is.close(); //重新再去得到当前这张图片的字节流数据 is = url.openStream(); //开始解析图片 Bitmap bitmap = BitmapFactory.decodeStream(is, null, options); //关闭流 is.close(); // Bitmap bitmap = BitmapFactory.decodeStream(is); return bitmap; } } catch (Exception e) { e.printStackTrace(); } return null; } }.execute(path); } 使用:直接在需要的地方直接调用就可以了
相关文章推荐
- 图片的二次采样
- 图片的二次采样
- 图片的压缩(二次采样)
- Android BitmapFactory图片压缩处理(大位图二次采样压缩处理)
- Android内存优化图片二次采样
- 图片二次采样
- 图片二次采样工具类
- 图片的三级缓存和二次采样使用的案例
- Android_Bitmap_图片的二次采样并生成缩略图
- 图片的二次采样
- 图片的二次采样
- 安卓代码实现图片二次采样
- 图片的二次采样
- 图片压缩大全及二次采样
- Bitmap的图片二次采样
- Android_Bitmap_图片的二次采样并生成缩略图
- 图片的二次采样
- 网络地址图片二次采样(HttpURLConnection)
- Android_Bitmap_图片的二次采样并生成缩略图
- 图片(Bitmap)二次采样、图片内存计算