admin
2019-02-19 9192375a211cff2f91d1f65f932f97612d8dbcdb
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
package org.fanli.facade.user.util;
 
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.RenderingHints.Key;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
 
import javax.imageio.ImageIO;
 
import org.yeshi.utils.FileUtil;
import org.yeshi.utils.HttpUtil;
import org.yeshi.utils.MoneyBigDecimalUtil;
import org.yeshi.utils.StringUtil;
 
import com.yeshi.fanli.base.entity.goods.TaoBaoGoodsBrief;
import com.yeshi.fanli.base.log.LogHelper;
 
public class InviteImageUtil {
 
    // 画商品分享图
    public static InputStream drawGoodsShareImg(InputStream qrcodeStream, InputStream portrait,
            TaoBaoGoodsBrief goods) {
 
        String fontPath = "/usr/share/fonts/PingFang_Medium.ttf";
 
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            fontPath = "D:/PingFang_Medium.ttf";
        }
 
        String fontBoldPath = "/usr/share/fonts/PingFang_Heavy_0.ttf";
        if (os.toLowerCase().startsWith("win")) {
            fontBoldPath = "D:/PingFang_Heavy_0.ttf";
        }
 
        final BufferedImage targetImg = new BufferedImage(720, 1280, BufferedImage.TYPE_INT_RGB);
 
        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);// 文字抗锯齿 
 
        final Graphics2D g2d = (Graphics2D) targetImg.getGraphics();
 
        g2d.setRenderingHints(mapH);
 
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, 720, 1280);
        Font font = null;
        try {
            font = Font.createFont(Font.PLAIN, new File(fontPath)).deriveFont(30.0f);
        } catch (FontFormatException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
 
        g2d.setFont(font);
        try {
            g2d.setColor(new Color(153, 153, 153));
            // 画来源图标
            InputStream userTypeIcon = null;
            if (goods.getUserType() == 0)// 淘宝
            {
                userTypeIcon = InviteImageUtil.class.getClassLoader().getResourceAsStream("image/icon_tb.png");
            } else {
                userTypeIcon = InviteImageUtil.class.getClassLoader().getResourceAsStream("image/icon_tm.png");
            }
 
            g2d.drawImage(ImageIO.read(userTypeIcon), 50, 88, null);
 
            // 商品标题
            String title = goods.getTitle();
            int row = 0;
            int length = 0;
            // 画第一排
            length = getTextLengthByWidth(g2d, font, title, 500, 10);
            g2d.drawString(title.substring(0, length), 50 + 65, 112 + row * 40);
            title = title.substring(length);
            row++;
 
            // 判断是否画完,最多画2排
            while (title.length() > 0 && row < 2) {
                length = getTextLengthByWidth(g2d, font, title, 335, 10);
                g2d.drawString(title.substring(0, length), 50, 112 + row * 40);
                title = title.substring(length);
                row++;
            }
 
            // 画商品主图
            InputStream goodsPicture = HttpUtil.getAsInputStream(goods.getPictUrl());
            BufferedImage picImage = ImageIO.read(goodsPicture);
            picImage = zoomInImage(picImage, 620, 620);
            g2d.drawImage(picImage, 50, 190, null);
            Font boldFont = Font.createFont(Font.PLAIN, new File(fontBoldPath)).deriveFont(50.0f);
            // 画价格
            // 有券
            if (!StringUtil.isNullOrEmpty(goods.getCouponInfo())) {
                BigDecimal finalPrice = goods.getZkPrice();
                if (goods.getCouponStartFee().compareTo(goods.getZkPrice()) <= 0
                        && goods.getZkPrice().compareTo(goods.getCouponAmount()) >= 0) {
                    finalPrice = goods.getZkPrice().subtract(goods.getCouponAmount());
                }
 
                g2d.setColor(new Color(229, 0, 93));
                g2d.drawString("券后价  ¥", 57, 875);
                g2d.setColor(new Color(229, 0, 93));
                g2d.setFont(boldFont);
                g2d.drawString(finalPrice.toString(), 85 + 110, 875);
 
                // 画券右侧
                BufferedImage quanRight = ImageIO
                        .read(InviteImageUtil.class.getClassLoader().getResourceAsStream("image/fanli_quan_right.png"));
                g2d.setColor(new Color(241, 66, 66));
                g2d.drawImage(quanRight, 670 - quanRight.getWidth(), 852, null);
 
                // 画券的内容
                g2d.setColor(new Color(229, 0, 93));
 
                String quanString = " " + MoneyBigDecimalUtil.getWithNoZera(goods.getCouponAmount()) + "元券 ";
 
                boldFont = boldFont.deriveFont(44.0f);
                g2d.setFont(boldFont);
                FontMetrics fm = g2d.getFontMetrics(boldFont);
                int textLength = fm.stringWidth(quanString);
 
                g2d.fillRect(670 - quanRight.getWidth() - textLength, 852, textLength, 80);
 
                g2d.setColor(Color.WHITE);
 
                g2d.setFont(boldFont);
                g2d.drawString(quanString, 670 - quanRight.getWidth() - textLength, 927 - 19);
 
                // 画券左侧
                BufferedImage quanLeft = ImageIO
                        .read(InviteImageUtil.class.getClassLoader().getResourceAsStream("image/fanli_quan_left.png"));
                g2d.drawImage(quanLeft, 670 - quanRight.getWidth() - textLength - quanLeft.getWidth(), 852, null);
 
                String zkPriceName = "";
                if (goods.getUserType() == 0)
                    zkPriceName = "淘宝价  ¥ " + MoneyBigDecimalUtil.getWithNoZera(goods.getZkPrice());
                else
                    zkPriceName = "天猫价  ¥ " + MoneyBigDecimalUtil.getWithNoZera(goods.getZkPrice());
 
                g2d.setColor(new Color(153, 153, 153));
                font = font.deriveFont(30.0f);
                g2d.setFont(font);
                g2d.drawString(zkPriceName, 56, 930);
 
            } else// 无券
            {
                g2d.setColor(new Color(229, 0, 93));
                g2d.drawString("¥", 60, 870);
                g2d.setColor(new Color(229, 0, 93));
                BigDecimal finalPrice = goods.getZkPrice();
                g2d.setFont(boldFont);
                g2d.drawString(finalPrice.toString(), 85, 870);
            }
 
            g2d.setColor(new Color(247, 247, 247));
            g2d.fillRect(56, 1015, 608, 204);
 
            // 画二维码
 
            BufferedImage qrcodeImage = ImageIO.read(qrcodeStream);
            qrcodeImage = zoomInImage(qrcodeImage, 170, 170);
 
            g2d.drawImage(qrcodeImage, 56 + 17, 1015 + 17, null);
 
            // 画头像
            if (portrait != null) {
                BufferedImage portraitImg = ImageIO.read(portrait);
                portraitImg = zoomInImage(portraitImg, 40, 40);
                g2d.drawImage(portraitImg, 56 + 17 + (qrcodeImage.getWidth() - portraitImg.getWidth()) / 2,
                        1015 + 17 + (qrcodeImage.getHeight() - portraitImg.getHeight()) / 2, null);
            }
 
            font = font.deriveFont(30.0f);
            g2d.setFont(font);
            g2d.setColor(new Color(229, 0, 93));
            // g2d.drawString("返利券提醒您", 250 + 17, 1080 + 17);
 
            g2d.setColor(new Color(102, 102, 102));
            g2d.drawString("长按识别二维码领取优惠券", 250 + 17, 1130 + 17);
 
            g2d.dispose();
 
            // OutputStream out = new ByteArrayOutputStream(); new
            // FileOutputStream(new File(targetPath));
            // ImageIO.write(targetImg, "JPEG", out);
            // out.flush();
            // out.close();
            ByteArrayOutputStream aos = new ByteArrayOutputStream();
            ImageIO.write(targetImg, "JPEG", aos);
            InputStream is = new ByteArrayInputStream(aos.toByteArray());
            return is;
        } catch (Exception e) {
            try {
                LogHelper.errorDetailInfo(e);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
 
        return null;
    }
 
    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 void inviteFriendImg(InputStream urlInputStream, InputStream portraitInputStream,
            InputStream erCodeInputStream, String targetPath) throws IOException {
        inviteFriendImg(urlInputStream, portraitInputStream, erCodeInputStream, targetPath, 260, 908, 230);
    }
 
    /**
     * 
     * @param urlInputStream
     * @param portraitInputStream
     * @param erCodeInputStream
     * @param targetPath
     * @param pX
     *            -二维码的横坐标
     * @param pY
     *            -二维码的纵坐标
     * @param size
     *            -二维码的尺寸
     * @throws IOException
     */
    // 邀请好友图片
    public static void inviteFriendImg(InputStream urlInputStream, InputStream portraitInputStream,
            InputStream erCodeInputStream, String targetPath, int pX, int pY, int size) throws IOException {
        BufferedImage bgImage = ImageIO.read(urlInputStream);
        final BufferedImage targetImg = new BufferedImage(bgImage.getWidth(), bgImage.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        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);// 文字抗锯齿 
 
        // 画 背景图片
        final Graphics2D g2d = targetImg.createGraphics();
 
        g2d.drawImage(bgImage, 0, 0, bgImage.getWidth(), bgImage.getHeight(), null);
 
        // 画 二维码
        BufferedImage qrCodeImage = ImageIO.read(erCodeInputStream);
        qrCodeImage = InviteImageUtil.qrCodeImage(g2d, qrCodeImage, pX, pY, size, size); // 二维码长宽
        // 230*230
 
        // 画 头像
        BufferedImage portraitImg = ImageIO.read(portraitInputStream);
        int portraitSize = size * 5 / 23;
 
        int pPX = pX + size / 2 - portraitSize / 2;
        int pPY = pY + size / 2 - portraitSize / 2;
        portraitImg = InviteImageUtil.portraitImg(g2d, portraitImg, pPX, pPY, portraitSize, portraitSize);// 头像长宽
 
        OutputStream out = new FileOutputStream(new File(targetPath));
        ImageIO.write(targetImg, "JPEG", out);
        out.flush();
        out.close();
    }
 
    // 二维码
    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 portraitImg(Graphics2D g2d, BufferedImage originalImage, int pX, int pY, int width,
            int height) {
        g2d.drawImage(originalImage, pX, pY, width, height, null);
        return originalImage;
    }
 
    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;
    }
 
    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 };
    }
 
}