# 前言 例如:生成分享海报,比如注册扫二维码登录.分享商品海报等!本博文是基于springboot工程得!

一、使用步骤

1.导入pom依赖和上传图片到工程

代码如下(示例):在自己得通用工具类模块中导入坐标!(这需要根据自己得工程来)

 <!--谷歌图片压缩-->
        <dependency>
            <groupid>net.coobird</groupid>
            <artifactid>thumbnailator</artifactid>
        </dependency>
        <!--谷歌图片压缩-->
        <dependency>
            <groupid>com.google.guava</groupid>
            <artifactid>guava</artifactid>
        </dependency>
        <!--生成二维码-->
        <dependency>
            <groupid>cn.hutool</groupid>
            <artifactid>hutool-extra</artifactid>
            <version>5.4.3</version>
        </dependency>
        <dependency>
            <groupid>com.google.zxing</groupid>
            <artifactid>core</artifactid>
            <version>3.3.3</version>
        </dependency>
        <!--生成二维码-->

代码如下(示例):
这里是要生成海报的模板和二维码的logo

2.创建生成接口

代码如下(示例):
@loginuser:是自定义注解获取jwt的用户id(根据自己的需求和工程来)
@nologin:是项目种的白名单,不需要携带token的注解

  /**
     * 生成用户的邀请二维码
     *
     * @param userid 用户id
     */
    @getmapping("qrcode")
    @nologin
    public object qrcode(@loginuser integer userid) {
        //判断用户id是否为空
        if (userid == null) {
            return responseutil.fail("请选择用户");
        }
        //获取生成海报的图片路径
        string filepath = wxuserservice.qrcode(userid);
        return responseutil.ok(filepath);
    }

3.创建service层

代码如下(示例):
这是一个接口!需要自己实现该接口!实现接口代码在下面!

   /**
     * 根据用户的邀请码生成分享海报
     *
     * @param userid
     * @return
     */
    string qrcode(integer userid);

代码如下(示例):
上面接口的实现类

  /**
     * 根据用户的邀请码生成分享海报
     *
     * @param userid
     * @return
     */
    @override
    public string qrcode(integer userid) {
        try {
            // 根据用户id查询验证码
            userinfo userinfo = userservice.selectbyid(userid);
            //判断是否库是否存在海报地址
            if (!stringutils.isempty(userinfo.getposter())) {
                return userinfo.getposter();
            }
            //要生成海报的模板(一般在springboot工程的 resources下 我的工程路径:templates/poster/xjcq.png  可以改成自己工程需要的路径)
            file hbpath = resourceutils.getfile("classpath:templates/poster/xjcq.png");
            //要生成二维码的logo(一般在springboot工程的 resources下 我的工程路径:templates/poster/xjcqlogo.png 可以改成自己工程需要的路径)
            file logopath = resourceutils.getfile("classpath:templates/poster/xjcqlogo.png");
            // 获取上传后的路径
            string filepath = imageutil.drawstring(qrcodeinvitescheme + userinfo.getinvitecode(), userinfo.getinvitecode(), userinfo.getinvitecode(), hbpath, logopath);
            //file转multipartfile(因为我们的oss是转multipartfile)
            file file = new file(filepath);
            inputstream inputstream = new fileinputstream(file);
            multipartfile multipartfile = new mockmultipartfile(file.getname(), file.getname(),
                    contenttype.application_octet_stream.tostring(), inputstream);
            //上转至阿里云
            string s = storageutil.uploadossfile(multipartfile);
            //更改数据库
            userinfo updateuserinfo = new userinfo();
            updateuserinfo.setid(userinfo.getid());
            updateuserinfo.setposter(s);
            userservice.updatebyid(updateuserinfo);
            return updateuserinfo.getposter();
        } catch (filenotfoundexception e) {
            log.error("文件找不到:{}", e);
        } catch (ioexception e) {
            log.error("io异常:{}", e);
        }
        return null;
    }

4.生成海报的工具类

代码如下(示例):
wordpath类的代码,可以参考一下java获取yml配置文件内容

package com.legend.core.config;


import lombok.data;
import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;

/**
 * 获取全局配置path
 * @author admin
 */
@component
@data
public class wordpath {
     //生成电子合同的路径
     @value("${word.path}")
     private string wordpath;
     //生成海报的路径
     @value("${poster.path}")
     private string posterpath;
}

代码如下(示例):
wordpath: 这个是我把要生成画报地址的路径配置到了yml中了,因为测试的使用用的是winodows,上了生产就用linux服务器了。所以配置到了yml中了

package com.legend.core.util;

import cn.hutool.extra.qrcode.qrcodeutil;
import cn.hutool.extra.qrcode.qrconfig;
import com.google.zxing.qrcode.decoder.errorcorrectionlevel;
import com.legend.core.config.wordpath;
import lombok.extern.slf4j.slf4j;
import org.apache.commons.io.ioutils;
import org.springframework.core.io.defaultresourceloader;
import org.springframework.core.io.resourceloader;
import org.springframework.stereotype.service;

import javax.annotation.resource;
import javax.imageio.imageio;
import javax.imageio.stream.imageoutputstream;
import java.awt.*;
import java.awt.image.bufferedimage;
import java.io.*;

/**
 * 生成分享好友
 *
 * @author 生成分享好友
 */
@service
@slf4j
public class imageutil {
    //我把生成海报地址的路径配置到了springboot的yml配置文件中了
    @resource
    private wordpath wordpath;

    /**
     * 生成海报
     *
     * @param content  二维码内容
     * @param written  文字内容
     * @param filepath 保存文件 例:1.png    (d:/1.png)
     * @param hbpath   海报图片地址 例:1.png   (d:/1.png)
     * @param logopath 二维码logo
     * @return
     * @author uncle
     * @description 在一张背景图上添加二维码
     * @date 2020-09-28 23:59
     */
    public string drawstring(string content, string written, string filepath, file hbpath, file logopath) {
        try {
            bufferedimage image = addwater(content, hbpath, logopath);
            graphics2d gd = image.creategraphics();
            // 3、设置对线段的锯齿状边缘处理
            gd.setrenderinghint(renderinghints.key_interpolation, renderinghints.value_interpolation_bilinear);
            // 5、设置水印文字颜色
            gd.setcolor(color.darkgray);
            // 6、设置水印文字font
            gd.setfont(new font("苹方", font.plain, 32));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
            gd.drawstring(written, 440, 1122);
            gd.dispose();

            bytearrayoutputstream bs = new bytearrayoutputstream();
            imageoutputstream imout = imageio.createimageoutputstream(bs);
            imageio.write(image, "png", imout);
            inputstream inputstream = new bytearrayinputstream(bs.tobytearray());

            // 获取yml海报的配置
            string file = wordpath.getposterpath() + filepath + ".png";
            if (!new file(wordpath.getposterpath()).exists()) {
                new file(wordpath.getposterpath()).mkdirs();
            }
            outputstream outstream = new fileoutputstream(file);
            ioutils.copy(inputstream, outstream);
            inputstream.close();
            outstream.close();
            // 返回文件地址
            return file;
        } catch (exception e) {
            log.error("海报生成失败:", e);
        }
        return null;
    }


    /***
     * 在一张背景图上添加二维码
     */
    public bufferedimage addwater(string content, file hbpath, file logopath) throws exception {
        // 读取原图片信息
        //得到文件
        //file file = new file(hbpath);
        //文件转化为图片
        image srcimg = imageio.read(hbpath);
        //获取图片的宽
        int srcimgwidth = srcimg.getwidth(null);
        //获取图片的高
        int srcimgheight = srcimg.getheight(null);
        // 加水印
        bufferedimage bufimg = new bufferedimage(srcimgwidth, srcimgheight, bufferedimage.type_int_rgb);
        graphics2d g = bufimg.creategraphics();
        g.drawimage(srcimg, 0, 0, srcimgwidth, srcimgheight, null);
        //使用工具类生成二维码
        image image = createqrcode(content, 230, 230, logopath);
        //将小图片绘到大图片上,500,300 .表示你的小图片在大图片上的位置。
        g.drawimage(image, 25, 1070, null);
        //设置颜色。
        g.setcolor(color.white);
        g.dispose();
        return bufimg;
    }

    private bufferedimage createqrcode(string content, int width, int height, file logopath) throws ioexception {
        qrconfig config = new qrconfig(width, height);
        if (logopath != null) {
            image image = imageio.read(new fileinputstream(logopath));
            config.setimg(image);
        }
        config.seterrorcorrection(errorcorrectionlevel.h);
        return qrcodeutil.generate(
                content,
                config);
    }

    public inputstream resourceloader(string filefullpath) throws ioexception {
        resourceloader resourceloader = new defaultresourceloader();
        return resourceloader.getresource(filefullpath).getinputstream();
    }

}


总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了如何生成分享海报。例如:以上就是今天要讲的内容,本文仅仅简单介绍了如何生成分享海报。

以上就是java 生成分享海报工具类的详细内容,更多关于java 生成分享海报工具类的资料请关注www.887551.com其它相关文章!