生成二维码及二维码添加文本及图片

 

 生成二维码及二维码添加文本及图片

如果要输出流,也可以参考此处

package com.myFirstSpring.test;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;


public class Qrcoe
{    
    // 二维码尺寸
    private static final int QRCODE_SIZE = 400;
    // LOGO宽度
    private static final int WIDTH = 60;
    // LOGO高度
    private static final int HEIGHT = 60;
    //logo图片的路径
    private static final String logopath = "D://Qrcoe/logo.jpg"; 
    
    public static void main(String[] args) throws Exception
    {    
        String url =""; //二维码访问地址
        //fileName 二维码图片名称
        String fileName = "";//new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";
        //String path1 = request.getSession().getServletContext().getRealPath("/images/320240jpg.jpg");//获取图像在项目中的路径
        //path 二维码存放路径
        String path ="D://Qrcoe/";// FileSystemView.getFileSystemView().getHomeDirectory() + File.separator + "testQrcode";
        for (int i = 1; i < 2; i++) {
            url = "http://m.xinjuenet.com/evaluation_details?id=28&channel="+i+"";
            fileName = i+".jpg";
            createQrCode(url, path, fileName,logopath); //生成二维码图片
            File qrcFile = new File("D://Qrcoe/",fileName);
            pressText("心觉-咨询平台", qrcFile, 5, Color.black, 16); //图片上添加文本 居中在留白区域
        }
    }
    /**
     * 生成二维码 
     * @param url 访问地址 或者文本内容
     * @param path 生成文件存放路径
     * @param fileName 生成文件名称
     * @param logopath logo图标路径
     * @return
     */
    public static String createQrCode(String url, String path, String fileName,String logopath)
    {
        try
        {
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //设置编码方式
            hints.put(EncodeHintType.MARGIN, 4); 二维码空白区域,最小为0也有白边,只是很小,最小是6像素左右
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
            File file = new File(path, fileName);
            if (file.exists()
                    || ((file.getParentFile().exists() || file.getParentFile().mkdirs()) && file.createNewFile()))
            {
                writeToFile(bitMatrix, "jpg", file,logopath);
                System.out.println("搞定:" + file);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    static void writeToFile(BitMatrix matrix, String format, File file,String logopath) throws IOException
    {
        BufferedImage image = toBufferedImage(matrix,logopath);
        if (!ImageIO.write(image, format, file))
        {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    static void writeToStream(BitMatrix matrix, String format, OutputStream stream,String logopath) throws IOException
    {
        BufferedImage image = toBufferedImage(matrix,logopath);
        if (!ImageIO.write(image, format, stream))
        {
            throw new IOException("Could not write an image of format " + format);
        }
    }

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private static BufferedImage toBufferedImage(BitMatrix matrix,String logopath)
    {
        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) ? BLACK : WHITE);
            }
        }
        
        try {
            // 插入图片  添加logo
            if(logopath !=null && !"".equals(logopath)){
                insertImage(image, logopath, true);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return image;
    }

    /**
     * 在生成的二维码中插入图片
     * @param source
     * @param imgPath
     * @param needCompress
     * @throws Exception
     */
    static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file1 = new File(imgPath);
        if (!file1.exists()) {
            System.err.println("" + imgPath + "   该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }
    /**
     * 给二维码图片加上文字
     * @param pressText 文字
     * @param qrFile  二维码文件
     * @param fontStyle
     * @param color
     * @param fontSize
     */
    public static void pressText(String pressText, File qrFile, int fontStyle, Color color, int fontSize) throws Exception {
     pressText = new String(pressText.getBytes(), "utf-8");
     Image src = ImageIO.read(qrFile);
     int imageW = src.getWidth(null);
     int imageH = src.getHeight(null);
     BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
     Graphics g = image.createGraphics();
     g.drawImage(src, 0, 0, imageW, imageH, null);
     //设置画笔的颜色
     g.setColor(color);
     //设置字体
     Font font = new Font("宋体", fontStyle, fontSize);
     FontMetrics metrics = g.getFontMetrics(font);
     //文字在图片中的坐标 这里设置在中间
     int startX = 150; //(WIDTH - metrics.stringWidth(pressText)) / 2;
     int startY = 380;//HEIGHT/2;
     g.setFont(font);
     g.drawString(pressText, startX, startY);
     g.dispose();
     FileOutputStream out = new FileOutputStream(qrFile);
     ImageIO.write(image, "JPEG", out);
     out.close();
     System.out.println("二维码添加文本成功");
    }
}

  

 此处需要继承 import cn.hutool.extra.qrcode.QrCodeUtil;

 也可以通过QrCodeUtil 直接生成二维码

    public static String generateBase64(String content, String pressText){
        QrConfig config = new QrConfig().setHeight(400).setWidth(400).setMargin(3).setCharset(Charset.forName("UTF-8"));
        BufferedImage imageSource = generate(content, config);
        if(StringUtils.isNotBlank(pressText)){
            int imageW = imageSource.getWidth(null);
            int imageH = imageSource.getHeight(null);
            BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            g.drawImage(imageSource, 0, 0, imageW, imageH, null);
            g.setColor(Color.black);
            //文字在图片中的坐标 这里设置在中间
            int startX = 150;//(WIDTH - metrics.stringWidth(pressText)) / 2;
            int startY = 380;//HEIGHT/2;
            g.setFont(new Font("宋体", 5, 16));
            g.drawString(pressText, startX, startY);
            g.dispose();
            return ImgUtil.toBase64DataUri(image, ImgUtil.IMAGE_TYPE_JPEG);
        }
        return ImgUtil.toBase64DataUri(imageSource, ImgUtil.IMAGE_TYPE_JPEG);
    }

 

posted on 2024-03-12 10:56  lewisat  阅读(91)  评论(0编辑  收藏  举报

导航