//读取本地图片如果不压缩很容易OOM //尺寸压缩 BitmapFactory.Options options = new BitmapFactory.Options(); //为true表示decodeFile时只会返回宽和高,不用加载图片 options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, 500, 500); //读取图片 options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile(path, options); if (bitmap == null) { return; } //质量压缩 ByteArrayOutputStream baos = null; baos = new ByteArrayOutputStream(); int pro = 100; // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 do { baos.reset(); bitmap.compress(Bitmap.CompressFormat.JPEG, pro, baos); pro -= 10; } while (baos.toByteArray().length / 1024 > 100); imageView.setImageBitmap(bitmap); //定义一个file,为压缩后的图片 File f = new File("图片保存路径","图片名称"); String newPath = imageView.getContext().getCacheDir().getAbsolutePath() + "/myImages.jpg"; File file = new File(newPath); //有重名文件就删除 if (file.exists()) { file.delete(); } try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } //将输出流写入到新文件 FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(baos.toByteArray()); fos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { closeStream(fos); closeStream(baos); }
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will // guarantee // a final image with both dimensions larger than or equal to the // requested height and width. inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio; } return inSampleSize; }
public static void closeStream(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } }