Quellcode durchsuchen

Merge branch 'master' of http://git.qmth.com.cn/ExamCloud-2/examcloud-core-questions

weiwenhai vor 7 Jahren
Ursprung
Commit
484627e1f4

+ 15 - 6
examcloud-core-questions-base/src/main/java/cn/com/qmth/examcloud/core/questions/base/ImageUtils.java

@@ -16,12 +16,11 @@ public class ImageUtils {
     private static final String TAG_IMG = "img";
     private static final String UNIT = "px";
     private static final int MAX_WIDTH = 350;
-    private static final int MAX_HEIGHT = 300;
     private static final String STYLE_WIDTH = "width:%spx;";
     private static final String STYLE_HEIGHT = "height:%spx;";
 
     /**
-     * 如果图片尺寸过大,则限制图片最大宽度高度
+     * 如果图片尺寸过大,则按比例缩放图片的宽度高度
      */
     public static String reSizeImg(String html) {
         if (html == null) {
@@ -37,16 +36,18 @@ public class ImageUtils {
             element.removeAttr("height");
             String widthStr = "";
             String heightStr = "";
+            boolean isOutWidth = false;
             if (width > 0) {
                 if (width > MAX_WIDTH) {
+                    isOutWidth = true;
                     widthStr = String.format(STYLE_WIDTH, MAX_WIDTH);
                 } else {
                     widthStr = String.format(STYLE_WIDTH, width);
                 }
             }
             if (height > 0) {
-                if (height > MAX_HEIGHT) {
-                    heightStr = String.format(STYLE_HEIGHT, MAX_HEIGHT);
+                if (isOutWidth) {
+                    heightStr = String.format(STYLE_HEIGHT, calculateHeight(width, height, MAX_WIDTH));
                 } else {
                     heightStr = String.format(STYLE_HEIGHT, height);
                 }
@@ -58,6 +59,14 @@ public class ImageUtils {
         return bodyHtml;
     }
 
+    public static int calculateHeight(int oldWidth, int oldHeight, int newWidth) {
+        if (oldWidth == 0) {
+            return 0;
+        }
+        int newHeight = (newWidth * oldHeight) / oldWidth;
+        return newHeight;
+    }
+
     public static int parseValue(String styleValue, String attrName) {
         if (styleValue == null || "".equals(styleValue)) {
             return 0;
@@ -95,8 +104,8 @@ public class ImageUtils {
     }
 
     public static void main(String[] args) {
-        String html = "<p><IMG src=\"abc\" style=\"width: 500PX; height:500PX;\"/><img src=\"xyz\" style=\"width:300px;\"/></p>";
-        ImageUtils.reSizeImg(html);
+        String html = "<p><IMG src=\"abc\" style=\"width: 600PX; height:300PX;\"/><img src=\"xyz\" style=\"width:300px;\"/></p>";
+        System.out.println(ImageUtils.reSizeImg(html));
     }
 
 }