admin
2021-06-24 df4441322e9801c102299451da41d7c40b4502e9
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
package com.ks.daylucky.util;
 
import com.ks.daylucky.pojo.VO.ActivityAwardVO;
import com.ks.daylucky.pojo.VO.SimpleUser;
import com.ks.lucky.pojo.DO.LuckyActivity;
import org.yeshi.utils.FileUtil;
import org.yeshi.utils.HttpUtil;
import org.yeshi.utils.StringUtil;
 
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.RenderingHints.Key;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
public class ImageUtil {
 
 
    private static Font getFont() throws FontFormatException, IOException {
        InputStream fi = ImageUtil.class.getClassLoader().getResourceAsStream("font/msyh.ttf");
        Font font = Font.createFont(Font.PLAIN, fi);
        return font;
    }
 
    /**
     * 画活动分享图
     *
     * @param awardVOList
     * @param bg
     * @return
     * @throws FontFormatException
     * @throws IOException
     */
    public static InputStream drawActivityShareImage(List<ActivityAwardVO> awardVOList, InputStream bg) throws FontFormatException, IOException {
        Font font = getFont();
        font = font.deriveFont(30.0f);
        int width = 750;
        int height = 825;
        final BufferedImage targetImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        final Graphics2D g2d = (Graphics2D) targetImg.getGraphics();
        RenderingHints rh = new RenderingHints(
                RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g2d.setRenderingHints(rh);
        g2d.setFont(font);
        //画背景
        g2d.drawImage(ImageIO.read(bg), 0, 0, width, height, null);
        //--画奖项--
        //计算奖项占高
        int lineSpaceHeight = 5;
        int awardSpaceHeight = 23;
        int totalHeight = 0;
        int maxWidth = 608;
        int paddintTop = 21;
        int paddingBottom = 21;
        for (ActivityAwardVO vo : awardVOList) {
            totalHeight += computeStringHeight(g2d, font, vo.getTitle(), maxWidth, lineSpaceHeight);
        }
 
        totalHeight += (awardVOList.size() - 1) * awardSpaceHeight + paddintTop + paddingBottom;
 
 
        //画背景
 
        g2d.fillRoundRect(20, 625 - totalHeight, 711, totalHeight, 16, 16);
 
        int startY = 625 - totalHeight+paddintTop;
        //画奖品
        g2d.setColor(Color.decode("#333333"));
        for (ActivityAwardVO vo : awardVOList) {
            //画图标
            InputStream icon = HttpUtil.getAsInputStream(vo.getTypeIcon());
            BufferedImage iconImage = zoomInImage(ImageIO.read(icon), 28, 28);
            g2d.drawImage(iconImage, 48, startY, iconImage.getWidth(), iconImage.getHeight(), null);
            //画文字
            drawString(g2d, font, vo.getTitle(), maxWidth, lineSpaceHeight, 86, startY + font.getSize()-5);
            startY += computeStringHeight(g2d, font, vo.getTitle(), maxWidth, lineSpaceHeight) + awardSpaceHeight;
        }
 
 
        g2d.dispose();
 
        ByteArrayOutputStream aos = new ByteArrayOutputStream();
        ImageIO.write(targetImg, "JPEG", aos);
        return new ByteArrayInputStream(aos.toByteArray());
    }
 
    /**
     * 画活动用户分享图
     *
     * @param user
     * @param bg
     * @return
     * @throws FontFormatException
     * @throws IOException
     */
    public static InputStream drawActivityUserShareImage(SimpleUser user, InputStream bg) throws FontFormatException, IOException {
        Font font = getFont();
        font = font.deriveFont(24.76f);
        int width = 750;
        int height = 825;
        final BufferedImage targetImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        final Graphics2D g2d = (Graphics2D) targetImg.getGraphics();
        RenderingHints rh = new RenderingHints(
                RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g2d.setRenderingHints(rh);
        g2d.setFont(font);
 
        //画背景
        g2d.drawImage(ImageIO.read(bg), 0, 0, width, height, null);
 
        InputStream icon = HttpUtil.getAsInputStream(user.getPortrait());
        BufferedImage portrait = roundImage(zoomInImage(ImageIO.read(icon), 103, 103), 500);
 
        g2d.drawImage(portrait, null, (width - portrait.getWidth()) / 2, 35);
        FontMetrics fm = g2d.getFontMetrics(font);
        int nickNameWidth = fm.stringWidth(user.getNickName());
        g2d.drawString(user.getNickName(), (width - nickNameWidth) / 2, portrait.getHeight() + 35 + 8 + 25);
 
        g2d.dispose();
        ByteArrayOutputStream aos = new ByteArrayOutputStream();
        ImageIO.write(targetImg, "JPEG", aos);
        return new ByteArrayInputStream(aos.toByteArray());
    }
 
 
    private static int computeStringHeight(Graphics2D g2d, Font font, String content, int maxWidth, int spaceHeight) {
        FontMetrics fm = g2d.getFontMetrics(font);
        int start = 0;
        int rows = 1;
        for (int i = 0; i < content.length(); i++) {
            if (fm.stringWidth(content.substring(start, i)) > maxWidth) {
                start = i;
                rows++;
            }
        }
 
        return font.getSize() * rows + (rows - 1) * spaceHeight;
    }
 
 
    private static void drawString(Graphics2D g2d, Font font, String content, int maxWidth, int spaceHeight, int startX, int startY) {
        FontMetrics fm = g2d.getFontMetrics(font);
        int start = 0;
        List<String> rowsContentList = new ArrayList<>();
        for (int i = 0; i < content.length(); i++) {
            if (fm.stringWidth(content.substring(start, i)) >= maxWidth) {
                rowsContentList.add(content.substring(start, i));
                start = i;
            } else if (i == content.length() - 1) {//结束
                rowsContentList.add(content.substring(start, i));
            }
        }
 
        for (int i = 0; i < rowsContentList.size(); i++) {
            g2d.drawString(rowsContentList.get(i), startX, startY + i * spaceHeight + font.getSize() * i);
        }
    }
 
 
    private static int[] computeCropPosition(BufferedImage source, int width, int height) {
        int[] cropParams = new int[4];
        int owidth = source.getWidth();
        int oheight = source.getHeight();
        if (oheight * width - owidth * height > 0) {
            cropParams[0] = 0;
            cropParams[1] = (oheight - height) / 2;
            cropParams[2] = owidth;
            cropParams[3] = cropParams[2] * height / width;
        } else {
            cropParams[0] = (owidth - width) / 2;
            cropParams[1] = 0;
            cropParams[3] = oheight;
            cropParams[2] = cropParams[3] * width / height;
        }
 
        return cropParams;
    }
 
    public static BufferedImage crop(BufferedImage source, int startX, int startY, int w, int h) {
        int width = source.getWidth();
        int height = source.getHeight();
 
        if (startX <= -1) {
            startX = 0;
        }
        if (startY <= -1) {
            startY = 0;
        }
        if (w <= -1) {
            w = width - 1;
        }
        if (h <= -1) {
            h = height - 1;
        }
        BufferedImage result = new BufferedImage(w, h, source.getType());
        for (int y = startY; y < h + startY; y++) {
            for (int x = startX; x < w + startX; x++) {
                int rgb = source.getRGB(x, y);
                result.setRGB(x - startX, y - startY, rgb);
            }
        }
        return result;
    }
 
    public static BufferedImage zoomInImage(BufferedImage originalImage, int width, int height) {
        int type = originalImage.getType();
        if (type == 0)
            type = 5;
        BufferedImage newImage = new BufferedImage(width, height, type);
        Graphics g = newImage.getGraphics();
        g.drawImage(originalImage, 0, 0, width, height, null);
        g.dispose();
        return newImage;
    }
 
 
    // 二维码
    public static BufferedImage qrCodeImage(Graphics2D g2d, BufferedImage originalImage, int pX, int pY, int width,
                                            int height) {
        g2d.drawImage(originalImage, pX, pY, width, height, null);
        return originalImage;
    }
 
 
    public static BufferedImage roundImage(BufferedImage srcImage, int cornerRadius) { // 半径
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();
        HashMap<Key, Object> mapH = new HashMap<Key, Object>();
        mapH.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// 抗锯齿 (抗锯齿总开关)  
        mapH.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);// 文字抗锯齿 
        gs.setRenderingHints(mapH);
        gs.setClip(new RoundRectangle2D.Double(0, 0, width, height, cornerRadius, cornerRadius));
        gs.drawImage(srcImage, 0, 0, null);
        gs.dispose();
        return image;
    }
 
    public static int saveToImgByInputStream(InputStream inputStream, String imgPath, String imgName) {
        int stateInt = 1;
        try {
            File file = new File(imgPath, imgName);// 可以是任何图片格式.jpg,.png等
            FileOutputStream fos = new FileOutputStream(file);
 
            FileInputStream fis = (FileInputStream) inputStream;
 
            byte[] b = new byte[1024];
            int nRead = 0;
            while ((nRead = fis.read(b)) != -1) {
                fos.write(b, 0, nRead);
            }
            fos.flush();
            fos.close();
            fis.close();
 
        } catch (Exception e) {
            stateInt = 0;
            e.printStackTrace();
        } finally {
        }
        return stateInt;
    }
 
    public static int getTextLengthByWidth(Graphics2D g2d, Font font, String content, int maxWidth, int startPos) {
        FontMetrics fm = g2d.getFontMetrics(font);
        for (int i = startPos; i < content.length(); i++) {
            if (fm.stringWidth(content.substring(0, i)) >= maxWidth) {
                return i + 1;
            }
        }
        return content.length();
    }
 
    public static int[] getImgWidthAndHeight(String imgUrl) throws MalformedURLException, IOException {
        if (StringUtil.isNullOrEmpty(imgUrl)) {
            return new int[]{0, 0};
        }
        if (imgUrl.toLowerCase().endsWith("webp")) {
            return getImgWidthAndHeightWithWebp(imgUrl);
        } else {
            return getImgWidthAndHeightWithPngAndJpg(imgUrl);
        }
    }
 
    public static int[] getImgWidthAndHeightWithPngAndJpg(String imgUrl) throws MalformedURLException, IOException {
        InputStream murl = new URL(imgUrl).openStream();
        BufferedImage sourceImg = ImageIO.read(murl);
 
        int width = sourceImg.getWidth();
        int height = sourceImg.getHeight();
        return new int[]{width, height};
    }
 
    public static int[] getImgWidthAndHeightWithWebp(String imgUrl) throws MalformedURLException, IOException {
        String cacheFile = FileUtil.getCacheDir();
        String targetPath = cacheFile + "/CACHE_DOWNLOAD_IMG_" + System.currentTimeMillis() + "_"
                + (long) (Math.random() * 1000000000L);
        HttpUtil.downloadFile(imgUrl, targetPath);
        FileInputStream file = new FileInputStream(targetPath);
        byte[] bytes = new byte[30];
        file.read(bytes, 0, bytes.length);
        int width = ((int) bytes[27] & 0xff) << 8 | ((int) bytes[26] & 0xff);
        int height = ((int) bytes[29] & 0xff) << 8 | ((int) bytes[28] & 0xff);
        file.close();
        return new int[]{width, height};
    }
 
}