若有侵權,請聯繫博主刪除!!!(記錄所需)
參考:https://blog.csdn.net/qq_30336433/article/details/83752092#commentBox
矩形圖片
生成一個如下圖的簽章圖片:
不多說上代碼:
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import sun.font.FontDesignMetrics;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class PdfImage {
/**
* @param doctorName
* String 印
* @param hospitalName
* String 姓
* @param date
* String 名
* 圖片高度
* @param jpgname
* String 圖片名(生成的路徑)
* @return
*/
public static boolean createSignTextImg(
String doctorName, //
String surname , //
String name,
String jpgname) {
int width = 130;//圖片的寬度
int height = 130;//圖片的高度
FileOutputStream out = null;
//背景色
Color bgcolor = Color.WHITE;
//字色
Color fontcolor = Color.RED;
Font doctorNameFont = new Font("仿宋", Font.PLAIN, 25);
Font othorTextFont = new Font("仿宋", Font.PLAIN, 53);
Font doctorNameFonts = new Font("仿宋", Font.PLAIN, 83);
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, 3, height);
g.fillRect(0, 0, width, 3);
g.fillRect(0, height - 3, width, height);
g.fillRect(width - 3, 0, width, height);
g.setColor(fontcolor); // 字的顏色
g.setFont(doctorNameFonts); // 字體字形字號
FontMetrics fm = FontDesignMetrics.getMetrics(doctorNameFont);
int font1_Hight = fm.getHeight();
int strWidth = fm.stringWidth(doctorName);
int y = 100;//圖片上邊距
int x = 0;//圖片左邊距
g.drawString(doctorName, x, y); // 在指定座標處 添加文字
g.setFont(othorTextFont); // 字體大小
FontMetrics fms = FontDesignMetrics.getMetrics(doctorNameFont);
int font2_Hight = fms.getHeight();
strWidth = fms.stringWidth(surname );
int c =22;//圖片上邊距
x = 75;//圖片左邊距
g.drawString(surname, x, c + font1_Hight); // 在指定座標處添加文字
g.setFont(othorTextFont); // 字體大小
FontMetrics fmss = FontDesignMetrics.getMetrics(doctorNameFont);
int font2_Hights = fmss.getHeight();
strWidth = fmss.stringWidth(name );
int d =80;//圖片上邊距
x = 75;//圖片左邊距
g.drawString(name, x, d + font2_Hights); // 在指定座標處添加文字
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) {
return false;
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
}
}
}
}
public static void main(String[] args) {
System.out.println(createSignTextImg("印","呵", "呵","C:/pdf/sign.jpg"));
}