失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > JAVA生成数字印章图片

JAVA生成数字印章图片

时间:2024-04-09 21:28:47

相关推荐

JAVA生成数字印章图片

废话少说直接上代码,看不懂复制本地跑一下就完事了。

package cn.xxx.xxx.utils;import mons.codec.binary.Base64;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;public class GraphicsUtil {public static void main(String[] args) {GraphicsUtil.sealToFile("1000",new File("D:\\Config\\1000.png"));GraphicsUtil.sealToFile("1111",new File("D:\\Config\\1111.png"));String s = GraphicsUtil.sealToBase64("56");System.out.println(s);}/*** 生成数字印章到文件* @param text* @return*/public static String sealToBase64(String text){BufferedImage bi = seal(text);try {ByteArrayOutputStream outStream = new ByteArrayOutputStream();//bufferedImage转为byte数组ImageIO.write(bi, "png", outStream);byte[] bytes = outStream.toByteArray();return Base64.encodeBase64String(bytes);} catch (IOException e) {e.printStackTrace();}return "";}/*** 生成数字印章到文件* @param text* @param file* @return*/public static File sealToFile(String text,File file){BufferedImage bi = seal(text);try {ImageIO.write(bi, "png", file);} catch (IOException e) {e.printStackTrace();}return file;}/**** 生成数字印章* @param text* @return*/public static BufferedImage seal(String text){int width = 95;int height = 44;double rate = 1.5;//文字间距,重要if (text.length() > 2){rate = 1;}//1.创建对象并绘制背景BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);//创建画笔Graphics2D g2d = bi.createGraphics();//背景颜色g2d.setColor(Color.WHITE);//背景g2d.fill3DRect(0, 0, width, height, true);//2.绘制边框int stroke = 4;g2d.setPaint(Color.RED);//设置画笔的粗度g2d.setStroke(new BasicStroke(stroke));g2d.drawRect(stroke/2, stroke/2, width-stroke, height-stroke);//3.绘制文件内容//文字颜色g2d.setColor(Color.RED);//设置字体g2d.setFont(new Font("宋体",Font.BOLD,40));//居中显示int x = (int)(width / 2 - rate * g2d.getFontMetrics().stringWidth(text) / 2);int y = height / 2 + g2d.getFontMetrics().getHeight() / 3;//4.重新设置文字间距rate(text, x, y, rate, g2d);g2d.dispose();return bi;}/**** 设置文字间距* @param str* @param x* @param y* @param rate* @param g*/private static void rate(String str,int x,int y,double rate,Graphics g){String tempStr = null;int orgStringWight = g.getFontMetrics().stringWidth(str);int orgStringLength = str.length();int tempx = x;int tempy = y;while(str.length()>0){tempStr = str.substring(0, 1);str = str.substring(1, str.length());g.drawString(tempStr, tempx, tempy);tempx = (int)(tempx + (double)orgStringWight / (double)orgStringLength * rate);}}}

如果觉得《JAVA生成数字印章图片》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。