fasrDfs配合zxing(背景图合成二维码,上传,下载)

FastDfs的使用案例(实战)

pom.xml文档

		<dependency>
            <groupId>org.csource</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27-RELEASE</version>
 		 </dependency>
     <!-- 二维码支持包 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>

       <dependency>
            <groupId>net.glxn</groupId>
            <artifactId>qrgen</artifactId>
            <version>1.4</version>
       </dependency>

注意事项:

maven仓库没有该依赖需要手动打成jar包,然后引入仓库,这里是1.27版本(网上也有教程)。

1.cmd命令下执行.
2,mvn install:install-file -Dfile=fastdfs-client-java-1.27-SNAPSHOT.jar -DgroupId=com.zl -DartifactId=fastdfs-client -Dversion=1.27 -Dpackaging=jar

创建fastdfs(工具包)
包下创建DownloadFileWriter类

/**
 * Copyright (C) 2008 Happy Fish / YuQing
 * <p>
 * FastDFS Java Client may be copied only under the terms of the GNU Lesser
 * General Public License (LGPL).
 * Please visit the FastDFS Home Page http://www.csource.org/ for more detail.
 */

package cn.zl.demo.common;

import org.csource.fastdfs.DownloadCallback;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件下载写本地磁盘的
 *
 * @author Happy Fish / YuQing
 * @version Version 1.3
 */
public class DownloadFileWriter implements DownloadCallback {
  private String filename;
  private FileOutputStream out = null;
  private long current_bytes = 0;

  /**
   *  文件完整路径
   * @param filename
   */
  public DownloadFileWriter(String filename) {
    this.filename = filename;
  }


  public int download( byte[] data){
    return this.recv(data.length,data,data.length);
  }
  /**
   * 下载文件
   * @param file_size  总长度
   * @param data     二进制
   * @param bytes    下载速度
   * @return
   */
  @Deprecated
  public int recv(long file_size, byte[] data, int bytes) {
    try {
      if (this.out == null) {
        this.out = new FileOutputStream(this.filename);
      }

      this.out.write(data, 0, bytes);
      this.current_bytes += bytes;

      if (this.current_bytes == file_size) {
        this.out.close();
        this.out = null;
        this.current_bytes = 0;
      }
    } catch (IOException ex) {
      ex.printStackTrace();
      return -1;
    }

    return 0;
  }

  protected void finalize() throws Throwable {
    if (this.out != null) {
      this.out.close();
      this.out = null;
    }
  }
}


包下创建FastDFSUtil类

package com.sjzew.allySystem.util.fastdfs;

import org.csource.fastdfs.*;
import org.springframework.stereotype.Component;

@Component
public class FastDFSUtil {

    private static TrackerServer ts;
    private static StorageServer ss;

    //加载配置信息(加一次)
    static {
        try {
            ClientGlobal.init("fdfs_client.properties");
            TrackerGroup tg = new TrackerGroup(ClientGlobal.getG_tracker_group().tracker_servers);
            //上传客户端
            TrackerClient tc = new TrackerClient(tg);
            //得到tracker服务器
            ts = tc.getConnection();
            if (ts == null) {
                throw new Exception("没有连接到fastdfs追踪服务器");
            }

            //存储服务器
            ss = tc.getStoreStorage(ts);
            if (ss == null) {
                throw new Exception("没有连接到fastdfs存储服务器");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到fastdfs客户端
     *
     * @return
     */
    public StorageClient1 getStorageClient() {
        return new StorageClient1(ts, ss);
    }

}


创建image包(生成二维码的工具类)
包下QRCodeMax类

package com.sjzew.allySystem.util.image;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
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;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;

/**
 * 类名称:QRCodeMax
 * 类描述:生成二维码图片+背景+文字描述工具类
 */
@Slf4j
public class QRCodeMax {
    private static final int QRCOLOR = 0x201f1f; // 二维码颜色:黑色
    private static final int BGWHITE = 0xFFFFFF; //二维码背景颜色:白色
    private static final int width = 120;//二维码宽度
    private static final int height = 120;//二维码高度
    private static final String note1 = "";//文字描述1
    private static final String note2 = "";//文字描述2
    private static final int size = 38;//文字大小
    private static final int text1x=0;//文字描述1 x轴方向
    private static final int text1y=0;//文字描述1 y轴方向
    private static final int text2x=0;//文字描述2 x轴方向
    private static final int text2y=0;//文字描述2 y轴方向
    private static String imgPath = "";//合成图片路径
    // 设置QR二维码参数信息
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {

        private static final long serialVersionUID = 1L;
        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)
            put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
            put(EncodeHintType.MARGIN, 0);// 白边
        }
    };
    /**
     * 合成二维码图片
     *
     * @param background  背景图服务器地址
     * @param url 二维码内容
     * @param x  数字越大二维码越靠左
     * @param y  数字越大二维码越靠下
     */
    public static String synthesis(String background, String url,int x,int y) {
        File backgroundFile = getFileByUrl(background,"png");
        CreatQRCode(backgroundFile, backgroundFile, width, height, url, note1, note2, size, x, y, text1x, text1y, text2x, text2y);
        return imgPath;
    }

    /**
     * 服务器图片url地址转file
     *
     * @param fileUrl  背景图服务器地址
     * @param suffix 后缀图片格式
     */
    private static File getFileByUrl(String fileUrl, String suffix) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        BufferedOutputStream stream = null;
        InputStream inputStream = null;
        File file = null;
        try {
            URL imageUrl = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            file = File.createTempFile("spread", "." + suffix);
            imgPath = file.getCanonicalPath();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fileOutputStream);
            stream.write(outStream.toByteArray());
        } catch (Exception e) {
            log.error("获取服务器图片异常:" + e);
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (stream != null) stream.close();
                outStream.close();
            } catch (Exception e) {
                log.error("关闭流异常:" + e);
            }
        }
        return file;
    }

    /**
     * 生成二维码图片+背景+文字描述
     *
     * @param codeFile  生成图地址
     * @param bgImgFile 背景图地址
     * @param WIDTH     二维码宽度
     * @param HEIGHT    二维码高度
     * @param qrUrl     二维码识别地址
     * @param note1      文字描述1
     * @param note2       文字描述2
     * @param size      文字大小
     * @param imagesX   二维码x轴方向
     * @param imagesY   二维码y轴方向
     * @param text1X    文字描述1x轴方向
     * @param text1Y    文字描述1y轴方向
     * @param text2X    文字描述2x轴方向
     * @param text2Y    文字描述2y轴方向
     */
    private static void CreatQRCode(File codeFile, File bgImgFile, Integer WIDTH, Integer HEIGHT, String qrUrl,
                                   String note1, String note2, Integer size, Integer imagesX, Integer imagesY,
                                    Integer text1X, Integer text1Y, Integer text2X, Integer text2Y) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为: 编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF) 白(0xFF000000)两色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
            /*
             * 	添加背景图片
             */
            BufferedImage backgroundImage = ImageIO.read(bgImgFile);
            int bgWidth = backgroundImage.getWidth();
            int qrWidth = image.getWidth();
            //距离背景图片x边的距离,居中显示
            int disx = (bgWidth - qrWidth) - imagesX;
            //距离y边距离 * * * *
            int disy = imagesY;
            Graphics2D rng = backgroundImage.createGraphics();
            rng.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
            rng.drawImage(image, disx, disy, WIDTH, HEIGHT, null);

            /*
             * 	文字描述参数设置
             */

            Color textColor = Color.white;
            rng.setColor(textColor);
            rng.drawImage(backgroundImage, 0, 0, null);
            //设置字体类型和大小(BOLD加粗/ PLAIN平常)
            rng.setFont(new Font("微软雅黑,Arial", Font.BOLD, size));
            //设置字体颜色
            rng.setColor(Color.black);
            int strWidth = rng.getFontMetrics().stringWidth(note1);

            //文字1显示位置
            int disx1 = (bgWidth - strWidth) - text1X;//左右
            rng.drawString(note1, disx1, text1Y);//上下

            //文字2显示位置
            int disx2 = (bgWidth - strWidth) - text2X;//左右
            rng.drawString(note2, disx2, text2Y);//上下

            rng.dispose();
            image = backgroundImage;
            image.flush();
            ImageIO.write(image, "png", codeFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

controller类

package com.sjzew.allySystem.controller.fastdfs;

import com.sjzew.allySystem.entity.SystemImgs;
import com.sjzew.allySystem.entity.UserImgs;
import com.sjzew.allySystem.entity.Users;
import com.sjzew.allySystem.superPack.SuperController;
import com.sjzew.allySystem.util.image.QRCodeMax;
import com.sjzew.allySystem.util.jsonVo.Json;
import com.sjzew.allySystem.util.search.Criterion;
import com.sjzew.allySystem.util.search.SearchParameter;
import com.sjzew.allySystem.util.search.SignEnum;
import org.csource.common.MyException;
import org.csource.fastdfs.StorageClient1;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
public class Synthesis extends SuperController {

    @RequestMapping(value = "/synthesis", method = RequestMethod.GET)
    public Json synthesis(){
        Map data = new HashMap();
        SearchParameter parameter = new SearchParameter();
        parameter.addParameter(new Criterion("picture", SignEnum.eq,"商城海报"));
        List<SystemImgs> systemImgs = systemImgsService.search(parameter);
        data.put("mallPoster",systemImgs);
        SearchParameter parameter1 = new SearchParameter();
        parameter1.addParameter(new Criterion("picture",SignEnum.eq,"推广海报"));
        List<SystemImgs> systemImgs1 = systemImgsService.search(parameter1);
        data.put("promotionalPoster",systemImgs1);
        return Json.success(data);
    }
    //背景图合成二维码并上传到fastDfs,返回前端图片地址
    
    @RequestMapping(value = "/imgurl", method = RequestMethod.POST)
    public Json synthesis(HttpServletRequest request, @RequestBody SystemImgs imgs){
        String phone=redisString.get(request.getHeader("Authorization")) ;
        Users user= usersService.phoneSelect(phone);

        try {
            Map data=new HashMap();
            SystemImgs systemImgs=systemImgsService.selectByPrimaryKey(imgs.getId());
            String background = systemImgs.getImgUrl(); //远程图片地址
            String url = "http://114.67.72.214/sjzew/register.html?uuid="+user.getUuId();
            String imgPath= QRCodeMax.synthesis(background,url,systemImgs.getX(),systemImgs.getY()); //合成二维码与图片
            StorageClient1 sc1= fastDFSUtil.getStorageClient(); //链接服务器
            String id1=sc1.upload_file1(imgPath,"png",null); //上传合成的图片地址+图片格式
            StringBuffer imgurl=new StringBuffer("http://114.67.72.214:81/");
            imgurl.append(id1);
            data.put("imgurl",imgurl);
            UserImgs userImgs=new UserImgs();
            userImgs.setImgName(id1.substring(id1.lastIndexOf("/")+1));
            userImgs.setImgUrl(imgurl.toString());
            userImgs.setPicture(systemImgs.getPicture());
            boolean flag=false;
            UserImgs imgs1=userimgsService.phoneSelect(phone);
            if(imgs1==null){
                userImgs.setPhone(phone);
                userimgsService.insert(userImgs);
                flag=true;
            }else {
                userImgs.setId(imgs1.getId());
                userimgsService.updateByPrimaryKey(userImgs);
                flag=true;
            }

            if (flag) {
                return Json.success(data);
            }else{
                return  Json.failed(501,"数据异常请重新操作!");
            }


        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return Json.failed(502,"系统异常请联系管理员!");
    }

}

这个贴出上传代码(这里用的test)

package com.sjzew.allySystem;

import com.sjzew.allySystem.entity.SystemImgs;
import com.sjzew.allySystem.superPack.SuperController;
import org.csource.common.MyException;
import org.csource.fastdfs.StorageClient1;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDFSTest extends SuperController {

    @Test
    public void test01() {
		//下载代码块
        StorageClient1 sc1 = fastDFSUtil.getStorageClient(); //链接服务器
        try {
            String id1 = sc1.upload_file1("E://x128y404.png", "png", null); //上传合成的图片地址+图片格式
            SystemImgs systemImgs = new SystemImgs();
            String url = "http://114.67.72.214:81/"+id1;
            String imgName = id1.substring(id1.lastIndexOf("/")+1);
            systemImgs.setImgName(imgName);
            systemImgs.setImgUrl(url);
            systemImgsService.insert(systemImgs);
            System.out.println(id1);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值