微信小程序拍照后上传并且添加字体

时间:2024-04-14 20:45:58

1、思路

微信小程序拍照上传并且加字体,本来是准备在前端处理,后来发现前端只能用原生组件处理.但是效果清晰度都不理想,以下是前端处理方法

watermark(item) {
    let _this = this
    //获取图片详细信息
    wx.getImageInfo({
      src: item,
      success: (ress) => {
        console.log("获取图片详情", item)
        console.log("获取详情成功", ress)
        let date = util.formatTime(new Date());
        let ctx = wx.createCanvasContext(\'firstCanvas\')
        _this.setData({
          canvasHeight: ress.height,
          canvasWidth: ress.width
        })
        //将图片src放到cancas内,宽高为图片大小
        ctx.drawImage(item, 0, 0, 80, 80)
        //将声明的时间放入canvas
        ctx.setFontSize(10) //注意:设置文字大小必须放在填充文字之前,否则不生效
        ctx.setFillStyle(\'grey\')
        ctx.fillText("运联快车", 0, 30)
        ctx.strokeText("运联快车", 0, 30)
        wx.showToast({
          title: \'分享图片生成中...\',
          icon: \'loading\',
          duration: 1000
        });
        ctx.draw(false, setTimeout(() => {
          debugger
          wx.canvasToTempFilePath({
            canvasId: \'firstCanvas\',
            success: (res) => {
              debugger
              console.log(res.tempFilePath + "123");
              _this.data.fileList.push({
                ...file,
                url: file.tempFilePath
              });
              _this.setData({
                fileList
              });
            },
            fail: (e) => {
              console.log(e)
            }
          },_this)
        }),300)
      }


    })

然后换了个思路,打算后端(java)处理

/**
     *
     * @param path 原图路径
     * @param remark 封装了向原图中插入的信息
     */
    public static void panAlter(String path, String remark) {


        PngAlterUtil pngAlterUtil = new PngAlterUtil();
        //导入本地图片到缓冲区
        BufferedImage img1 = pngAlterUtil.loadImageLocal(path);
        //修改图片,返回修改后的图片缓冲区
        BufferedImage image = pngAlterUtil.modifyImage(img1, null, null, null, remark, 10, 40, 0);
        //将生成的新lable保存到本地
        pngAlterUtil.writeImageLocal(path, image);
    }
  
  
  package cn.wisestar.irm.wechat.beans;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;

/**
 * @author fulipeng
 */
public class PngAlterUtil {

    /**
     * 添加字体的属性设置
     */
    private Font font = new Font("微软雅黑", Font.BOLD, 18);
    private Graphics2D g = null;
    private int fontsize = 0;
    private int x = 0;
    private int y = 0;
    private static int z = 0;

    /**
     * 导入本地图片到缓冲区
     */
    public BufferedImage loadImageLocal(String imgName) {
        BufferedImage read = null;
        try {
            read = ImageIO.read(new File(imgName));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return read;
    }

    /**
     * 生成图片到本地
     */
    public void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                ImageIO.write(img, "jpg", outputfile);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 修改图片,返回修改后的图片缓冲区
     */
    public BufferedImage modifyImage(BufferedImage img, BufferedImage imgs1, BufferedImage imgs2, BufferedImage imgs3, Object content, int x, int y, int j) {
        try {

            if (j >= z) {
                font = new Font("微软雅黑", Font.BOLD, 22);
            }


            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();

            //遮盖原本模板
            if (imgs1 != null) {
                ImageObserver observer = new Checkbox();
                g.drawImage(imgs1, 5, 270, observer);
            }
            if (imgs2 != null) {
                ImageObserver observer = new Checkbox();
                g.drawImage(imgs2, 5, 470, observer);
            }
            if (imgs3 != null) {
                ImageObserver observer = new Checkbox();
                g.drawImage(imgs3, 205, 1010, observer);
            }

            //设置背景颜色
            g.setBackground(Color.WHITE);
            //设置字体颜色
            g.setColor(Color.BLACK);
            if (this.font != null) {
                g.setFont(this.font);
            }
            //验证输出位置的纵坐标和横坐标
            if (x >= h || y >= w) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (content != null) {
                g.drawString(content.toString(), this.x, this.y);
            }
            g.dispose();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return img;
    }
}

可行