app 开发中图片的加载和上传是经常使用到的,如果加载的图片过大,可能会出现oom内存溢出
这是就需要我进行图片宽高,和图片大少(质量)的压缩
public void clickPhoto(View view){ Intent intent = new Intent(); intent.setAction(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent,image_request_code); } private Bitmap ImageMassCompress(Bitmap btm){ int mass = 100; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //第一个参数是jpeg的图片格式,第二参数要压缩到的百分比100%不变,写入到一个输出流中 btm.compress(Bitmap.CompressFormat.JPEG,mass,outputStream); //指定压缩图片的大少不超过500k int targer = 500*1024; int length = outputStream.toByteArray().length; if(length > targer){ mass = length * 100 /targer;//指定压缩的百分比 } btm.compress(Bitmap.CompressFormat.JPEG,mass,outputStream); //读取输出流 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray()); //通过bitmapfactory进行解析 Bitmap bitmap = BitmapFactory.decodeStream(byteArrayInputStream); return bitmap; } private Bitmap ImageSizeCompress(Uri uri){ InputStream Stream = null; InputStream inputStream = null; try { //根据uri获取图片的流 inputStream = getContentResolver().openInputStream(uri); BitmapFactory.Options options = new BitmapFactory.Options(); //options的in系列的设置了,injustdecodebouond只解析图片的大小,而不加载到内存中去 options.inJustDecodeBounds = true; //1.如果通过options.outHeight获取图片的宽高,就必须通过decodestream解析同options赋值 //否则options.outheight获取不到宽高 BitmapFactory.decodeStream(inputStream,null,options); //2.通过 btm.getHeight()获取图片的宽高就不需要1的解析,我这里采取第一张方式 // Bitmap btm = BitmapFactory.decodeStream(inputStream); //以屏幕的宽高进行压缩 DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); int heightPixels = displayMetrics.heightPixels; int widthPixels = displayMetrics.widthPixels; //获取图片的宽高 int outHeight = options.outHeight; int outWidth = options.outWidth; //heightPixels就是要压缩后的图片高度,宽度也一样 int a = (int) Math.ceil((outHeight/(float)heightPixels)); int b = (int) Math.ceil(outWidth/(float)widthPixels); //比例计算,一般是图片比较大的情况下进行压缩 int max = Math.max(a, b); if(max > 1){ options.inSampleSize = max; } //解析到内存中去 options.inJustDecodeBounds = false; // 根据uri重新获取流,inputstream在解析中发生改变了 Stream = getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(Stream, null, options); return bitmap; } catch (Exception e) { e.printStackTrace(); }finally { try { if(inputStream != null) { inputStream.close(); } if(Stream != null){ Stream.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK){ switch (requestCode){ case image_request_code: if(data != null){ //从相册中获取到图片的路径,图片所在文件夹 Uri uri = data.getData(); Bitmap bitmap = ImageSizeCompress(uri); if(bitmap != null){ Bitmap btm = ImageMassCompress(bitmap); } } break; } } }