Java实现画图

DevToCoding | Java面试指南、学习笔记

 

目录

1.导入依赖

2.1工具类

2.2 工具类

2.3 工具类

3.测试接口

4.页面效果


1.导入依赖

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

2.1工具类

package com.github.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;
        }
    }
}

2.2 工具类

package com.github.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;
}

2.3 工具类

package com.github.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;
}

3.测试接口

package com.github.controller.meetingApply;

import com.github.pojo.meetingApply.MeetingApply;
import com.github.dcp.pojo.meetingApply.MeetingGuestCardTemplate;
import com.github.dcp.service.meetingApply.MeetingApplyService;
import com.github.dcp.service.meetingApply.MeetingGuestCardTemplateService;
import com.github.dcp.util.*;
import com.github.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");
                    ImageIO.write(bufferedImage, "jpg", os);

                    //更新meetingApply的状态
                    MeetingApply apply = new MeetingApply();
                    apply.setId(meetingApply.getId());
                    apply.setCreateCardDate(new Date());
                    apply.setIsCreateCard("Yes");
                    apply.setCardUrl("generateGuestCard/" + datePath + String.valueOf(i + 1) + name + ".jpg");
                    meetingApplyService.update(apply);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            String zipFile = CompressUtil.zipFile(new File(zipPath), "zip");
            response.setContentType("APPLICATION/OCTET-STREAM");
            String fileName = "guestCard" + uuid + ".zip";
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            //ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
            OutputStream out = response.getOutputStream();
            File ftp = ResourceUtils.getFile(zipFile);
            InputStream in = new FileInputStream(ftp);

            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            in.close();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

4.页面效果

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
实现一个画图编辑器,需要掌握以下几个方面的知识: 1. Java 的图形界面编程:Java 提供了许多图形界面编程的工具包,如 AWT、Swing 和 JavaFX。其中,Swing 是最常用的一个,它提供了一系列组件和容器,可以用于构建用户界面。 2. 图形绘制:Java 的 Graphics 类提供了许多绘图方法,可以用于在组件上绘制各种图形,如直线、矩形、圆形、椭圆等。此外,还可以使用 Graphics2D 类进行更高级的绘图操作,如绘制渐变、阴影等。 3. 鼠标事件处理:画图编辑器需要支持鼠标操作,如点击、拖拽、释放等事件,需要使用 Java 提供的 MouseListener 和 MouseMotionListener 接口来处理这些事件。 4. 文件读写:画图编辑器需要支持将绘制的图形保存到文件中,以及从文件中加载已有的图形。Java 提供了许多文件读写的类和接口,如 File、FileReader、FileWriter 等。 下面是一个简单的画图编辑器的实现步骤: 1. 创建一个 JFrame 窗口,并添加一个 JPanel 组件用于绘制图形。 2. 在 JPanel 组件上重写 paintComponent 方法,使用 Graphics 类提供的方法绘制图形。 3. 使用 MouseListener 和 MouseMotionListener 接口处理鼠标事件,根据事件类型调用不同的绘图方法。 4. 添加菜单栏和工具栏,并在菜单栏和工具栏上添加绘图工具,如画笔、直线、矩形、圆形等。 5. 实现保存和加载功能,将绘制的图形保存到文件中,以及从文件中加载已有的图形。 注意事项: 1. 在绘制图形时,需要注意 Graphics 类的一些特性,如颜色、线条粗细、填充模式等。 2. 在处理鼠标事件时,需要注意鼠标坐标与组件坐标的转换,以及鼠标操作的顺序和逻辑。 3. 在实现保存和加载功能时,需要注意文件格式的选择和读写方法的正确使用。 以上是一个简单的画图编辑器的实现步骤和注意事项,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿里巴巴P8技术专家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值