0%

分享一个图片工具类

分享一个图片工具类,

图片切割,图片水印,。。。。。

直接上代码

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;

/**
* 图片处理工具类
* 核心功能:水印(图片/文字/多行)、裁剪/切割、缩放、格式转换、压缩、旋转、圆角、黑白化、图片信息获取等
*
* @author rstyro
*/
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";

// 默认压缩质量(0.0-1.0)
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;

// 提取图片URL的正则表达式
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);

/**
* 图片添加图片水印(覆盖原文件)
*
* @param watermarkImg 水印图片路径
* @param targetImg 目标图片路径
* @param position 水印位置(<0.5左上,=0.5居中,>0.5右下)
* @param alpha 透明度(0.0-1.0)
* @throws IOException 图片处理异常
*/
public static void addImageWatermark(String watermarkImg, String targetImg, float position, float alpha) throws IOException {
addImageWatermark(watermarkImg, targetImg, targetImg, position, alpha);
}

/**
* 图片添加图片水印(生成新文件)
*
* @param watermarkImg 水印图片路径
* @param targetImg 目标图片路径
* @param outputImg 输出图片路径
* @param position 水印位置(<0.5左上,=0.5居中,>0.5右下)
* @param alpha 透明度(0.0-1.0)
* @throws IOException 图片处理异常
*/
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);
}

/**
* 图片添加文字水印
*
* @param text 水印文字
* @param targetImg 目标图片路径
* @param fontName 字体名称
* @param fontStyle 字体样式(Font.PLAIN/Font.BOLD/Font.ITALIC)
* @param color 字体颜色
* @param fontSize 字体大小
* @param position 水印位置(<0.5左上,=0.5居中,>0.5右下)
* @param alpha 透明度(0.0-1.0)
* @throws IOException 图片处理异常
*/
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);
}

/**
* 添加旋转的平铺图片水印
*
* @param targetImg 目标图片路径
* @param outputImg 输出图片路径
* @param watermarkImg 水印图片路径
* @param degree 旋转角度(-180~180)
* @param alpha 透明度(0.0-1.0)
* @throws IOException 图片处理异常
*/
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);
}

/**
* 从HTML源码提取图片URL
*
* @param htmlCode HTML源码
* @return 图片URL列表(空列表表示无图片)
*/
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;
}

/**
* 图片切割(基础版)
*
* @param srcImageFile 源图片路径
* @param outputFile 输出图片路径
* @param x 起始X坐标
* @param y 起始Y坐标
* @param width 切割宽度
* @param height 切割高度
* @throws IOException 图片处理异常
*/
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);
}
}

/**
* 图片切割(输入流版)
*
* @param inputStream 源图片输入流
* @param outputFile 输出图片路径
* @param x 起始X坐标
* @param y 起始Y坐标
* @param width 切割宽度
* @param height 切割高度
* @throws IOException 图片处理异常
*/
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);
}

/**
* 高精度图片裁切(支持多格式)
*
* @param x1 起始X坐标
* @param y1 起始Y坐标
* @param width 裁切宽度
* @param height 裁切高度
* @param sourcePath 源图片路径
* @param outputPath 输出图片路径
* @throws IOException 图片处理异常
*/
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);

// 释放ImageReader资源
reader.dispose();
}
}

/**
* 图片裁剪(支持PNG透明通道)
*
* @param input 源图片输入流
* @param output 输出流
* @param x 起始X坐标
* @param y 起始Y坐标
* @param w 裁剪宽度
* @param h 裁剪高度
* @param isPNG 是否为PNG格式(保留透明通道)
* @throws IOException 图片处理异常
*/
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);
}

/**
* 图片裁剪(输出到文件)
*
* @param input 源图片输入流
* @param outputPath 输出文件路径
* @param x 起始X坐标
* @param y 起始Y坐标
* @param w 裁剪宽度
* @param h 裁剪高度
* @param isPNG 是否为PNG格式
* @throws IOException 图片处理异常
*/
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);
}
}

// ------------------- 私有工具方法 -------------------

/**
* 创建Graphics2D并绘制原始图片
*/
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;
}

/**
* 释放Graphics资源
*/
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());
}
}

/**
* 图片等比例缩放(按宽度)
*
* @param srcPath 源图片路径
* @param destPath 目标图片路径
* @param targetWidth 目标宽度
* @param format 输出格式(JPG/PNG/GIF)
* @throws IOException 处理异常
*/
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);
}

/**
* 图片等比例缩放(按高度)
*
* @param srcPath 源图片路径
* @param destPath 目标图片路径
* @param targetHeight 目标高度
* @param format 输出格式(JPG/PNG/GIF)
* @throws IOException 处理异常
*/
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);
}

/**
* 图片固定尺寸缩放(非等比例)
*
* @param srcPath 源图片路径
* @param destPath 目标图片路径
* @param targetWidth 目标宽度
* @param targetHeight 目标高度
* @param format 输出格式
* @param quality 压缩质量(0.0-1.0)
* @throws IOException 处理异常
*/
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);
}

// ====================== 扩展方法:图片格式转换 ======================

/**
* 图片格式转换
*
* @param srcPath 源图片路径
* @param destPath 目标图片路径
* @param targetFormat 目标格式(JPG/PNG/GIF/BMP)
* @throws IOException 处理异常
*/
public static void convertFormat(String srcPath, String destPath, String targetFormat) throws IOException {
convertFormat(srcPath, destPath, targetFormat, DEFAULT_COMPRESS_QUALITY);
}

/**
* 图片格式转换(带压缩)
*
* @param srcPath 源图片路径
* @param destPath 目标图片路径
* @param targetFormat 目标格式
* @param quality 压缩质量
* @throws IOException 处理异常
*/
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);
}

// ====================== 图片压缩(按大小/质量) ======================

/**
* 图片质量压缩
*
* @param srcPath 源图片路径
* @param destPath 目标图片路径
* @param quality 压缩质量(0.0-1.0,值越小压缩越厉害)
* @throws IOException 处理异常
*/
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);
}

/**
* 图片按文件大小压缩(目标大小,单位:KB)
*
* @param srcPath 源图片路径
* @param destPath 目标图片路径
* @param targetSizeKB 目标大小(KB)
* @throws IOException 处理异常
*/
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(); // 删除临时文件
}
}

// ====================== 图片旋转 ======================

/**
* 图片旋转(按角度)
*
* @param srcPath 源图片路径
* @param destPath 目标图片路径
* @param degree 旋转角度(正数:顺时针,负数:逆时针)
* @throws IOException 处理异常
*/
public static void rotateImage(String srcPath, String destPath, int degree) throws IOException {
// 1. 参数校验 + 读取原图
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));

// 2. 计算旋转后的尺寸
Rectangle rotatedRect = calculateRotatedSize(srcImg, degree);
int newWidth = rotatedRect.width;
int newHeight = rotatedRect.height;

// 3. 按格式选择画布类型(关键:JPG用RGB,PNG用ARGB)
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); // JPG填充白色背景
g2d.fillRect(0, 0, newWidth, newHeight); // 填充整个画布
} else {
g2d.setColor(new Color(0, 0, 0, 0)); // PNG填充透明背景
g2d.fillRect(0, 0, newWidth, newHeight);
}

// 4. 渲染优化
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

// 5. 核心:旋转+平移(保证图片居中,修复90度显示一半)
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); // 移回原图中心

// 6. 绘制图片(顺序修正:先绘制,再处理背景,避免清空)
g2d.setTransform(at);
g2d.drawImage(srcImg, 0, 0, null);

// 7. JPG格式填充白色背景(避免黑色),PNG保留透明
if (FORMAT_JPG.equalsIgnoreCase(format)) {
g2d.setBackground(Color.WHITE);
g2d.clearRect(0, 0, newWidth, newHeight); // 先清空为白色
g2d.drawImage(srcImg, 0, 0, null); // 重新绘制图片
}

// 8. 释放资源
releaseGraphics(g2d);

// 9. 写入文件(带结果校验,失败抛异常)
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;
// 特殊角度优化:90/270度宽高互换,避免浮点计算误差
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);
}


// ====================== 添加多行文字水印 ======================

/**
* 添加多行文字水印
*
* @param textLines 多行文字(每行一个元素)
* @param scrImg 原图片路径
* @param outPath 目标图片路径
* @param fontName 字体名称
* @param fontStyle 字体样式
* @param color 字体颜色
* @param fontSize 字体大小
* @param position 水印位置
* @param alpha 透明度
* @param lineSpacing 行间距(像素)
* @throws IOException 处理异常
*/
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; // 默认行间距10像素

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);
}

// ====================== 图片圆角处理 ======================

/**
* 图片添加圆角
*
* @param srcPath 源图片路径
* @param destPath 目标图片路径
* @param radius 圆角半径(像素)
* @param format 输出格式(建议PNG,保留透明)
* @throws IOException 处理异常
*/
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();

// 创建圆角图片(必须用ARGB格式保留透明)
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);
}

// ====================== 图片黑白化(灰度处理) ======================

/**
* 图片黑白化(灰度处理)
*
* @param srcPath 源图片路径
* @param destPath 目标图片路径
* @param format 输出格式
* @throws IOException 处理异常
*/
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);
}

// ====================== 获取图片基本信息 ======================

/**
* 获取图片基本信息(宽度、高度、格式、大小)
*
* @param imgPath 图片路径
* @return 图片信息Map(key: width/height/format/sizeKB)
* @throws IOException 处理异常
*/
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之间");
}
}

/**
* 带质量的图片写入(支持JPG压缩)
*/
private static void writeImageWithQuality(BufferedImage image, String outputPath, String format, float quality) throws IOException {
File outputFile = new File(outputPath);
createParentDir(outputFile);

// JPG格式支持质量压缩,其他格式用默认方式
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);
}
}
}

/**
* 图片拼接
*
* @param imgPaths 待拼接的图片路径列表
* @param destPath 输出路径
* @param isHorizontal 是否横向拼接(true:横向,false:纵向)
* @param gap 图片间距(像素)
* @param format 输出格式
* @throws IOException 处理异常
*/
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);
}

/**
* 图片转Base64字符串
*
* @param imgPath 图片路径
* @return Base64字符串(带data:image/xxx;base64,前缀)
* @throws IOException 处理异常
*/
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;
}
}

/**
* Base64字符串转图片
*
* @param base64Str Base64字符串(可带/不带data:image/xxx;base64,前缀)
* @param destPath 输出路径
* @throws IOException 处理异常
*/
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);
}
}

/**
* 生成缩略图(等比例,最长边不超过指定尺寸)
*
* @param srcPath 源图片路径
* @param destPath 输出路径
* @param maxSize 最长边最大尺寸
* @param format 输出格式
* @throws IOException 处理异常
*/
public static void generateThumbnail(String srcPath, String destPath, int maxSize, String format) throws IOException {
generateThumbnail(srcPath, destPath, maxSize, maxSize, format, true, DEFAULT_COMPRESS_QUALITY);
}

/**
* 生成缩略图(自定义规则)
*
* @param srcPath 源图片路径
* @param destPath 输出路径
* @param width 目标宽度
* @param height 目标高度
* @param format 输出格式
* @param keepRatio 是否保持比例
* @param quality 压缩质量
* @throws IOException 处理异常
*/
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";
// 示例1:添加图片水印
addImageWatermark(watermarkImage, srcImage, getOutPath("test"), POSITION_RIGHT_BOTTOM, 0.5f);

//示例2:添加文字水印
// addTextWatermark("www.rstyro.com", srcImage, "微软雅黑", Font.PLAIN, Color.WHITE, 36, POSITION_CENTER, 0.7f);

// 示例3:添加旋转平铺水印
addRotatedTileWatermark(srcImage, getOutPath("test_rotate"), watermarkImage, 30, 0.5f);

//示例4:图片裁切
preciseCutImage(0, 0, 1000, 1000, srcImage, getOutPath("test_cut"));

//示例5:图片裁剪
// try (FileInputStream fis = new FileInputStream("E:\\lrs_img\\timg1.jpg")) {
// cropImage(fis, "E:\\lrs_img\\timg121.png", 148, 14, 251, 251, true);
// }


// 等比例缩放(宽度缩为800px)
ImageUtils.scaleByWidth(srcImage, getOutPath("test_scaled"), 800, ImageUtils.FORMAT_JPG);

// 按大小压缩(压缩到100KB)
ImageUtils.compressBySize(srcImage, getOutPath("test_compress"), 300);

// 旋转90度
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);

// 圆角处理(半径50px)
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());
}
}

拿走自己调试,如果可以,就点个赞呗!!!

您的打赏,是我创作的动力!不给钱?那我只能靠想象力充饥了。