首页 > 其他分享 >生成二维码及二维码添加文本及图片

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

时间:2024-03-12 11:00:27浏览次数:25  
标签:java String int image 二维码 添加 new import 文本

 

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

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

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);
    }

 

标签:java,String,int,image,二维码,添加,new,import,文本
From: https://www.cnblogs.com/lewisat/p/18067842

相关文章

  • openlayers2批量添加点
    //初始化地图initMap(){map=newMap({layers:[newTileLayer({source:newOSM(),}),],target:'map',view:newView({center:[116.403218,......
  • UVM宏解释+odt文件转doc+merge命令和difflib+python调用命令+clog2和系统函数+java添
    UVM宏解释UVM_DISABLE_AUTO_ITEM_RECORDINGhttps://blog.csdn.net/MGoop/article/details/127295965itemrecord的方法主要是用于记录事务信息的,原理是调用accept_tr,begin_tr,end_tr。似乎和波形上显示出各个事务相关。默认情况下,在调用get_next_item()和item_done()时自动......
  • Typecho Joe主题添加文章目录导航
    方法和样式参考https://www.wlplove.com/archives/84/1、安装Menutree插件wgethttps://github.com/typecho-fans/plugins/releases/download/plugins-M_to_R/MenuTree.zip解压后放到typecho插件目录2、修改主题模版编辑Joe主题文件夹public/aside.php文件<sectionclass="......
  • ESP32CAM使用Quirc识别二维码并连接WIFI
    ESP32CAM使用Quirc识别二维码并连接WIFI网上有教程,但是是要做出来很难,或者说做出来报错识别不了。前提:搭建好ESP-IDF环境CAMERA能成功初始化此处用的二维码识别库是用的quirc,如下这个和Github下载的差不多,加了个CMakeList,我会把这个传到我的Github上,感兴趣去下载Lesterbor/E......
  • 【C#】HttpWebRequest 接口请求,添加基础Basic认证
    C#,调用对方接口,POST方法,Basic账号密码身份认证。stringurl="";stringaccount="";stringpwd="";JObjectpostData=newJObject();HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(url);request.Method="POST";re......
  • WPF RichTextBox 文本超过限定行数移除旧数据
    在使用serilog.sinks.richtextbox显示日志时,会需要移除旧的日志信息的需求,实现打码如下;根据换行符“\n”进行判断; privatevoidCheckAndRemoveText(){intnewLineCount=0;boolremoveText=false;foreach(Paragraphparagraphin_richTex......
  • aspnet zero 12 添加登录 验证码
       aspnetzero自带的验证码是基于Google,国内当前无法使用,只能替换国内的。实现后的界面如下图: PackageManagerInstall-PackageLazy.Captcha.Core验证码后端代码publicinterfaceICaptchaAppService:IApplicationService{///<summary>......
  • fabricjs怎么添加网格线
    html文件:1<canvasid="c"width="600"height="400"></canvas>css文件:1canvas{2border:1pxsolidlightgrey;3} javascript文件1varcanvas=newfabric.Canvas('c',{2selection:false3});4v......
  • 用vcpkg 和vs2022,使用msvc编译器,怎么添加新的依赖库(包含头文件与dll)
    安装vcpkg:如果您还没有安装vcpkg,可以通过VisualStudioInstaller安装。在安装或修改VisualStudio时,选择“C++桌面开发”,然后勾选“vcpkg-C++库管理器”1。集成vcpkg到VisualStudio:在VisualStudio中,通过“工具”菜单选择“NuGet包管理器->程序包管......
  • 在Chrome添加vue插件
    1.首先打开Chrome的开发者模式:(1)点击浏览器的"设置",再点击"扩展程序”:(2)或者直接点击浏览器右上角的扩展程序:打开右上角的“开发者模式”:2.在github下载vue插件,点击进入下载地址:https://github.com/vuejs/devtools3.依次点击下载:按需要浏览器(Chrome)下载:4.点击添加到......