ImageUtils { public static String compressImage(final String path, int mode) { if (FileUtil.getFileSuffix(new File(path)).equals("gif")) { return path; } if (mode == ZipMode.Original) { return path; } int quality = 80; float maxSize = 720; switch (mode) { case ZipMode.Low: quality = 80; maxSize = 720; break; case ZipMode.Medium: quality = 95; maxSize = 1280; break; case ZipMode.High: quality = 100; maxSize = 1280; break; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); final int outWidth = options.outWidth; final int outHeight = options.outHeight; final int halfHeight = outHeight / 2; final int halfWidth = outWidth / 2; int sample = 1; while (halfWidth / sample > maxSize && halfHeight / sample > maxSize) { sample *= 2; } if (outWidth > maxSize && outHeight > maxSize) { options.inJustDecodeBounds = false; options.inSampleSize = sample; Bitmap finalBitmap = BitmapFactory.decodeFile(path, options); if (mode != ZipMode.High) { int finalWidth = finalBitmap.getWidth(); int finalHeight = finalBitmap.getHeight(); float scale = (finalWidth < finalHeight) ? maxSize / finalWidth : maxSize / finalHeight; if (scale > 1) { scale = 1; } Matrix matrix = new Matrix(); matrix.setScale(scale, scale); finalBitmap = Bitmap.createBitmap(finalBitmap, 0, 0, finalWidth, finalHeight, matrix, false); } String parentPath; File pFile = null; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { pFile = App.getApp().getExternalCacheDir(); } if (pFile == null) { pFile = App.getApp().getCacheDir(); } parentPath = pFile.getAbsolutePath(); String cachePath = new File(parentPath, System.currentTimeMillis() + ".jpg").getAbsolutePath(); FileOutputStream outputStream = null; boolean ok = false; try { outputStream = new FileOutputStream(cachePath); finalBitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream); outputStream.flush(); ok = true; } catch (IOException e) { ok = false; } finally { try { if (outputStream != null) { outputStream.close(); } } catch (Exception e) { ErrorUtils.onException(e); } } if (ok) { return cachePath; } else { return path; } } else { return path; } }  static String compressImage(final String path, int mode); static String compressImage(String path); static Bitmap convertImgRound(Bitmap bitmap, int strokeColor, float strokeWidth,
            boolean isCircle); @Nullable static Point getImageFileScale(File imageFile); static DisplayImageOptions defaultImageOptions; static DisplayImageOptions articleTitleImageOptions; static DisplayImageOptions bigAvatarOptions; static DisplayImageOptions avatarOptions; static DisplayImageOptions downloadOptions; }
@Test public void compressImage() throws Exception { try { String str = new Markdown4jProcessor().process("#test\n" + "\n" + "- 1\n" + "- 2\n" + "\n" + "> sss\n\n" + "ds\n" + " [](http: " ![](http: System.out.println(str); } catch (IOException e) { e.printStackTrace(); } }