1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
| package top.lrshuai.util;
import cn.hutool.core.img.ImgUtil; import cn.hutool.core.io.FileUtil;
import javax.imageio.*; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.CropImageFilter; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.io.*; import java.util.List; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern;
public class ImageUtils {
public static final String FORMAT_JPG = "jpg"; public static final String FORMAT_PNG = "png"; public static final String FORMAT_GIF = "gif"; public static final String FORMAT_BMP = "bmp"; public static final float POSITION_LEFT_TOP = 0.0f; public static final float POSITION_CENTER = 0.5f; public static final float POSITION_RIGHT_BOTTOM = 1.0f; private static final int DEFAULT_WATERMARK_OFFSET = 50; private static final int DEFAULT_FONT_SIZE = 36; private static final String DEFAULT_CUT_FORMAT = FORMAT_PNG;
private static final String DEFAULT_FONT_NAME = "Serif";
private static final float DEFAULT_COMPRESS_QUALITY = 0.85f;
private static final Set<String> SUPPORTED_FORMATS = new HashSet<>(Arrays.asList("jpg", "jpeg", "png", "gif", "bmp")); private static final int DEFAULT_THUMBNAIL_SIZE = 200; private static final int DEFAULT_BORDER_WIDTH = 2; private static final Color DEFAULT_BORDER_COLOR = Color.BLACK;
private static final Pattern IMG_SRC_PATTERN = Pattern.compile( "<img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)[^>]*>", Pattern.CASE_INSENSITIVE);
public static void addImageWatermark(String watermarkImg, String targetImg, float position, float alpha) throws IOException { addImageWatermark(watermarkImg, targetImg, targetImg, position, alpha); }
public static void addImageWatermark(String watermarkImg, String targetImg, String outputImg, float position, float alpha) throws IOException { validateFileExists(targetImg, "目标图片不存在"); validateFileExists(watermarkImg, "水印图片不存在"); validateAlpha(alpha);
File targetFile = new File(targetImg); BufferedImage targetBufferedImg = ImageIO.read(targetFile); int targetWidth = targetBufferedImg.getWidth(); int targetHeight = targetBufferedImg.getHeight();
BufferedImage watermarkBufferedImg = ImageIO.read(new File(watermarkImg)); int watermarkWidth = watermarkBufferedImg.getWidth(); int watermarkHeight = watermarkBufferedImg.getHeight();
BufferedImage resultImg = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = createGraphics2D(resultImg, targetBufferedImg);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
Point watermarkPoint = calculateWatermarkPosition(position, targetWidth, targetHeight, watermarkWidth, watermarkHeight); g2d.drawImage(watermarkBufferedImg, watermarkPoint.x, watermarkPoint.y, null);
releaseGraphics(g2d); writeImage(resultImg, outputImg, FORMAT_JPG); }
public static void addTextWatermark(String text, String targetImg, String fontName, int fontStyle, Color color, int fontSize, float position, float alpha) throws IOException { validateFileExists(targetImg, "目标图片不存在"); validateAlpha(alpha); if (text == null || text.isEmpty()) { throw new IllegalArgumentException("水印文字不能为空"); } fontSize = fontSize <= 0 ? DEFAULT_FONT_SIZE : fontSize;
File targetFile = new File(targetImg); BufferedImage targetBufferedImg = ImageIO.read(targetFile); int targetWidth = targetBufferedImg.getWidth(); int targetHeight = targetBufferedImg.getHeight();
BufferedImage resultImg = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = createGraphics2D(resultImg, targetBufferedImg);
String actualFontName = (fontName == null || fontName.trim().isEmpty()) ? DEFAULT_FONT_NAME : fontName; Font font = new Font(actualFontName, fontStyle, fontSize); g2d.setFont(font); g2d.setColor(color == null ? Color.BLACK : color); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
Point textPoint = calculateTextPosition(position, targetWidth, targetHeight, text, font, g2d); g2d.drawString(text, textPoint.x, textPoint.y);
releaseGraphics(g2d); writeImage(resultImg, targetImg, FORMAT_JPG); }
public static void addRotatedTileWatermark(String targetImg, String outputImg, String watermarkImg, int degree, float alpha) throws IOException { validateFileExists(targetImg, "目标图片不存在"); validateFileExists(watermarkImg, "水印图片不存在"); validateAlpha(alpha);
BufferedImage targetBufferedImg = ImageIO.read(new File(targetImg)); int targetWidth = targetBufferedImg.getWidth(); int targetHeight = targetBufferedImg.getHeight();
BufferedImage watermarkBufferedImg = ImageIO.read(new File(watermarkImg)); int watermarkWidth = watermarkBufferedImg.getWidth(); int watermarkHeight = watermarkBufferedImg.getHeight();
BufferedImage resultImg = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = resultImg.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.drawImage(targetBufferedImg, 0, 0, targetWidth, targetHeight, null);
g2d.rotate(Math.toRadians(degree), targetWidth / 2.0, targetHeight / 2.0); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
int x = -targetWidth; int y = -targetHeight; int spacingX = watermarkWidth + 300; int spacingY = watermarkHeight + 300;
while (x < targetWidth * 2) { y = -targetHeight; while (y < targetHeight * 2) { g2d.drawImage(watermarkBufferedImg, x, y, null); y += spacingY; } x += spacingX; }
releaseGraphics(g2d); writeImage(resultImg, outputImg, FORMAT_JPG); }
public static List<String> extractImageUrls(String htmlCode) { List<String> imageUrls = new ArrayList<>(); if (htmlCode == null || htmlCode.isEmpty()) { return imageUrls; }
Matcher matcher = IMG_SRC_PATTERN.matcher(htmlCode); while (matcher.find()) { String quote = matcher.group(1); String src = matcher.group(2); if (src != null) { src = (quote == null || quote.isEmpty()) ? src.split("\\s+")[0] : src; imageUrls.add(src); } } return imageUrls; }
public static void cutImage(String srcImageFile, String outputFile, int x, int y, int width, int height) throws IOException { validateFileExists(srcImageFile, "源图片不存在"); try (InputStream inputStream = new FileInputStream(srcImageFile)) { cutImage(inputStream, outputFile, x, y, width, height); } }
public static void cutImage(InputStream inputStream, String outputFile, int x, int y, int width, int height) throws IOException { if (width <= 0 || height <= 0) { throw new IllegalArgumentException("切割宽度和高度必须大于0"); }
BufferedImage srcImg = ImageIO.read(inputStream); int srcWidth = srcImg.getWidth(); int srcHeight = srcImg.getHeight();
int validX = Math.max(0, Math.min(x, srcWidth - 1)); int validY = Math.max(0, Math.min(y, srcHeight - 1)); int validWidth = Math.min(width, srcWidth - validX); int validHeight = Math.min(height, srcHeight - validY);
ImageFilter cropFilter = new CropImageFilter(validX, validY, validWidth, validHeight); Image croppedImage = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(srcImg.getSource(), cropFilter));
BufferedImage resultImg = new BufferedImage(validWidth, validHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = resultImg.createGraphics(); g2d.drawImage(croppedImage, 0, 0, null); releaseGraphics(g2d);
writeImage(resultImg, outputFile, DEFAULT_CUT_FORMAT); }
public static void preciseCutImage(int x1, int y1, int width, int height, String sourcePath, String outputPath) throws IOException { validateFileExists(sourcePath, "源图片不存在"); if (width <= 0 || height <= 0) { throw new IllegalArgumentException("裁切宽度和高度必须大于0"); }
try (FileInputStream fis = new FileInputStream(sourcePath); ImageInputStream iis = ImageIO.createImageInputStream(fis)) {
String format = getFileSuffix(sourcePath); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(format); if (!readers.hasNext()) { throw new UnsupportedEncodingException("不支持的图片格式:" + format); }
ImageReader reader = readers.next(); reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam(); Rectangle rect = new Rectangle(x1, y1, width, height); param.setSourceRegion(rect);
BufferedImage cutImg = reader.read(0, param); writeImage(cutImg, outputPath, format);
reader.dispose(); } }
public static void cropImage(InputStream input, OutputStream output, int x, int y, int w, int h, boolean isPNG) throws IOException { BufferedImage srcImg = ImageIO.read(input); int srcWidth = srcImg.getWidth(); int srcHeight = srcImg.getHeight();
int validX = Math.max(0, Math.min(x, srcWidth - 1)); int validY = Math.max(0, Math.min(y, srcHeight - 1)); int validW = Math.min(w, srcWidth - validX); int validH = Math.min(h, srcHeight - validY);
BufferedImage subImg = srcImg.getSubimage(validX, validY, validW, validH);
int imageType = isPNG ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB; BufferedImage resultImg = new BufferedImage(w, h, imageType); Graphics2D g2d = resultImg.createGraphics(); g2d.drawImage(subImg, 0, 0, null); releaseGraphics(g2d);
ImageIO.write(resultImg, isPNG ? FORMAT_PNG : FORMAT_JPG, output); }
public static void cropImage(InputStream input, String outputPath, int x, int y, int w, int h, boolean isPNG) throws IOException { try (OutputStream outputStream = new FileOutputStream(outputPath)) { cropImage(input, outputStream, x, y, w, h, isPNG); } }
private static Graphics2D createGraphics2D(BufferedImage resultImg, BufferedImage targetImg) { Graphics2D g2d = resultImg.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.drawImage(targetImg, 0, 0, targetImg.getWidth(), targetImg.getHeight(), null); return g2d; }
private static void releaseGraphics(Graphics2D g2d) { if (g2d != null) { g2d.dispose(); } }
private static Point calculateWatermarkPosition(float position, int targetWidth, int targetHeight, int watermarkWidth, int watermarkHeight) { int x, y; if (position < POSITION_CENTER) { x = DEFAULT_WATERMARK_OFFSET; y = DEFAULT_WATERMARK_OFFSET; } else if (position == POSITION_CENTER) { x = (targetWidth - watermarkWidth) / 2; y = (targetHeight - watermarkHeight) / 2; } else { x = targetWidth - watermarkWidth - DEFAULT_WATERMARK_OFFSET; y = targetHeight - watermarkHeight - DEFAULT_WATERMARK_OFFSET; } return new Point(x, y); }
private static Point calculateTextPosition(float position, int targetWidth, int targetHeight, String text, Font font, Graphics2D g2d) { int x, y; FontMetrics metrics = g2d.getFontMetrics(font); int textWidth = metrics.stringWidth(text); int textHeight = metrics.getAscent();
if (position < POSITION_CENTER) { x = textHeight; y = textHeight; } else if (position == POSITION_CENTER) { x = (targetWidth - textWidth) / 2; y = (targetHeight + textHeight) / 2; } else { x = targetWidth - textWidth - textHeight; y = targetHeight - textHeight; } return new Point(x, y); }
private static void validateAlpha(float alpha) { if (alpha < 0.0f || alpha > 1.0f) { throw new IllegalArgumentException("透明度必须在0.0-1.0之间"); } }
private static void validateFileExists(String filePath, String errorMsg) { File file = new File(filePath); if (!file.exists() || !file.isFile()) { throw new IllegalArgumentException(errorMsg + ":" + filePath); } }
private static String getFileSuffix(String filePath) { int lastDotIndex = filePath.lastIndexOf("."); if (lastDotIndex == -1 || lastDotIndex == filePath.length() - 1) { throw new IllegalArgumentException("文件没有后缀:" + filePath); } return filePath.substring(lastDotIndex + 1).toLowerCase(); }
private static void writeImage(BufferedImage image, String outputPath, String format) throws IOException { File outputFile = new File(outputPath); File parentDir = outputFile.getParentFile(); if (parentDir != null && !parentDir.exists()) { boolean mkdirsSuccess = parentDir.mkdirs(); if (!mkdirsSuccess) { throw new IOException("创建目录失败:" + parentDir.getAbsolutePath()); } } boolean writeSuccess = ImageIO.write(image, format, outputFile); if (!writeSuccess) { throw new IOException("图片写入失败!不支持的格式:" + format + ",图片类型:" + image.getType()); } }
public static void scaleByWidth(String srcPath, String destPath, int targetWidth, String format) throws IOException { validateFileExists(srcPath, "源图片不存在"); BufferedImage srcImg = ImageIO.read(new File(srcPath)); int targetHeight = (int) (srcImg.getHeight() * (targetWidth / (double) srcImg.getWidth())); scaleImage(srcImg, destPath, targetWidth, targetHeight, format, DEFAULT_COMPRESS_QUALITY); }
public static void scaleByHeight(String srcPath, String destPath, int targetHeight, String format) throws IOException { validateFileExists(srcPath, "源图片不存在"); BufferedImage srcImg = ImageIO.read(new File(srcPath)); int targetWidth = (int) (srcImg.getWidth() * (targetHeight / (double) srcImg.getHeight())); scaleImage(srcImg, destPath, targetWidth, targetHeight, format, DEFAULT_COMPRESS_QUALITY); }
public static void scaleImage(String srcPath, String destPath, int targetWidth, int targetHeight, String format, float quality) throws IOException { validateFileExists(srcPath, "源图片不存在"); validateCompressQuality(quality); BufferedImage srcImg = ImageIO.read(new File(srcPath)); scaleImage(srcImg, destPath, targetWidth, targetHeight, format, quality); }
private static void scaleImage(BufferedImage srcImg, String destPath, int targetWidth, int targetHeight, String format, float quality) throws IOException { BufferedImage scaledImg = new BufferedImage(targetWidth, targetHeight, getImageType(srcImg)); Graphics2D g2d = scaledImg.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.drawImage(srcImg, 0, 0, targetWidth, targetHeight, null); releaseGraphics(g2d);
writeImageWithQuality(scaledImg, destPath, format, quality); }
public static void convertFormat(String srcPath, String destPath, String targetFormat) throws IOException { convertFormat(srcPath, destPath, targetFormat, DEFAULT_COMPRESS_QUALITY); }
public static void convertFormat(String srcPath, String destPath, String targetFormat, float quality) throws IOException { validateFileExists(srcPath, "源图片不存在"); validateCompressQuality(quality); BufferedImage srcImg = ImageIO.read(new File(srcPath)); writeImageWithQuality(srcImg, destPath, targetFormat, quality); }
public static void compressByQuality(String srcPath, String destPath, float quality) throws IOException { validateFileExists(srcPath, "源图片不存在"); validateCompressQuality(quality); BufferedImage srcImg = ImageIO.read(new File(srcPath)); String format = getFileSuffix(srcPath); writeImageWithQuality(srcImg, destPath, format, quality); }
public static void compressBySize(String srcPath, String destPath, int targetSizeKB) throws IOException { validateFileExists(srcPath, "源图片不存在"); if (targetSizeKB <= 0) { throw new IllegalArgumentException("目标大小必须大于0KB"); }
File srcFile = new File(srcPath); long srcSizeKB = srcFile.length() / 1024; if (srcSizeKB <= targetSizeKB) { copyFile(srcFile, new File(destPath)); return; }
BufferedImage srcImg = ImageIO.read(srcFile); String format = getFileSuffix(srcPath); float low = 0.0f, high = 1.0f, mid = 0.5f; File tempFile = File.createTempFile("img_compress_", "." + format);
try { while (high - low > 0.01) { mid = (low + high) / 2; writeImageWithQuality(srcImg, tempFile.getAbsolutePath(), format, mid); long tempSizeKB = tempFile.length() / 1024;
if (tempSizeKB < targetSizeKB) { low = mid; } else if (tempSizeKB > targetSizeKB) { high = mid; } else { break; } } writeImageWithQuality(srcImg, destPath, format, mid); } finally { tempFile.delete(); } }
public static void rotateImage(String srcPath, String destPath, int degree) throws IOException { validateFileExists(srcPath, "源图片不存在"); String format = extractFileSuffix(srcPath); if (!Arrays.asList(FORMAT_JPG, FORMAT_PNG).contains(format)) { throw new IllegalArgumentException("仅支持JPG/PNG格式,当前格式:" + format); } BufferedImage srcImg = ImageIO.read(new File(srcPath));
Rectangle rotatedRect = calculateRotatedSize(srcImg, degree); int newWidth = rotatedRect.width; int newHeight = rotatedRect.height;
int imageType = FORMAT_PNG.equalsIgnoreCase(format) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB; BufferedImage rotatedImg = new BufferedImage(newWidth, newHeight, imageType); Graphics2D g2d = rotatedImg.createGraphics();
if (FORMAT_JPG.equalsIgnoreCase(format)) { g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, newWidth, newHeight); } else { g2d.setColor(new Color(0, 0, 0, 0)); g2d.fillRect(0, 0, newWidth, newHeight); }
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
AffineTransform at = new AffineTransform(); at.translate(newWidth / 2.0, newHeight / 2.0); at.rotate(Math.toRadians(degree)); at.translate(-srcImg.getWidth() / 2.0, -srcImg.getHeight() / 2.0);
g2d.setTransform(at); g2d.drawImage(srcImg, 0, 0, null);
if (FORMAT_JPG.equalsIgnoreCase(format)) { g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, newWidth, newHeight); g2d.drawImage(srcImg, 0, 0, null); }
releaseGraphics(g2d);
writeImage(rotatedImg, destPath, format); }
private static String extractFileSuffix(String filePath) { if (filePath == null || filePath.isEmpty()) { throw new IllegalArgumentException("文件路径不能为空"); } int lastDotIndex = filePath.lastIndexOf("."); if (lastDotIndex == -1 || lastDotIndex == filePath.length() - 1) { throw new IllegalArgumentException("文件路径无有效后缀:" + filePath); } return filePath.substring(lastDotIndex + 1).toLowerCase(); }
private static Rectangle calculateRotatedSize(BufferedImage src, int degree) { if (degree % 360 == 0) { return new Rectangle(src.getWidth(), src.getHeight()); } int absDegree = Math.abs(degree) % 360; if (absDegree == 90 || absDegree == 270) { return new Rectangle(src.getHeight(), src.getWidth()); } double radian = Math.toRadians(degree); double sin = Math.abs(Math.sin(radian)); double cos = Math.abs(Math.cos(radian)); int width = (int) Math.round(src.getWidth() * cos + src.getHeight() * sin); int height = (int) Math.round(src.getWidth() * sin + src.getHeight() * cos); return new Rectangle(width, height); }
public static void addMultiLineTextWatermark(List<String> textLines, String scrImg,String outPath, String fontName, int fontStyle, Color color, int fontSize, float position, float alpha, int lineSpacing) throws IOException { validateFileExists(scrImg, "目标图片不存在"); validateAlpha(alpha); if (textLines == null || textLines.isEmpty()) { throw new IllegalArgumentException("水印文字不能为空"); } fontSize = fontSize <= 0 ? DEFAULT_FONT_SIZE : fontSize; lineSpacing = lineSpacing < 0 ? 10 : lineSpacing;
BufferedImage targetImgObj = ImageIO.read(new File(scrImg)); int targetWidth = targetImgObj.getWidth(); int targetHeight = targetImgObj.getHeight();
BufferedImage resultImg = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = createGraphics2D(resultImg, targetImgObj);
String actualFontName = (fontName == null || fontName.trim().isEmpty()) ? DEFAULT_FONT_NAME : fontName; Font font = new Font(actualFontName, fontStyle, fontSize); g2d.setFont(font); g2d.setColor(color == null ? Color.BLACK : color); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
FontMetrics metrics = g2d.getFontMetrics(font); int maxLineWidth = 0; int totalTextHeight = 0; for (String line : textLines) { maxLineWidth = Math.max(maxLineWidth, metrics.stringWidth(line)); totalTextHeight += metrics.getHeight() + lineSpacing; } totalTextHeight -= lineSpacing;
Point startPoint = new Point(0, 0); if (position < POSITION_CENTER) { startPoint.x = DEFAULT_WATERMARK_OFFSET; startPoint.y = DEFAULT_WATERMARK_OFFSET + metrics.getAscent(); } else if (position == POSITION_CENTER) { startPoint.x = (targetWidth - maxLineWidth) / 2; startPoint.y = (targetHeight - totalTextHeight) / 2 + metrics.getAscent(); } else { startPoint.x = targetWidth - maxLineWidth - DEFAULT_WATERMARK_OFFSET; startPoint.y = targetHeight - totalTextHeight - DEFAULT_WATERMARK_OFFSET + metrics.getAscent(); }
int currentY = startPoint.y; for (String line : textLines) { g2d.drawString(line, startPoint.x, currentY); currentY += metrics.getHeight() + lineSpacing; }
releaseGraphics(g2d); writeImage(resultImg, outPath, FORMAT_JPG); }
public static void addRoundCorner(String srcPath, String destPath, int radius, String format) throws IOException { validateFileExists(srcPath, "源图片不存在"); if (radius < 0) { throw new IllegalArgumentException("圆角半径不能为负数"); }
BufferedImage srcImg = ImageIO.read(new File(srcPath)); int width = srcImg.getWidth(); int height = srcImg.getHeight();
BufferedImage roundImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = roundImg.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillRoundRect(0, 0, width, height, radius, radius); g2d.setComposite(AlphaComposite.SrcIn); g2d.drawImage(srcImg, 0, 0, width, height, null);
releaseGraphics(g2d); writeImage(roundImg, destPath, format); }
public static void convertToGrayscale(String srcPath, String destPath, String format) throws IOException { validateFileExists(srcPath, "源图片不存在"); BufferedImage srcImg = ImageIO.read(new File(srcPath));
BufferedImage grayImg = new BufferedImage(srcImg.getWidth(), srcImg.getHeight(), BufferedImage.TYPE_BYTE_GRAY); Graphics2D g2d = grayImg.createGraphics(); g2d.drawImage(srcImg, 0, 0, null); releaseGraphics(g2d);
writeImage(grayImg, destPath, format); }
public static Map<String, Object> getImageInfo(String imgPath) throws IOException { validateFileExists(imgPath, "图片不存在"); File imgFile = new File(imgPath); BufferedImage img = ImageIO.read(imgFile);
Map<String, Object> info = new HashMap<>(); info.put("width", img.getWidth()); info.put("height", img.getHeight()); info.put("format", getFileSuffix(imgPath).toUpperCase()); info.put("sizeKB", imgFile.length() / 1024.0); info.put("sizeMB", imgFile.length() / (1024.0 * 1024.0));
return info; }
private static int getImageType(BufferedImage img) { return img.getType() == BufferedImage.TYPE_CUSTOM ? BufferedImage.TYPE_INT_RGB : img.getType(); }
private static void validateCompressQuality(float quality) { if (quality < 0.0f || quality > 1.0f) { throw new IllegalArgumentException("压缩质量必须在0.0-1.0之间"); } }
private static void writeImageWithQuality(BufferedImage image, String outputPath, String format, float quality) throws IOException { File outputFile = new File(outputPath); createParentDir(outputFile);
if (FORMAT_JPG.equalsIgnoreCase(format)) { ImageWriter writer = ImageIO.getImageWritersByFormatName(FORMAT_JPG).next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(quality);
try (FileOutputStream fos = new FileOutputStream(outputFile); ImageOutputStream ios = ImageIO.createImageOutputStream(fos)) { writer.setOutput(ios); writer.write(null, new IIOImage(image, null, null), param); writer.dispose(); } } else { ImageIO.write(image, format, outputFile); } }
private static void createParentDir(File file) throws IOException { File parentDir = file.getParentFile(); if (parentDir != null && !parentDir.exists()) { boolean mkdirsSuccess = parentDir.mkdirs(); if (!mkdirsSuccess) { throw new IOException("创建目录失败:" + parentDir.getAbsolutePath()); } } }
private static void copyFile(File src, File dest) throws IOException { try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest)) { byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } }
public static void stitchImages(List<String> imgPaths, String destPath, boolean isHorizontal, int gap, String format) throws IOException { if (imgPaths == null || imgPaths.size() < 2) { throw new IllegalArgumentException("至少需要2张图片进行拼接"); } gap = Math.max(0, gap);
List<BufferedImage> imgList = new ArrayList<>(); int totalWidth = 0, totalHeight = 0; int singleWidth = 0, singleHeight = 0;
for (String path : imgPaths) { validateFileExists(path, "拼接图片不存在"); BufferedImage img = ImageIO.read(new File(path)); imgList.add(img);
if (isHorizontal) { totalWidth += img.getWidth() + gap; singleHeight = Math.max(singleHeight, img.getHeight()); } else { totalHeight += img.getHeight() + gap; singleWidth = Math.max(singleWidth, img.getWidth()); } }
if (isHorizontal) { totalWidth -= gap; totalHeight = singleHeight; } else { totalHeight -= gap; totalWidth = singleWidth; }
BufferedImage stitchImg = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = stitchImg.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, totalWidth, totalHeight);
int currentX = 0, currentY = 0; for (BufferedImage img : imgList) { if (isHorizontal) { g2d.drawImage(img, currentX, 0, img.getWidth(), img.getHeight(), null); currentX += img.getWidth() + gap; } else { g2d.drawImage(img, 0, currentY, img.getWidth(), img.getHeight(), null); currentY += img.getHeight() + gap; } }
releaseGraphics(g2d); writeImage(stitchImg, destPath, format); }
public static String imageToBase64(String imgPath) throws IOException { validateFileExists(imgPath, "图片不存在"); String format = getFileSuffix(imgPath); if (!SUPPORTED_FORMATS.contains(format)) { throw new IllegalArgumentException("不支持的图片格式:" + format); }
try (FileInputStream fis = new FileInputStream(imgPath); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { bos.write(buffer, 0, len); } byte[] bytes = bos.toByteArray(); String base64 = Base64.getEncoder().encodeToString(bytes); return "data:image/" + format + ";base64," + base64; } }
public static void base64ToImage(String base64Str, String destPath) throws IOException { if (base64Str == null || base64Str.isEmpty()) { throw new IllegalArgumentException("Base64字符串不能为空"); }
String pureBase64 = base64Str.contains(";base64,") ? base64Str.split(";base64,")[1] : base64Str; byte[] bytes = Base64.getDecoder().decode(pureBase64);
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); FileOutputStream fos = new FileOutputStream(destPath)) {
BufferedImage img = ImageIO.read(bis); String format = getFileSuffix(destPath); writeImage(img, destPath, format); } }
public static void generateThumbnail(String srcPath, String destPath, int maxSize, String format) throws IOException { generateThumbnail(srcPath, destPath, maxSize, maxSize, format, true, DEFAULT_COMPRESS_QUALITY); }
public static void generateThumbnail(String srcPath, String destPath, int width, int height, String format, boolean keepRatio, float quality) throws IOException { validateFileExists(srcPath, "源图片不存在"); validateCompressQuality(quality);
BufferedImage srcImg = ImageIO.read(new File(srcPath)); int srcWidth = srcImg.getWidth(); int srcHeight = srcImg.getHeight();
int thumbWidth = width; int thumbHeight = height;
if (keepRatio) { double ratio = Math.min((double) width / srcWidth, (double) height / srcHeight); thumbWidth = (int) (srcWidth * ratio); thumbHeight = (int) (srcHeight * ratio); }
scaleImage(srcImg, destPath, thumbWidth, thumbHeight, format, quality); }
public static void main(String[] args) throws IOException { String watermarkImage="D:/test/waterMark.png"; String srcImage="D:/test/test.jpg"; addImageWatermark(watermarkImage, srcImage, getOutPath("test"), POSITION_RIGHT_BOTTOM, 0.5f);
addRotatedTileWatermark(srcImage, getOutPath("test_rotate"), watermarkImage, 30, 0.5f);
preciseCutImage(0, 0, 1000, 1000, srcImage, getOutPath("test_cut"));
ImageUtils.scaleByWidth(srcImage, getOutPath("test_scaled"), 800, ImageUtils.FORMAT_JPG);
ImageUtils.compressBySize(srcImage, getOutPath("test_compress"), 300);
ImageUtils.rotateImage(srcImage, getOutPath("test_rotate90"), 90);
List<String> lines = Arrays.asList("版权所有", "禁止转载", "www.example.com"); ImageUtils.addMultiLineTextWatermark(lines, srcImage, getOutPath("test_textWater"),"微软雅黑", Font.PLAIN, Color.WHITE, 24, ImageUtils.POSITION_CENTER, 0.7f, 10);
ImageUtils.addRoundCorner(srcImage, getOutPath("test_round"), 50, ImageUtils.FORMAT_PNG);
convertToGrayscale(srcImage, getOutPath("test_grayscale"), ImageUtils.FORMAT_JPG);
Map<String, Object> info = ImageUtils.getImageInfo(srcImage); System.out.println("宽度:" + info.get("width") + "px"); System.out.println("大小:" + info.get("sizeKB") + "KB");
System.out.println("图片处理完成");
}
private static String getOutPath(String fileName) { return "D:/test/%s_%s.jpg".formatted(fileName,System.currentTimeMillis()); } }
|