创建一个简单的签章
package com.hxc;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import sun.font.FontDesignMetrics;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
public class SignImage {
/**
* 创建一个签章
* @param docotorName 医生名字
* @param hospittalName 医生名称
* @param date 签名日期
* @param jpgName 图片名
* @return
*/
public static boolean createSignTextImg(String docotorName,String hospittalName,String date,String jpgName){
int width = 255;
int height = 100;
FileOutputStream out = null;
//背景色
Color bgcolor = Color.WHITE;
//字色
Color fontcolor = Color.RED;
Font docotorNameFont = new Font(null, com.itextpdf.text.Font.BOLD, 20);
Font otherTextFont = new Font(null, Font.BOLD, 18);
try {//宽度、高度
BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bimage.createGraphics();
g.setColor(bgcolor); //背景色
g.fillRect(0,0,width,height); //画一个矩形
//去除锯齿
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.RED);
g.fillRect(0, 0, 8, height);
g.fillRect(0, 0, width, 8);
g.fillRect(0, height - 8, width, height);
g.fillRect(width - 8, 0, width, height);
g.setColor(fontcolor); //字的颜色
g.setFont(docotorNameFont); //字体字形字号
FontMetrics fm = FontDesignMetrics.getMetrics(docotorNameFont);
int font1_Hight = fm.getHeight();
int strWidth = fm.stringWidth(docotorName);
int y = 35;
int x = (width-strWidth)/2;
g.drawString(docotorName, x, y); // 在指定坐标除添加文字
g.setFont(otherTextFont); // 字体字形字号
fm = FontDesignMetrics.getMetrics(otherTextFont);
int font2_Hight = fm.getHeight();
strWidth = fm.stringWidth(hospittalName);
x = (width - strWidth) / 2;
g.drawString(hospittalName, x, y + font1_Hight); // 在指定坐标除添加文字
strWidth = fm.stringWidth(date);
x = (width - strWidth) / 2;
g.drawString(date, x, y + font1_Hight + font2_Hight); // 在指定坐标除添加文字
g.dispose();
out = new FileOutputStream(jpgName); // 指定输出文件
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(50f, true);
encoder.encode(bimage, param); // 存盘
out.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}finally {
if (out!=null){
try {
out.close();
}catch (IOException e){
}
}
}
}
public static void main(String[] args) {
createSignTextImg("华佗","在线医院","2020.12.12","sing.jpg");
}
}