操作图片的工具类:



1 import java.awt.AlphaComposite;
2 import java.awt.Color;
3 import java.awt.Font;
4 import java.awt.Graphics;
5 import java.awt.Graphics2D;
6 import java.awt.Image;
7 import java.awt.Toolkit;
8 import java.awt.color.ColorSpace;
9 import java.awt.geom.AffineTransform;
10 import java.awt.image.AffineTransformOp;
11 import java.awt.image.BufferedImage;
12 import java.awt.image.ColorConvertOp;
13 import java.awt.image.CropImageFilter;
14 import java.awt.image.FilteredImageSource;
15 import java.awt.image.ImageFilter;
16 import java.io.File;
17 import java.io.FileInputStream;
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21
22 import com.sun.image.codec.jpeg.JPEGEncodeParam;
23 import com.sun.image.codec.jpeg.JPEGImageEncoder;
24 import com.sun.image.codec.jpeg.JPEGCodec;
25
26 import javax.imageio.ImageIO;
27
28 /**
29 * 图片处理工具类:<br>
30 * 功能:缩放图像、切割图像、图像类型转换、彩色转黑白、文字水印、图片水印等
31 * @author Administrator
32 */
33 public class ImageUtils {
34
35 /**
36 * 几种常见的图片格式
37 */
38 public static String IMAGE_TYPE_GIF = "gif";// 图形交换格式
39 public static String IMAGE_TYPE_JPG = "jpg";// 联合照片专家组
40 public static String IMAGE_TYPE_JPEG = "jpeg";// 联合照片专家组
41 public static String IMAGE_TYPE_BMP = "bmp";// 英文Bitmap(位图)的简写,它是Windows操作系统中的标准图像文件格式
42 public static String IMAGE_TYPE_PNG = "png";// 可移植网络图形
43 public static String IMAGE_TYPE_PSD = "psd";// Photoshop的专用格式Photoshop
44
45 /**
46 * 缩放图像(按比例缩放)
47 * @param srcImageFile 源图像文件地址
48 * @param result 缩放后的图像地址
49 * @param scale 缩放比例
50 * @param flag 缩放选择:true 放大; false 缩小;
51 */
52 public final static void scale(String srcImageFile, String result,
53 int scale, boolean flag) {
54 try {
55 BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
56 int width = src.getWidth(); // 得到源图宽
57
58 int height = src.getHeight(); // 得到源图长
59
60 if (flag) {// 放大
61 width = width * scale;
62 height = height * scale;
63 } else {// 缩小
64 width = width / scale;
65 height = height / scale;
66 }
67 Image image = src.getScaledInstance(width, height,
68 Image.SCALE_DEFAULT);
69 BufferedImage tag = new BufferedImage(width, height,
70 BufferedImage.TYPE_INT_RGB);
71 Graphics g = tag.getGraphics();
72 g.drawImage(image, 0, 0, null); // 绘制缩小后的图
73
74 g.dispose();
75 ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
76 } catch (IOException e) {
77 e.printStackTrace();
78 }
79 }
80
81 /**
82 * 缩放图像(按高度和宽度缩放)
83 * @param srcImageFile 源图像文件地址
84 * @param result 缩放后的图像地址
85 * @param height 缩放后的高度
86 * @param width 缩放后的宽度
87 * @param bb 比例不对时是否需要补白:true为补白; false为不补白;
88 */
89 public final static void scale2(String srcImageFile, String result, int width,int height, boolean bb) {
90 try {
91 double ratio = 0.0; // 缩放比例
92 File f = new File(srcImageFile);
93 BufferedImage bi = ImageIO.read(f);
94 Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
95 // 计算比例
96 if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
97 if (bi.getHeight() > bi.getWidth()) {
98 ratio = (new Integer(height)).doubleValue()
99 / bi.getHeight();
100 } else {
101 ratio = (new Integer(width)).doubleValue() / bi.getWidth();
102 }
103 AffineTransformOp op = new AffineTransformOp(AffineTransform
104 .getScaleInstance(ratio, ratio), null);
105 itemp = op.filter(bi, null);
106 }
107 if (bb) {//补白
108 BufferedImage image = new BufferedImage(width, height,
109 BufferedImage.TYPE_INT_RGB);
110 Graphics2D g = image.createGraphics();
111 g.setColor(Color.white);
112 g.fillRect(0, 0, width, height);
113 if (width == itemp.getWidth(null))
114 g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
115 itemp.getWidth(null), itemp.getHeight(null),
116 Color.white, null);
117 else
118 g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
119 itemp.getWidth(null), itemp.getHeight(null),
120 Color.white, null);
121 g.dispose();
122 itemp = image;
123 }
124 ImageIO.write((BufferedImage) itemp, "JPEG", new File(result));
125 } catch (IOException e) {
126 e.printStackTrace();
127 }
128 }
129
130 /**
131 * 缩放图像(按高度和宽度缩放)
132 * @param srcImageFile 源图像文件地址
133 * @param result 缩放后的图像地址
134 * @param height 缩放后的高度
135 * @param width 缩放后的宽度
136 * @param bb 比例不对时是否需要补白:true为补白; false为不补白;
137 */
138 public final static void scale3(String srcImageFile, String result, int width,int height, boolean bb) {
139 try {
140 BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
141 //int _width = src.getWidth(); // 得到源图宽
142
143 //int _height = src.getHeight(); // 得到源图长
144
145
146 Image image = src.getScaledInstance(width, height,
147 Image.SCALE_DEFAULT);
148 BufferedImage tag = new BufferedImage(width, height,
149 BufferedImage.TYPE_INT_RGB);
150 Graphics g = tag.getGraphics();
151 g.drawImage(image, 0, 0, null); // 绘制缩小后的图
152
153 g.dispose();
154 ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
155 } catch (IOException e) {
156 e.printStackTrace();
157 }
158 }
159
160 /**
161 * 图像切割(按指定起点坐标和宽高切割)
162 * @param srcImageFile 源图像地址
163 * @param result 切片后的图像地址
164 * @param x 目标切片起点坐标X
165 * @param y 目标切片起点坐标Y
166 * @param width 目标切片宽度
167 * @param height 目标切片高度
168 */
169 public final static void cut(String srcImageFile, String result,
170 int x, int y, int width, int height) {
171 try {
172 // 读取源图像
173
174 BufferedImage bi = ImageIO.read(new File(srcImageFile));
175 int srcWidth = bi.getHeight(); // 源图宽度
176 int srcHeight = bi.getWidth(); // 源图高度
177 if (srcWidth > 0 && srcHeight > 0) {
178 Image image = bi.getScaledInstance(srcWidth, srcHeight,
179 Image.SCALE_DEFAULT);
180 // 四个参数分别为图像起点坐标和宽高
181 // 即: CropImageFilter(int x,int y,int width,int height)
182 ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
183 Image img = Toolkit.getDefaultToolkit().createImage(
184 new FilteredImageSource(image.getSource(),
185 cropFilter));
186 BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
187 Graphics g = tag.getGraphics();
188 g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
189
190 g.dispose();
191 // 输出为文件
192
193 ImageIO.write(tag, "JPEG", new File(result));
194 }
195 } catch (Exception e) {
196 e.printStackTrace();
197 }
198 }
199
200 /**
201 * 图像切割(指定切片的行数和列数)
202 * @param srcImageFile 源图像地址
203 * @param descDir 切片目标文件夹
204
205 * @param rows 目标切片行数。默认2,必须是范围 [1, 20] 之内
206 * @param cols 目标切片列数。默认2,必须是范围 [1, 20] 之内
207 */
208 public final static void cut2(String srcImageFile, String descDir,
209 int rows, int cols) {
210 try {
211 if(rows<=0||rows>20) rows = 2; // 切片行数
212 if(cols<=0||cols>20) cols = 2; // 切片列数
213 // 读取源图像
214
215 BufferedImage bi = ImageIO.read(new File(srcImageFile));
216 int srcWidth = bi.getHeight(); // 源图宽度
217 int srcHeight = bi.getWidth(); // 源图高度
218 if (srcWidth > 0 && srcHeight > 0) {
219 Image img;
220 ImageFilter cropFilter;
221 Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
222 int destWidth = srcWidth; // 每张切片的宽度
223
224 int destHeight = srcHeight; // 每张切片的高度
225
226 // 计算切片的宽度和高度
227 if (srcWidth % cols == 0) {
228 destWidth = srcWidth / cols;
229 } else {
230 destWidth = (int) Math.floor(srcWidth / cols) + 1;
231 }
232 if (srcHeight % rows == 0) {
233 destHeight = srcHeight / rows;
234 } else {
235 destHeight = (int) Math.floor(srcWidth / rows) + 1;
236 }
237 // 循环建立切片
238 // 改进的想法:是否可用多线程加快切割速度
239 for (int i = 0; i < rows; i++) {
240 for (int j = 0; j < cols; j++) {
241 // 四个参数分别为图像起点坐标和宽高
242 // 即: CropImageFilter(int x,int y,int width,int height)
243 cropFilter = new CropImageFilter(j * destWidth, i * destHeight,
244 destWidth, destHeight);
245 img = Toolkit.getDefaultToolkit().createImage(
246 new FilteredImageSource(image.getSource(),
247 cropFilter));
248 BufferedImage tag = new BufferedImage(destWidth,
249 destHeight, BufferedImage.TYPE_INT_RGB);
250 Graphics g = tag.getGraphics();
251 g.drawImage(img, 0, 0, null); // 绘制缩小后的图
252
253 g.dispose();
254 // 输出为文件
255
256 ImageIO.write(tag, "JPEG", new File(descDir
257 + "_r" + i + "_c" + j + ".jpg"));
258 }
259 }
260 }
261 } catch (Exception e) {
262 e.printStackTrace();
263 }
264 }
265
266 /**
267 * 图像切割(指定切片的宽度和高度)
268 * @param srcImageFile 源图像地址
269 * @param descDir 切片目标文件夹
270
271 * @param destWidth 目标切片宽度。默认200
272 * @param destHeight 目标切片高度。默认150
273 */
274 public final static void cut3(String srcImageFile, String descDir,
275 int destWidth, int destHeight) {
276 try {
277 if(destWidth<=0) destWidth = 200; // 切片宽度
278 if(destHeight<=0) destHeight = 150; // 切片高度
279 // 读取源图像
280
281 BufferedImage bi = ImageIO.read(new File(srcImageFile));
282 int srcWidth = bi.getHeight(); // 源图宽度
283 int srcHeight = bi.getWidth(); // 源图高度
284 if (srcWidth > destWidth && srcHeight > destHeight) {
285 Image img;
286 ImageFilter cropFilter;
287 Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
288 int cols = 0; // 切片横向数量
289 int rows = 0; // 切片纵向数量
290 // 计算切片的横向和纵向数量
291 if (srcWidth % destWidth == 0) {
292 cols = srcWidth / destWidth;
293 } else {
294 cols = (int) Math.floor(srcWidth / destWidth) + 1;
295 }
296 if (srcHeight % destHeight == 0) {
297 rows = srcHeight / destHeight;
298 } else {
299 rows = (int) Math.floor(srcHeight / destHeight) + 1;
300 }
301 // 循环建立切片
302 // 改进的想法:是否可用多线程加快切割速度
303 for (int i = 0; i < rows; i++) {
304 for (int j = 0; j < cols; j++) {
305 // 四个参数分别为图像起点坐标和宽高
306 // 即: CropImageFilter(int x,int y,int width,int height)
307 cropFilter = new CropImageFilter(j * destWidth, i * destHeight,
308 destWidth, destHeight);
309 img = Toolkit.getDefaultToolkit().createImage(
310 new FilteredImageSource(image.getSource(),
311 cropFilter));
312 BufferedImage tag = new BufferedImage(destWidth,
313 destHeight, BufferedImage.TYPE_INT_RGB);
314 Graphics g = tag.getGraphics();
315 g.drawImage(img, 0, 0, null); // 绘制缩小后的图
316
317 g.dispose();
318 // 输出为文件
319
320 ImageIO.write(tag, "JPEG", new File(descDir
321 + "_r" + i + "_c" + j + ".jpg"));
322 }
323 }
324 }
325 } catch (Exception e) {
326 e.printStackTrace();
327 }
328 }
329
330 /**
331 * 图像类型转换:GIF->JPG、GIF->PNG、PNG->JPG、PNG->GIF(X)、BMP->PNG
332 * @param srcImageFile 源图像地址
333 * @param formatName 包含格式非正式名称的 String:如JPG、JPEG、GIF等
334
335 * @param destImageFile 目标图像地址
336 */
337 public final static void convert(String srcImageFile, String formatName, String destImageFile) {
338 try {
339 File f = new File(srcImageFile);
340 f.canRead();
341 f.canWrite();
342 BufferedImage src = ImageIO.read(f);
343 ImageIO.write(src, formatName, new File(destImageFile));
344 } catch (Exception e) {
345 e.printStackTrace();
346 }
347 }
348
349 /**
350 * 彩色转为黑白
351 * @param srcImageFile 源图像地址
352 * @param destImageFile 目标图像地址
353 */
354 public final static void gray(String srcImageFile, String destImageFile) {
355 try {
356 BufferedImage src = ImageIO.read(new File(srcImageFile));
357 ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
358 ColorConvertOp op = new ColorConvertOp(cs, null);
359 src = op.filter(src, null);
360 ImageIO.write(src, "JPEG", new File(destImageFile));
361 } catch (IOException e) {
362 e.printStackTrace();
363 }
364 }
365
366 /**
367 * 给图片添加文字水印
368
369 * @param pressText 水印文字
370 * @param srcImageFile 源图像地址
371 * @param destImageFile 目标图像地址
372 * @param fontName 水印的字体名称
373
374 * @param fontStyle 水印的字体样式
375
376 * @param color 水印的字体颜色
377
378 * @param fontSize 水印的字体大小
379
380 * @param x 修正值
381
382 * @param y 修正值
383
384 * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
385
386 */
387 public final static void pressText(String pressText,
388 String srcImageFile, String destImageFile, String fontName,
389 int fontStyle, Color color, int fontSize,int x,
390 int y, float alpha) {
391 try {
392 File img = new File(srcImageFile);
393 Image src = ImageIO.read(img);
394 int width = src.getWidth(null);
395 int height = src.getHeight(null);
396 BufferedImage image = new BufferedImage(width, height,
397 BufferedImage.TYPE_INT_RGB);
398 Graphics2D g = image.createGraphics();
399 g.drawImage(src, 0, 0, width, height, null);
400 g.setColor(color);
401 g.setFont(new Font(fontName, fontStyle, fontSize));
402 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
403 alpha));
404 // 在指定坐标绘制水印文字
405
406 g.drawString(pressText, (width - (getLength(pressText) * fontSize))
407 / 2 + x, (height - fontSize) / 2 + y);
408 g.dispose();
409 ImageIO.write((BufferedImage) image, "JPEG", new File(destImageFile));// 输出到文件流
410 } catch (Exception e) {
411 e.printStackTrace();
412 }
413 }
414
415 /**
416 * 给图片添加文字水印
417
418 * @param pressText 水印文字
419 * @param srcImageFile 源图像地址
420 * @param destImageFile 目标图像地址
421 * @param fontName 字体名称
422 * @param fontStyle 字体样式
423 * @param color 字体颜色
424 * @param fontSize 字体大小
425 * @param x 修正值
426
427 * @param y 修正值
428
429 * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
430
431 */
432 public final static void pressText2(String pressText, String srcImageFile,String destImageFile,
433 String fontName, int fontStyle, Color color, int fontSize, int x,
434 int y, float alpha) {
435 try {
436 File img = new File(srcImageFile);
437 Image src = ImageIO.read(img);
438 int width = src.getWidth(null);
439 int height = src.getHeight(null);
440 BufferedImage image = new BufferedImage(width, height,
441 BufferedImage.TYPE_INT_RGB);
442 Graphics2D g = image.createGraphics();
443 g.drawImage(src, 0, 0, width, height, null);
444 g.setColor(color);
445 g.setFont(new Font(fontName, fontStyle, fontSize));
446 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
447 alpha));
448 // 在指定坐标绘制水印文字
449
450 g.drawString(pressText, (width - (getLength(pressText) * fontSize))
451 / 2 + x, (height - fontSize) / 2 + y);
452 g.dispose();
453 ImageIO.write((BufferedImage) image, "JPEG", new File(destImageFile));
454 } catch (Exception e) {
455 e.printStackTrace();
456 }
457 }
458
459 /**
460 * 给图片添加图片水印
461
462 * @param pressImg 水印图片
463 * @param srcImageFile 源图像地址
464 * @param destImageFile 目标图像地址
465 * @param x 修正值。 默认在中间
466
467 * @param y 修正值。 默认在中间
468
469 * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
470
471 */
472 public final static void pressImage(String pressImg, String srcImageFile,String destImageFile,
473 int x, int y, float alpha) {
474 try {
475 File img = new File(srcImageFile);
476 Image src = ImageIO.read(img);
477 int wideth = src.getWidth(null);
478 int height = src.getHeight(null);
479 BufferedImage image = new BufferedImage(wideth, height,
480 BufferedImage.TYPE_INT_RGB);
481 Graphics2D g = image.createGraphics();
482 g.drawImage(src, 0, 0, wideth, height, null);
483 // 水印文件
484 Image src_biao = ImageIO.read(new File(pressImg));
485 int wideth_biao = src_biao.getWidth(null);
486 int height_biao = src_biao.getHeight(null);
487 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
488 alpha));
489 g.drawImage(src_biao, (wideth - wideth_biao) / 2,
490 (height - height_biao) / 2, wideth_biao, height_biao, null);
491 // 水印文件结束
492 g.dispose();
493 ImageIO.write((BufferedImage) image, "JPEG", new File(destImageFile));
494 } catch (Exception e) {
495 e.printStackTrace();
496 }
497 }
498
499 /**
500 * 创建图片缩略图(等比缩放 无失真缩放)
501 * @param src 源图片文件完整路径
502
503 * @param dist 目标图片文件完整路径
504 * @param width 缩放的宽度
505
506 * @param height 缩放的高度
507
508 * @param flag true 按照实际长宽输出 如果 false 按照比例进行无失真压缩
509
510
511 */
512 public static boolean createThumbnail(String src, String dist, float width, float height,boolean flag) {
513 boolean flag1 = false ;
514 try {
515 File srcfile = new File(src);
516 if (!srcfile.exists()) {
517 System.out.println("文件不存在");
518 return flag1;
519 }
520 BufferedImage image = ImageIO.read(srcfile);
521
522 // 获得缩放的比例
523
524 double ratio = 1.0;
525 // 判断如果高、宽都不大于设定值,则不处理
526 if (image.getHeight() > height || image.getWidth() > width) {
527 if (image.getHeight() > image.getWidth()) {
528 ratio = height / image.getHeight();
529 } else {
530 ratio = width / image.getWidth();
531 }
532 }
533 int newWidth = flag ? (int) width : (int) (image.getWidth() * ratio);
534 int newHeight = flag ? (int)height : (int) (image.getHeight() * ratio);
535 BufferedImage bfImage = new BufferedImage(newWidth, newHeight,
536 BufferedImage.TYPE_INT_RGB);
537 flag1 = bfImage.getGraphics().drawImage(
538 image.getScaledInstance(newWidth, newHeight,
539 Image.SCALE_SMOOTH), 0, 0, null);
540
541 FileOutputStream os = new FileOutputStream(dist);
542 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
543 JPEGEncodeParam jParam = encoder.getDefaultJPEGEncodeParam(bfImage) ;
544 jParam.setQuality(1f, false) ;
545 encoder.encode(bfImage);
546 os.close();
547 flag1 = true ;
548 } catch (Exception e) {
549 flag1 = false ;
550 }
551 return flag1 ;
552 }
553
554 /**
555 * 计算text的长度(一个中文算两个字符)
556
557 * @param text
558 * @return
559 */
560 public final static int getLength(String text) {
561 int length = 0;
562 for (int i = 0; i < text.length(); i++) {
563 if (new String(text.charAt(i) + "").getBytes().length > 1) {
564 length += 2;
565 } else {
566 length += 1;
567 }
568 }
569 return length / 2;
570 }
571
572 /**
573 * <获取图片宽度>
574 * add by jiang_yanyan 2015-01-04
575 * @param file 图片文件
576 * @return 宽度
577 */
578 public static int getImgWidth(File file) {
579 InputStream is = null;
580 BufferedImage src = null;
581 int ret = -1;
582 try {
583 is = new FileInputStream(file);
584 src = javax.imageio.ImageIO.read(is);
585 ret = src.getWidth(null); // 得到源图宽
586 is.close();
587 } catch (Exception e) {
588 e.printStackTrace();
589 }
590 return ret;
591 }
592
593 /**
594 * <获取图片高度>
595 * add by jiang_yanyan 2015-01-04
596 * @param file 图片文件
597 * @return 高度
598 */
599 public static int getImgHeight(File file) {
600 InputStream is = null;
601 BufferedImage src = null;
602 int ret = -1;
603 try {
604 is = new FileInputStream(file);
605 src = javax.imageio.ImageIO.read(is);
606 ret = src.getHeight(null); // 得到源图高
607 is.close();
608 } catch (Exception e) {
609 e.printStackTrace();
610 }
611 return ret;
612 }
613 }


 


作者:SummerChill


本博客为自己总结亦或在网上发现的技术博文的转载。 如果文中有什么错误,欢迎指出。以免更多的人被误导。