Java实现画图的详细步骤(完整代码)

一、导入依赖

<dependency>
   <groupId>net.coobird</groupId>
   <artifactId>thumbnailator</artifactId>
   <version>0.4.13</version>
</dependency>

二、工具类

package com.geidco.dcp.util;
 
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.geometry.Coordinate;
import org.apache.commons.lang3.StringUtils;
 
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
 
/**
 * @author XuPengFei
 */
public class ImageUtil {
 
    public static BufferedImage watermarkImgBase64(String base64, List<ImageWatermark> images, List<ImageFontText> texts) throws Exception {
        InputStream inputStream = null;
        base64 = base64.replaceFirst("data:image\/.*;base64,", "");
 
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            byte[] bytes = decoder.decode(base64);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            inputStream = bais;
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        BufferedImage destImage = ImageIO.read(inputStream);
        BufferedImage tempImage = null;
        int w1 = destImage.getWidth(), h1 = destImage.getHeight(), startX, startY, endX, endY;
        System.out.println("w1" + w1);
        System.out.println("h1" + h1);
        //水印位置
        Coordinate coordinate = null;
        //水印位置坐标左上、右下
        List<Integer> points = null;
 
        for (ImageWatermark imageWatermark : images) {
            inputStream = getInputStream(imageWatermark.getImageUrl());
            if (null == inputStream) {
                continue;
            }
            points = imageWatermark.getPoints();
            startX = new BigDecimal(points.get(0)).intValue();
            startY = new BigDecimal(points.get(1)).intValue();
            endX = new BigDecimal(points.get(2)).intValue();
            endY = new BigDecimal(points.get(3)).intValue();
            //设置水印位置
            coordinate = new Coordinate(startX, startY);
            tempImage = Thumbnails.of(ImageIO.read(inputStream)).size(endX - startX, endY - startY).keepAspectRatio(false).asBufferedImage();
//            tempImage = Thumbnails.of(ImageIO.read(inputStream)).size(180,180).keepAspectRatio(false).asBufferedImage();
//            destImage = Thumbnails.of(destImage).size(w1,h1).watermark(coordinate,tempImage,1f).asBufferedImage();
            destImage = Thumbnails.of(destImage).size(w1, h1).watermark(coordinate, tempImage, 1f).asBufferedImage();
        }
 
        for (ImageFontText fontText : texts) {
            startX = new BigDecimal(fontText.getStartX()).intValue();
            startY = new BigDecimal(fontText.getStartY()).intValue();
            destImage = mergeFontText(destImage, fontText, startX, startY);
        }
        destImage = Thumbnails.of(destImage).addFilter(new ThumbnailsImgFilter()).size(w1, h1).asBufferedImage();
        return destImage;
    }
 
    public static BufferedImage watermarkImg(String baseImgUrl, List<ImageWatermark> images, List<ImageFontText> texts) throws Exception {
        InputStream inputStream = getInputStream(baseImgUrl);
        if (null == inputStream) {
            throw new RuntimeException("海报图片生成失败");
        }
        BufferedImage destImage = ImageIO.read(inputStream);
        BufferedImage tempImage = null;
        int w1 = destImage.getWidth(), h1 = destImage.getHeight(), startX, startY, endX, endY;
        System.out.println("w1" + w1);
        System.out.println("h1" + h1);
        //水印位置
        Coordinate coordinate = null;
        //水印位置坐标左上、右下
        List<Integer> points = null;
        for (ImageWatermark imageWatermark : images) {
            inputStream = getInputStream(imageWatermark.getImageUrl());
            if (null == inputStream) {
                continue;
            }
            points = imageWatermark.getPoints();
            startX = new BigDecimal(points.get(0)).intValue();
            startY = new BigDecimal(points.get(1)).intValue();
            endX = new BigDecimal(points.get(2)).intValue();
            endY = new BigDecimal(points.get(3)).intValue();
            //设置水印位置
            coordinate = new Coordinate(startX, startY);
            tempImage = Thumbnails.of(ImageIO.read(inputStream)).size(endX - startX, endY - startY).keepAspectRatio(false).asBufferedImage();
//            tempImage = Thumbnails.of(ImageIO.read(inputStream)).size(180,180).keepAspectRatio(false).asBufferedImage();
//            destImage = Thumbnails.of(destImage).size(w1,h1).watermark(coordinate,tempImage,1f).asBufferedImage();
            destImage = Thumbnails.of(destImage).addFilter(new ThumbnailsImgFilter()).size(w1, h1).watermark(coordinate, tempImage, 1f).asBufferedImage();
        }
 
        for (ImageFontText fontText : texts) {
            startX = new BigDecimal(fontText.getStartX()).intValue();
            startY = new BigDecimal(fontText.getStartY()).intValue();
            destImage = mergeFontText(destImage, fontText, startX, startY);
        }
        return destImage;
    }
 
    private static BufferedImage mergeFontText(BufferedImage bufferedImage, ImageFontText fontText,
                                               int left, int top) throws Exception {
        Graphics2D g = bufferedImage.createGraphics();
        g.setColor(getColor(fontText.getTextColor()));
 
        Font font = new Font(fontText.getTextFont(), Font.BOLD, fontText.getTextSize());
        g.setFont(font);
 
        g.setBackground(Color.white);
 
        if (fontText.getStartX() == -1) {
            //昵称居中设置
            FontMetrics fmNick = g.getFontMetrics(font);
            int nickWidth = fmNick.stringWidth(fontText.getText());
            int nickWidthX = (bufferedImage.getWidth() - nickWidth) / 2;
            //绘制文字
            g.drawString(new String(fontText.getText().getBytes(), "utf-8"), nickWidthX, top);
        } else {
            g.drawString(new String(fontText.getText().getBytes(), "utf-8"), left, top);
        }
        g.dispose();
        return bufferedImage;
//        AttributedString ats = new AttributedString("我是n小雨哈哈哈");
//        ats.addAttribute(TextAttribute.FOREGROUND, f, 0,2 );
//        AttributedCharacterIterator iter = ats.getIterator();
//        g.drawString(iter,left,top);
    }
 
    private static Color getColor(String color) {
        if (StringUtils.isBlank(color) || color.length() < 7) {
            return null;
        }
        try {
            int r = Integer.parseInt(color.substring(1, 3), 16);
            int g = Integer.parseInt(color.substring(3, 5), 16);
            int b = Integer.parseInt(color.substring(5), 16);
            return new Color(r, g, b);
        } catch (NumberFormatException nfe) {
            return null;
        }
    }
 
    public static InputStream getInputStream(String baseUrl) {
        if (StringUtils.isBlank(baseUrl)) {
            return null;
        }
        try {
            InputStream inputStream = new FileInputStream(baseUrl);
            return inputStream;
        } catch (IOException e) {
            e.printStackTrace();
        }
//        try {
//            URL url = new URL(baseUrl);
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.setConnectTimeout(6000);
//            connection.setReadTimeout(6000);
//            int code = connection.getResponseCode();
//            if (HttpURLConnection.HTTP_OK == code) {
//                return connection.getInputStream();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return null;
    }
 
    /**
     * 将透明背景设置为白色
     */
    public static class ThumbnailsImgFilter implements ImageFilter {
        @Override
        public BufferedImage apply(BufferedImage img) {
            int w = img.getWidth();
            int h = img.getHeight();
            BufferedImage newImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphic = newImage.createGraphics();
            graphic.setColor(Color.white);//背景设置为白色
            graphic.fillRect(0, 0, w, h);
            graphic.drawRenderedImage(img, null);
            graphic.dispose();
            return newImage;
        }
    }
}

三、工具类

package com.geidco.dcp.util;
 
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
 
/**
 * @author XuPengFei
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ImageFontText {
    private String text;
    private Integer textSize = 50;
    private String textColor = "#ff0000";
    private String textFont = "宋体";
    private Integer startX;
    private Integer startY;
}

四、工具类

package com.geidco.dcp.util;
 
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
 
import java.util.List;
 
/**
 * @author XuPengFei
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ImageWatermark {
    /**
     * 图片地址
     */
    private String imageUrl;
    /**
     * 水印图片左上、右下标
     */
    private List<Integer> points;
}

五、测试接口

package com.geidco.dcp.controller.meetingApply;
 
import com.geidco.dcp.pojo.meetingApply.MeetingApply;
import com.geidco.dcp.pojo.meetingApply.MeetingGuestCardTemplate;
import com.geidco.dcp.service.meetingApply.MeetingApplyService;
import com.geidco.dcp.service.meetingApply.MeetingGuestCardTemplateService;
import com.geidco.dcp.util.*;
import com.xlkh.cloud.platform.common.annotation.Log;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
 
@RestController
@RequestMapping("/meetingGuestCard")
public class MeetingGuestCardController {
 
    @Value("${config.ldir}")
    String ldir;
 
    @Value("${config.wdir}")
    String wdir;
 
    @Autowired
    private MeetingApplyService meetingApplyService;
 
    @Autowired
    private IdWorker idWorker;
 
    @Autowired
    private MeetingGuestCardTemplateService meetingGuestCardTemplateService;
 
 
    @PostMapping("/generateGuestCard")
    @Log("绘制电子嘉宾证")
    public void generateGuestCard(@RequestBody Map<String, String> formData, HttpServletResponse response) {
        String templateId = formData.get("templateId");
        String ids = formData.get("meetingApplyId");
 
        List<String> meetingApplyIds = Arrays.asList(ids.split(","));
        List<MeetingApply> meetingApplys = meetingApplyService.getByKeys(meetingApplyIds);
 
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + uuid + "/";
        String zipPath = SysMeetingUtil.getAnnexFilePath() + "generateGuestCard/" + datePath;
        File file = new File(zipPath);
        if (!file.exists()) {
            file.mkdirs();
        }
 
        // 上传的位置
        String path = System.getProperty("os.name").toLowerCase().indexOf("win") >= 0 ? wdir : ldir;
 
        MeetingGuestCardTemplate cardTemplate = meetingGuestCardTemplateService.findById(templateId);
        // 底图
        String baseImgUrl = cardTemplate.getBaseMapUrl();
        try {
 
            for (int i = 0; i < meetingApplys.size(); i++) {
                MeetingApply meetingApply = meetingApplys.get(i);
 
                String name = null;
                String unitName = null;
                String postName = null;
 
                String photoUrl = path;
 
                if ("zh".equals(meetingApply.getApplyWay())) {
                    name = meetingApply.getName();
                    unitName = meetingApply.getUnitName();
                    postName = meetingApply.getPositionName();
                    photoUrl = photoUrl + meetingApply.getPhotoUrl();
                } else {
                    name = meetingApply.getNameEn();
                    unitName = meetingApply.getUnitNameEn();
                    postName = meetingApply.getPositionNameEn();
                    photoUrl = photoUrl + meetingApply.getPhotoUrl();
                }
 
                List<ImageWatermark> images = new ArrayList<>();
                List<ImageFontText> texts = new ArrayList<>();
 
                // 查询模板详情
                List<MeetingGuestCardTemplate> templates = meetingGuestCardTemplateService.findByTemplateId(templateId);
                for (MeetingGuestCardTemplate template : templates) {
                    String dict = template.getElementTypeDict();
                    if ("1".equals(dict)) {
                        ImageFontText imageFontText = new ImageFontText(name, StringUtils.isNotBlank(template.getFontSize()) ? Integer.parseInt(template.getFontSize()) : 30,
                                StringUtils.isNotBlank(template.getFontColor()) ? template.getFontColor() : "#333333",
                                StringUtils.isNotBlank(template.getFontType()) ? template.getFontType() : "宋体",
                                template.getStartX(), template.getStartY());
                        texts.add(imageFontText);
                    }
                    if ("2".equals(dict)) {
                        ImageFontText imageFontText = new ImageFontText(unitName, StringUtils.isNotBlank(template.getFontSize()) ? Integer.parseInt(template.getFontSize()) : 30,
                                StringUtils.isNotBlank(template.getFontColor()) ? template.getFontColor() : "#333333",
                                StringUtils.isNotBlank(template.getFontType()) ? template.getFontType() : "宋体",
                                template.getStartX(), template.getStartY());
                        texts.add(imageFontText);
                    }
                    if ("3".equals(dict)) {
                        ImageFontText imageFontText = new ImageFontText(postName, StringUtils.isNotBlank(template.getFontSize()) ? Integer.parseInt(template.getFontSize()) : 30,
                                StringUtils.isNotBlank(template.getFontColor()) ? template.getFontColor() : "#333333",
                                StringUtils.isNotBlank(template.getFontType()) ? template.getFontType() : "宋体",
                                template.getStartX(), template.getStartY());
                        texts.add(imageFontText);
                    }
                    if ("100".equals(dict)) {
                        Integer startX = template.getStartX();
                        Integer startY = template.getStartY();
                        Integer endX = template.getEndX();
                        Integer endY = template.getEndY();
                        List<Integer> imagePoints = Arrays.asList(startX, startY, endX, endY);
                        ImageWatermark image = new ImageWatermark(photoUrl, imagePoints);
                        images.add(image);
                    }
                }
 
                try {
                    BufferedImage bufferedImage = ImageUtil.watermarkImgBase64(baseImgUrl, images, texts);
                    OutputStream os = new FileOutputStream(zipPath + String.valueOf(i + 1) + name + ".jpg"/>

到此这篇关于Java实现画图的详细步骤(完整代码)的文章就介绍到这了,更多相关Java实现画图内容请搜索179885.Com以前的文章或继续浏览下面的相关文章希望大家以后多多支持179885.Com!

猜你在找的Java实现画图的详细步骤(完整代码)相关文章

TCP是一种传输控制协议,是面向连接的、可靠的、基于字节流之间的传输层通信协议,由IETF的RFC 793定义。在简化的计算机网络OSI模型中,TCP完成第四层传输层所指定的功
今天给大家带来的是关于Java的相关知识,文章围绕着Java如何实现树的同构展开,文中有非常详细的介绍及代码示例,需求的大佬可以参考下
本文主要介绍了MyBatis-Plus 使用枚举自动关联注入,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起
了SpringBoot集成Redis,并自定义对象序列化操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
此篇文章主要介绍了AtomicReference的出现背景,AtomicReference的使用场景,以及介绍了AtomicReference的源码,重点方法的源码分析
了springboot初始化执行sql语句的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
Nacos 是阿里巴巴推出来的一个新开源项目,这是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。本章节重点给大家介绍SpringCloud Alibaba项目
今天给大家带来的是关于Java的相关知识,文章围绕着java如何集成swagger组件展开,文中有非常详细的介绍及代码示例,需求的大佬可以参考下
今天给大家带来的是关于Java的相关知识,文章围绕着启动Tomcat时出现大量乱码的解决方法展开,文中有非常详细的介绍及图文示例,需求的大佬可以参考下
本文主要介绍了maven实现docker自动化部署插件的使用,分享给大家,感兴趣的小伙伴们可以参考一下
今天给大家带来的是关于Java的相关知识,文章围绕着SpringBoot异常处理流程及原理展开,文中有非常详细的介绍及代码示例,需求的大佬可以参考下
了SpringAop日志找不到方法的处理方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教