1 import javax.imageio.ImageIO;
2 import javax.swing.*;
3 import java.awt.*;
4 import java.awt.image.BufferedImage;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.InputStream;
8
9 public class ImageUtils {
10
11 /**
12 * 生成缩略图
13 * @param sourcePath
14 * @param outputPath
15 * @param x1
16 * @param y1
17 * @param w
18 * @param h
19 */
20 public static void createThumbnail(String sourcePath, String outputPath, int x1, int y1, int w, int h) {
21 File inputfile = new File(sourcePath);
22 File outfile = new File(outputPath);
23 Thumbnails.of(inputfile).sourceRegion(x1, y1, w, h)
24 .size(w, h).outputFormat("png").toFile(outfile);
25 }
26
27 /**
28 * 将图章图片透明化
29 * @param sourcePath
30 * @param outputPath
31 */
32 public static void transparentImage(String sourcePath, String outputPath) {
33 InputStream is = null;
34 try {
35 File file = new File(sourcePath);
36 is = new FileInputStream(file);
37 // 如果是MultipartFile类型,那么自身也有转换成流的方法:is = file.getInputStream();
38 BufferedImage bi = ImageIO.read(is);
39 Image image = (Image) bi;
40 ImageIcon imageIcon = new ImageIcon(image);
41 BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
42 BufferedImage.TYPE_4BYTE_ABGR);
43 Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
44 g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
45 int alpha = 0;
46 for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
47 for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
48 int rgb = bufferedImage.getRGB(j2, j1);
49 int R = (rgb & 0xff0000) >> 16;
50 int G = (rgb & 0xff00) >> 8;
51 int B = (rgb & 0xff);
52 if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) {
53 rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
54 }
55 bufferedImage.setRGB(j2, j1, rgb);
56 }
57 }
58 g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
59 ImageIO.write(bufferedImage, "png", new File(outputPath));// 直接输出文件
60 } catch (Exception e) {
61 e.printStackTrace();
62 } finally {
63 if (is != null) {
64 try {
65 is.close();
66 } catch (Exception e) {
67 }
68 }
69 }
70 }
71 }