今天在做熱敏打印機打印二維碼,並有文字描述,想到的簡單的方法就是根據熱敏打印機的紙張寬度和高度,生成對應的圖片,如下:
package com.orisdom.utils;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author chenxiaokang
* @date 2019/7/8 13:48
*/
@Slf4j
public class ImageBuilderUtils {
/**
* 熱敏打印機紙張大約寬度(4cm*6cm)
*/
private static final int width = 151;
/**
* 熱敏打印機紙張大約高度(4cm*6cm)
*/
private static final int height = 227;
/**
*
* @param code 編碼
* @param path 二維碼存放路勁
* @return 最新圖片生成路徑
*/
public static String ImageBuilder(String code,String path) {
//得到圖片緩沖區
FileInputStream fileInputStream = null;
try {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
File file = new File(path);
if(!file.exists()){
throw new BusinessException("二維碼存放地址有誤");
}
fileInputStream = new FileInputStream(file);
BufferedImage image2 = ImageIO.read(fileInputStream);
//得到它的繪制環境(這張圖片的筆)
Graphics2D g2 = (Graphics2D) bi.getGraphics();
g2.fillRect(0, 0, width, height);
//設置顏色
g2.setColor(Color.WHITE);
// 將圖片大小設置為大約4cm*4cm 具體根據紙張大小設定
g2.drawImage(image2, 10, 85, 135, 135,null);
g2.drawRect(0, 0, width - 1, height - 1);
//設置字體:字體、字號、大小
g2.setFont(new Font("黑體", Font.BOLD, 26));
//設置背景顏色
g2.setColor(Color.BLACK);
//向圖片上寫字符串
g2.drawString("東久", 15, 30);
g2.setFont(new Font("黑體", Font.BOLD, 20));
g2.drawString("·", 65, 28);
g2.setFont(new Font("黑體", Font.BOLD, 26));
g2.drawString("佳能", 83, 30);
g2.setFont(new Font("黑體", Font.BOLD, 18));
g2.drawString("iR-ADV C3525", 15, 60);
g2.setFont(new Font("黑體", Font.ITALIC, 14));
g2.drawString(code, 30, 80);
// 圖片上傳后的路徑
String savePath = "D:/a.jpg";
ImageIO.write(bi, "JPEG", new FileOutputStream(savePath));
return savePath;
}catch (Exception e){
log.error("生成圖片錯誤",e);
throw new BusinessException("生成圖片錯誤",e);
}finally {
if(fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
編寫測試類
package com.orisdom.utils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author chenxiaokang
* @date 2019/7/8 15:39
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class ImageBuilderUtilsTest {
@Test
public void imageBuilder() {
String path = ImageBuilderUtils.ImageBuilder("NO.1132323232","D:\\toolschenxiaokang\\qrcode_for_gh_02122d6b2ea8_258.jpg");
System.out.println(path);
}
}
最后生成的圖片模板