java Graphics2D.class 绘图并下载文件

package hanjq.hanjqtest.idcard;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.awt.image.BufferedImageGraphicsConfig;
import sun.java2d.SunGraphics2D;
import sun.java2d.SurfaceData;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;

@RestController
public class IdCardController {

    //下载单个文件
    @GetMapping("/hanjq/test")
    public HttpServletResponse test(HttpServletResponse response) throws IOException, WriterException {
        String deviceId = "hanjq";
        File file = new File("C:\\Users\\Administrator\\Desktop\\临时文件\\201811091614136373.jpg");
        int width = 420;  //图片的宽度
        int height = 228; //图片的高度

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        BufferedImageGraphicsConfig config = BufferedImageGraphicsConfig.getConfig(image);
        image =config.createCompatibleImage(width, height, Transparency.TRANSLUCENT);

        /**************** 主版底色边框 *************/
        Graphics2D main = image.createGraphics();
        //白底填充整个屏幕
//        main.fillRect(10,10,300,150);
        //控制线段的颜色类型
//        BasicStroke bs=new BasicStroke(1.0f);
//        main.setStroke(bs);
        //消除锯齿边缘
        main.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        RoundRectangle2D rect=new RoundRectangle2D.Double(0,0,width-1,height-1,20,20);
        main.setColor(new Color(0xD2D2D2));
        main.draw(rect);

        //外层边框
//        main.setColor(new Color(0xD2D2D2));
//        main.setColor(Color.green);
//        main.drawRect(1,1,width,height);
//        main.drawRect(-1,-1,width,height);

        /********** 插入设备图 *************/
        Graphics2D mainPic = image.createGraphics();
        BufferedImage bimg = null;
        try {
            bimg = javax.imageio.ImageIO.read(file);
        } catch (Exception e) {}
        //设备图片位置
        if(bimg!=null){
            mainPic.drawImage(bimg, 20, 20, 153, 120, null);
            mainPic.setColor(new Color(0xF2F2F2));
            mainPic.drawRect(20,20,153,120);
            mainPic.dispose();

            //消除锯齿边缘
            mainPic.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
            RoundRectangle2D rect1=new RoundRectangle2D.Double(0,0,width-1,height-1,20,20);
            mainPic.setColor(new Color(0xD2D2D2));
            mainPic.draw(rect1);
        }

        /************************* 文字位置 **************************/
        //设备编码
        Graphics2D tip1 = image.createGraphics();
        //设置字体颜色
        tip1.setColor(new Color(0x333333));
        //设置字体
        Font tipFont1 = new Font("宋体", Font.BOLD, 20);
        tip1.setFont(tipFont1);
        String deviceName = "数据传输仪";
        tip1.drawString(deviceName, 192, 55);

        Graphics2D tip2 = image.createGraphics();
        //设置区域颜色
        tip2.setColor(new Color(0x666666));
        //设置字体
        Font tipFont2 = new Font("宋体", Font.BOLD, 14);
        tip2.setFont(tipFont2);
        String deviceRemark = "出水口环保数采仪";
        tip2.drawString(deviceRemark, 192, 92);

        Graphics2D tip3 = image.createGraphics();
        //设置区域颜色
        tip3.setColor(new Color(0x999999));
        //设置字体
        Font tipFont3 = new Font("宋体", Font.BOLD, 14);
        tip3.setFont(tipFont3);
        String deviceCode = "0101010101010101010";
        tip3.drawString(deviceCode, 192, 122);

        Graphics2D tip4 = image.createGraphics();
        //设置区域颜色
        tip4.setColor(new Color(0xAEAEAE));
        //设置字体
        Font tipFont4 = new Font("宋体", Font.BOLD, 14);
        tip4.setFont(tipFont4);
        String QRCode = "扫描二维码在手机上查看设备信息";
        tip4.drawString(QRCode, 110, 187);

        /***********    插入中间广告图 二维码图片的位置  ***********/
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET,  "UTF-8");
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(deviceId,
                BarcodeFormat.QR_CODE, 54, 54, hints);
        BufferedImage images = toBufferedImage(bitMatrix);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(images, "png", os);
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        Graphics mainPic2 = image.getGraphics();
        BufferedImage bimg2 = null;
        try {
            bimg2 = javax.imageio.ImageIO.read(input);//二维码图片
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(bimg2!=null){
            mainPic2.drawImage(bimg2, 346, 154,54, 54, null);
            mainPic2.setColor(new Color(0xF2F2F2));
            mainPic2.drawRect(346,154,54,54);
            mainPic2.dispose();
        }

        /**********************  下载 ************/
        try {
            File pngFile = new File(deviceCode+".png");
            file.renameTo(pngFile);
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(pngFile.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + pngFile.getName());
            response.addHeader("Content-Length", "" + pngFile.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            ImageIO.write(image, "png", toClient);//写入流中
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

    public  BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }
}
    /**
     * 示例 下载多个文件
     * @Description 设备2.2接入弹窗名片
     * @Author hanjq
     * @Date 2021年6月16日14:26:35
     */
    @Override
    public List<Map<String,String>> getDeviceCard(HttpServletRequest request, HttpServletResponse response, List<String> deviceIds) throws IOException, WriterException {
        List<DeviceParametersVO> device =mapper.downPic(deviceIds);
        List<Map<String,String>> resList= new ArrayList<>();
        for(DeviceParametersVO i:device){
            if(StringUtils.isNotBlank(i.getImgUrl())){
                File file = getFileByUrl(i.getImgUrl());
                Map map = new HashMap();
                this.getDeviceCardFile(response,i,file);
                map.put(i.getDeviceId(), this.getDeviceCardFile(response,i,file));
                resList.add(map);
            }else{
                if(StringUtils.isNotBlank(i.getBdImgUrl())){
                    File file = getFileByUrl(i.getBdImgUrl());
                    Map map = new HashMap();
                    this.getDeviceCardFile(response,i,file);
                    map.put(i.getDeviceId(), this.getDeviceCardFile(response,i,file));
                    resList.add(map);
                }else{
                    if(StringUtils.isNotBlank(i.getDcImgUrl())){
                        File file = getFileByUrl(i.getDcImgUrl());
                        Map map = new HashMap();
                        this.getDeviceCardFile(response,i,file);
                        map.put(i.getDeviceId(), this.getDeviceCardFile(response,i,file));
                        resList.add(map);
                    }
                }
            }
        }
        return resList;
    }

    /**
     * @MethodName: graphicsGeneration
     * @Description: 生成自定图片 v2.2
     * @Param deviceName
     * @Return void
     * @Author: hanjq
     * @Date: 2021-6-25 09:39:49
     **/
    //生成自定义图片
    public String getDeviceCardFile(HttpServletResponse response,DeviceParametersVO device, File file) throws WriterException, IOException {

        /****************** 创建画板 **************************/
        int width = 420;  //图片的宽度
        int height = 228; //图片的高度
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        BufferedImageGraphicsConfig config = BufferedImageGraphicsConfig.getConfig(image);
        image =config.createCompatibleImage(width, height, Transparency.TRANSLUCENT);

        /**************** 主版底色边框 *************/
        Graphics2D main = image.createGraphics();
        //白底填充整个屏幕
//        main.fillRect(10,10,300,150);
        //控制线段的颜色类型
//        BasicStroke bs=new BasicStroke(1.0f);
//        main.setStroke(bs);
        //消除锯齿边缘
        main.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        RoundRectangle2D rect=new RoundRectangle2D.Double(0,0,width-1,height-1,20,20);
        main.setColor(new Color(0xD2D2D2));
        main.draw(rect);

        //外层边框
//        main.setColor(new Color(0xD2D2D2));
//        main.setColor(Color.green);
//        main.drawRect(1,1,width,height);
//        main.drawRect(-1,-1,width,height);

        /********** 插入设备图 *************/
        Graphics2D mainPic = image.createGraphics();
        BufferedImage bimg = null;
        try {
            bimg = javax.imageio.ImageIO.read(file);
        } catch (Exception e) {}
        //设备图片位置
        if(bimg!=null){
            mainPic.drawImage(bimg, 20, 20, 153, 120, null);
            mainPic.setColor(new Color(0xF2F2F2));
            mainPic.drawRect(20,20,153,120);
            mainPic.dispose();

            //消除锯齿边缘
            mainPic.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
            RoundRectangle2D rect1=new RoundRectangle2D.Double(0,0,width-1,height-1,20,20);
            mainPic.setColor(new Color(0xD2D2D2));
            mainPic.draw(rect1);
        }

        /************************* 文字位置 **************************/
        //设备编码
        Graphics2D tip1 = image.createGraphics();
        //设置字体颜色
        tip1.setColor(new Color(0x333333));
        //设置字体
        Font tipFont1 = new Font("宋体", Font.BOLD, 20);
        tip1.setFont(tipFont1);
        tip1.drawString(device.getDeviceCategoryName() == null ? "" : device.getDeviceCategoryName(), 192, 55);

        Graphics2D tip2 = image.createGraphics();
        //设置区域颜色
        tip2.setColor(new Color(0x666666));
        //设置字体
        Font tipFont2 = new Font("宋体", Font.BOLD, 14);
        tip2.setFont(tipFont2);
        tip2.drawString(device.getDeviceName() == null ? "" : device.getDeviceName(), 192, 92);

        Graphics2D tip3 = image.createGraphics();
        //设置区域颜色
        tip3.setColor(new Color(0x999999));
        //设置字体
        Font tipFont3 = new Font("宋体", Font.BOLD, 14);
        tip3.setFont(tipFont3);
        tip3.drawString(device.getDeviceCode() == null ? "" : device.getDeviceCode(), 192, 122);

        Graphics2D tip4 = image.createGraphics();
        //设置区域颜色
        tip4.setColor(new Color(0xAEAEAE));
        //设置字体
        Font tipFont4 = new Font("宋体", Font.BOLD, 14);
        tip4.setFont(tipFont4);
        tip4.drawString(QRCode, 110, 187);

        /***********    插入中间广告图 二维码图片的位置  ***********/
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET,  "UTF-8");
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(device.getDeviceCode(),
                BarcodeFormat.QR_CODE, 54, 54, hints);
        BufferedImage images = toBufferedImage(bitMatrix);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(images, "png", os);
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        Graphics mainPic2 = image.getGraphics();
        BufferedImage bimg2 = null;
        try {
            bimg2 = javax.imageio.ImageIO.read(input);//二维码图片
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(bimg2!=null){
            mainPic2.drawImage(bimg2, 346, 154,54, 54, null);
            mainPic2.setColor(new Color(0xF2F2F2));
            mainPic2.drawRect(346,154,54,54);
            mainPic2.dispose();
        }
        return createImagesV2(image);
    }

    //生成base64字符图片
    @SuppressWarnings("restriction")
    public String createImagesV2(BufferedImage image) {
        BufferedOutputStream bos = null;
        String png_base64="";
        if(image != null){
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
                ImageIO.write(image, "png", baos);//写入流中

                byte[] bytes = baos.toByteArray();//转换成字节
                BASE64Encoder encoder = new BASE64Encoder();
                png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
                //转中文格式
                png_base64 = new String(png_base64.getBytes("ISO-8859-1"),"utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(bos!=null){//关闭输出流
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return png_base64;
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值