这个忘记是在那篇博客上看到的没有测试过先记录一下,如果作者看到的话麻烦和我说下我去转载
java 生成印章 图章
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.10</version></dependency>工具类:import lombok.Builder;import lombok.Getter;import javax.imageio.ImageIO;import java.awt.*;import java.awt.font.FontRenderContext;import java.awt.geom.AffineTransform;import java.awt.geom.Rectangle2D;import java.awt.image.BufferedImage;import java.io.File;@Builder@Getterpublic class Seal {// 起始位置private static final int INIT_BEGIN = 5;// 尺寸private Integer size;// 颜色private Color color;// 主字private SealFont mainFont;// 副字private SealFont viceFont;// 抬头private SealFont titleFont;// 中心字private SealFont centerFont;// 边线圆private SealCircle borderCircle;// 内边线圆private SealCircle borderInnerCircle;// 内线圆private SealCircle innerCircle;// 边线框private Integer borderSquare;// 加字private String stamp;/*** 画公章*/public boolean draw(String pngPath) throws Exception {if (borderSquare != null) {return draw2(pngPath); // 画私章}//1.画布BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_4BYTE_ABGR);//2.画笔Graphics2D g2d = bi.createGraphics();//2.1抗锯齿设置//文本不抗锯齿,否则圆中心的文字会被拉长RenderingHints hints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);//其他图形抗锯齿hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);g2d.setRenderingHints(hints);//2.2设置背景透明度g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0));//2.3填充矩形g2d.fillRect(0, 0, size, size);//2.4重设透明度,开始画图g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1));//2.5设置画笔颜色g2d.setPaint(color == null ? Color.RED : color);//3.画边线圆if (borderCircle != null) {drawCircle(g2d, borderCircle, INIT_BEGIN, INIT_BEGIN);} else {throw new Exception("BorderCircle can not null!");}int borderCircleWidth = borderCircle.getWidth();int borderCircleHeight = borderCircle.getHeight();//4.画内边线圆if (borderInnerCircle != null) {int x = INIT_BEGIN + borderCircleWidth - borderInnerCircle.getWidth();int y = INIT_BEGIN + borderCircleHeight - borderInnerCircle.getHeight();drawCircle(g2d, borderInnerCircle, x, y);}//5.画内环线圆if (innerCircle != null) {int x = INIT_BEGIN + borderCircleWidth - innerCircle.getWidth();int y = INIT_BEGIN + borderCircleHeight - innerCircle.getHeight();drawCircle(g2d, innerCircle, x, y);}//6.画弧形主文字if (borderCircleHeight != borderCircleWidth) {drawArcFont4Oval(g2d, borderCircle, mainFont, true);} else {drawArcFont4Circle(g2d, borderCircleHeight, mainFont, true);}//7.画弧形副文字if (borderCircleHeight != borderCircleWidth) {drawArcFont4Oval(g2d, borderCircle, viceFont, false);} else {drawArcFont4Circle(g2d, borderCircleHeight, viceFont, false);}//8.画中心字drawFont(g2d, (borderCircleWidth + INIT_BEGIN) * 2, (borderCircleHeight + INIT_BEGIN) * 2, centerFont);//9.画抬头文字drawFont(g2d, (borderCircleWidth + INIT_BEGIN) * 2, (borderCircleHeight + INIT_BEGIN) * 2, titleFont);g2d.dispose();return ImageIO.write(bi, "PNG", new File(pngPath));}/*** 绘制圆弧形文字*/private static void drawArcFont4Circle(Graphics2D g2d, int circleRadius, SealFont font, boolean isTop) {if (font == null) {return;}//1.字体长度int textLen = font.getText().length();//2.字体大小,默认根据字体长度动态设定int size = font.getSize() == null ? (55 - textLen * 2) : font.getSize();//3.字体样式int style = font.getBold() ? Font.BOLD : Font.PLAIN;//4.构造字体Font f = new Font(font.getFamily(), style, size);FontRenderContext context = g2d.getFontRenderContext();Rectangle2D rectangle = f.getStringBounds(font.getText(), context);//5.文字之间间距,默认动态调整double space;if (font.getSpace() != null) {space = font.getSpace();} else {if (textLen == 1) {space = 0;} else {space = rectangle.getWidth() / (textLen - 1) * 0.9;}}//6.距离外圈距离int margin = font.getMargin() == null ? INIT_BEGIN : font.getMargin();//7.写字double newRadius = circleRadius + rectangle.getY() - margin;double radianPerInterval = 2 * Math.asin(space / (2 * newRadius));double fix = 0.04;if (isTop) {fix = 0.18;}double firstAngle;if (!isTop) {if (textLen % 2 == 1) {firstAngle = Math.PI + Math.PI / 2 - (textLen - 1) * radianPerInterval / 2.0 - fix;} else {firstAngle = Math.PI + Math.PI / 2 - ((textLen / 2.0 - 0.5) * radianPerInterval) - fix;}} else {if (textLen % 2 == 1) {firstAngle = (textLen - 1) * radianPerInterval / 2.0 + Math.PI / 2 + fix;} else {firstAngle = (textLen / 2.0 - 0.5) * radianPerInterval + Math.PI / 2 + fix;}}for (int i = 0; i < textLen; i++) {double theta;double thetaX;double thetaY;if (!isTop) {theta = firstAngle + i * radianPerInterval;thetaX = newRadius * Math.sin(Math.PI / 2 - theta);thetaY = newRadius * Math.cos(theta - Math.PI / 2);} else {theta = firstAngle - i * radianPerInterval;thetaX = newRadius * Math.sin(Math.PI / 2 - theta);thetaY = newRadius * Math.cos(theta - Math.PI / 2);}AffineTransform transform;if (!isTop) {transform = AffineTransform.getRotateInstance(Math.PI + Math.PI / 2 - theta);} else {transform = AffineTransform.getRotateInstance(Math.PI / 2 - theta + Math.toRadians(8));}Font f2 = f.deriveFont(transform);g2d.setFont(f2);g2d.drawString(font.getText().substring(i, i + 1), (float) (circleRadius + thetaX + INIT_BEGIN), (float) (circleRadius - thetaY + INIT_BEGIN));}}/*** 绘制椭圆弧形文字*/private static void drawArcFont4Oval(Graphics2D g2d, SealCircle sealCircle, SealFont font, boolean isTop) {if (font == null) {return;}float radiusX = sealCircle.getWidth();float radiusY = sealCircle.getHeight();float radiusWidth = radiusX + sealCircle.getLine();float radiusHeight = radiusY + sealCircle.getLine();//1.字体长度int textLen = font.getText().length();//2.字体大小,默认根据字体长度动态设定int size = font.getSize() == null ? 25 + (10 - textLen) / 2 : font.getSize();//3.字体样式int style = font.getBold() ? Font.BOLD : Font.PLAIN;//4.构造字体Font f = new Font(font.getFamily(), style, size);//5.总的角跨度double totalArcAng = font.getSpace() * textLen;//6.从边线向中心的移动因子float minRat = 0.90f;double startAngle = isTop ? -90f - totalArcAng / 2f : 90f - totalArcAng / 2f;double step = 0.5;int alCount = (int) Math.ceil(totalArcAng / step) + 1;double[] angleArr = new double[alCount];double[] arcLenArr = new double[alCount];int num = 0;double accArcLen = 0.0;angleArr[num] = startAngle;arcLenArr[num] = accArcLen;num++;double angR = startAngle * Math.PI / 180.0;double lastX = radiusX * Math.cos(angR) + radiusWidth;double lastY = radiusY * Math.sin(angR) + radiusHeight;for (double i = startAngle + step; num < alCount; i += step) {angR = i * Math.PI / 180.0;double x = radiusX * Math.cos(angR) + radiusWidth, y = radiusY * Math.sin(angR) + radiusHeight;accArcLen += Math.sqrt((lastX - x) * (lastX - x) + (lastY - y) * (lastY - y));angleArr[num] = i;arcLenArr[num] = accArcLen;lastX = x;lastY = y;num++;}double arcPer = accArcLen / textLen;for (int i = 0; i < textLen; i++) {double arcL = i * arcPer + arcPer / 2.0;double ang = 0.0;for (int p = 0; p < arcLenArr.length - 1; p++) {if (arcLenArr[p] <= arcL && arcL <= arcLenArr[p + 1]) {ang = (arcL >= ((arcLenArr[p] + arcLenArr[p + 1]) / 2.0)) ? angleArr[p + 1] : angleArr[p];break;}}angR = (ang * Math.PI / 180f);Float x = radiusX * (float) Math.cos(angR) + radiusWidth;Float y = radiusY * (float) Math.sin(angR) + radiusHeight;double qxang = Math.atan2(radiusY * Math.cos(angR), -radiusX * Math.sin(angR));double fxang = qxang + Math.PI / 2.0;int subIndex = isTop ? i : textLen - 1 - i;String c = font.getText().substring(subIndex, subIndex + 1);//获取文字高宽FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(f);int w = fm.stringWidth(c), h = fm.getHeight();if (isTop) {x += h * minRat * (float) Math.cos(fxang);y += h * minRat * (float) Math.sin(fxang);x += -w / 2f * (float) Math.cos(qxang);y += -w / 2f * (float) Math.sin(qxang);} else {x += (h * minRat) * (float) Math.cos(fxang);y += (h * minRat) * (float) Math.sin(fxang);x += w / 2f * (float) Math.cos(qxang);y += w / 2f * (float) Math.sin(qxang);}// 旋转AffineTransform affineTransform = new AffineTransform();affineTransform.scale(0.8, 1);if (isTop)affineTransform.rotate(Math.toRadians((fxang * 180.0 / Math.PI - 90)), 0, 0);elseaffineTransform.rotate(Math.toRadians((fxang * 180.0 / Math.PI + 180 - 90)), 0, 0);Font f2 = f.deriveFont(affineTransform);g2d.setFont(f2);g2d.drawString(c, x.intValue() + INIT_BEGIN, y.intValue() + INIT_BEGIN);}}/*** 画文字*/private static void drawFont(Graphics2D g2d, int circleWidth, int circleHeight, SealFont font) {if (font == null) {return;}//1.字体长度int textLen = font.getText().length();//2.字体大小,默认根据字体长度动态设定int size = font.getSize() == null ? (55 - textLen * 2) : font.getSize();//3.字体样式int style = font.getBold() ? Font.BOLD : Font.PLAIN;//4.构造字体Font f = new Font(font.getFamily(), style, size);g2d.setFont(f);FontRenderContext context = g2d.getFontRenderContext();String[] fontTexts = font.getText().split("\n");if (fontTexts.length > 1) {int y = 0;for (String fontText : fontTexts) {y += Math.abs(f.getStringBounds(fontText, context).getHeight());}//5.设置上边距float margin = INIT_BEGIN + (float) (circleHeight / 2 - y / 2);for (String fontText : fontTexts) {Rectangle2D rectangle2D = f.getStringBounds(fontText, context);g2d.drawString(fontText, (float) (circleWidth / 2 - rectangle2D.getCenterX()), margin);margin += Math.abs(rectangle2D.getHeight());}} else {Rectangle2D rectangle2D = f.getStringBounds(font.getText(), context);//5.设置上边距,默认在中心float margin = font.getMargin() == null ?(float) (circleHeight / 2 - rectangle2D.getCenterY()) :(float) (circleHeight / 2 - rectangle2D.getCenterY()) + (float) font.getMargin();g2d.drawString(font.getText(), (float) (circleWidth / 2 - rectangle2D.getCenterX()), margin);}}/*** 画圆*/private static void drawCircle(Graphics2D g2d, SealCircle circle, int x, int y) {if (circle == null) {return;}//1.圆线条粗细默认是圆直径的1/35int lineSize = circle.getLine() == null ? circle.getHeight() * 2 / (35) : circle.getLine();//2.画圆g2d.setStroke(new BasicStroke(lineSize));g2d.drawOval(x, y, circle.getWidth() * 2, circle.getHeight() * 2);}/*** 画私章*/public boolean draw2(String pngPath) throws Exception {if (mainFont == null || mainFont.getText().length() < 2 || mainFont.getText().length() > 4) {throw new IllegalArgumentException("请输入2-4个字");}int fixH = 18;int fixW = 2;//1.画布BufferedImage bi = new BufferedImage(size, size / 2, BufferedImage.TYPE_4BYTE_ABGR);//2.画笔Graphics2D g2d = bi.createGraphics();//2.1设置画笔颜色g2d.setPaint(Color.RED);//2.2抗锯齿设置g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//3.写签名int marginW = fixW + borderSquare;float marginH;FontRenderContext context = g2d.getFontRenderContext();Rectangle2D rectangle;Font f;if (mainFont.getText().length() == 2) {if (stamp != null && stamp.trim().length() > 0) {bi = drawThreeFont(bi, g2d, mainFont.append(stamp), borderSquare, size, fixH, fixW, true);} else {f = new Font(mainFont.getFamily(), Font.BOLD, mainFont.getSize());g2d.setFont(f);rectangle = f.getStringBounds(mainFont.getText().substring(0, 1), context);marginH = (float) (Math.abs(rectangle.getCenterY()) * 2 + marginW) + fixH - 4;g2d.drawString(mainFont.getText().substring(0, 1), marginW, marginH);marginW += Math.abs(rectangle.getCenterX()) * 2 + (mainFont.getSpace() == null ? INIT_BEGIN : mainFont.getSpace());g2d.drawString(mainFont.getText().substring(1), marginW, marginH);//拉伸BufferedImage nbi = new BufferedImage(size, size, bi.getType());Graphics2D ng2d = nbi.createGraphics();ng2d.setPaint(Color.RED);ng2d.drawImage(bi, 0, 0, size, size, null);//画正方形ng2d.setStroke(new BasicStroke(borderSquare));ng2d.drawRect(0, 0, size, size);ng2d.dispose();bi = nbi;}} else if (mainFont.getText().length() == 3) {if (stamp != null && stamp.trim().length() > 0) {bi = drawFourFont(bi, mainFont.append(stamp), borderSquare, size, fixH, fixW);} else {bi = drawThreeFont(bi, g2d, mainFont, borderSquare, size, fixH, fixW, false);}} else {bi = drawFourFont(bi, mainFont, borderSquare, size, fixH, fixW);}g2d.dispose();return ImageIO.write(bi, "PNG", new File(pngPath));}/*** 画三字*/private static BufferedImage drawThreeFont(BufferedImage bi, Graphics2D g2d, SealFont font, int lineSize, int imageSize, int fixH, int fixW, boolean isWithYin) {fixH -= 9;int marginW = fixW + lineSize;//设置字体Font f = new Font(font.getFamily(), Font.BOLD, font.getSize());g2d.setFont(f);FontRenderContext context = g2d.getFontRenderContext();Rectangle2D rectangle = f.getStringBounds(font.getText().substring(0, 1), context);float marginH = (float) (Math.abs(rectangle.getCenterY()) * 2 + marginW) + fixH;int oldW = marginW;if (isWithYin) {g2d.drawString(font.getText().substring(2, 3), marginW, marginH);marginW += rectangle.getCenterX() * 2 + (font.getSpace() == null ? INIT_BEGIN : font.getSpace());} else {marginW += rectangle.getCenterX() * 2 + (font.getSpace() == null ? INIT_BEGIN : font.getSpace());g2d.drawString(font.getText().substring(0, 1), marginW, marginH);}//拉伸BufferedImage nbi = new BufferedImage(imageSize, imageSize, bi.getType());Graphics2D ng2d = nbi.createGraphics();ng2d.setPaint(Color.RED);ng2d.drawImage(bi, 0, 0, imageSize, imageSize, null);//画正方形ng2d.setStroke(new BasicStroke(lineSize));ng2d.drawRect(0, 0, imageSize, imageSize);ng2d.dispose();bi = nbi;g2d = bi.createGraphics();g2d.setPaint(Color.RED);g2d.setFont(f);g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);if (isWithYin) {g2d.drawString(font.getText().substring(0, 1), marginW, marginH += fixH);rectangle = f.getStringBounds(font.getText(), context);marginH += Math.abs(rectangle.getHeight());g2d.drawString(font.getText().substring(1), marginW, marginH);} else {g2d.drawString(font.getText().substring(1, 2), oldW, marginH += fixH);rectangle = f.getStringBounds(font.getText(), context);marginH += Math.abs(rectangle.getHeight());g2d.drawString(font.getText().substring(2, 3), oldW, marginH);}return bi;}/*** 画四字*/private static BufferedImage drawFourFont(BufferedImage bi, SealFont font, int lineSize, int imageSize, int fixH, int fixW) {int marginW = fixW + lineSize;//拉伸BufferedImage nbi = new BufferedImage(imageSize, imageSize, bi.getType());Graphics2D ng2d = nbi.createGraphics();ng2d.setPaint(Color.RED);ng2d.drawImage(bi, 0, 0, imageSize, imageSize, null);//画正方形ng2d.setStroke(new BasicStroke(lineSize));ng2d.drawRect(0, 0, imageSize, imageSize);ng2d.dispose();bi = nbi;Graphics2D g2d = bi.createGraphics();g2d.setPaint(Color.RED);g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);FontRenderContext context = g2d.getFontRenderContext();Font f = new Font(font.getFamily(), Font.BOLD, font.getSize());g2d.setFont(f);Rectangle2D rectangle = f.getStringBounds(font.getText().substring(0, 1), context);float marginH = (float) (Math.abs(rectangle.getCenterY()) * 2 + marginW) + fixH;g2d.drawString(font.getText().substring(2, 3), marginW, marginH);int oldW = marginW;marginW += Math.abs(rectangle.getCenterX()) * 2 + (font.getSpace() == null ? INIT_BEGIN : font.getSpace());g2d.drawString(font.getText().substring(0, 1), marginW, marginH);marginH += Math.abs(rectangle.getHeight());g2d.drawString(font.getText().substring(3, 4), oldW, marginH);g2d.drawString(font.getText().substring(1, 2), marginW, marginH);return bi;}}import lombok.Builder;import lombok.Getter;@Getter@Builderpublic class SealCircle {private Integer line;private Integer width;private Integer height;}import lombok.Builder;import lombok.Getter;@Getter@Builderpublic class SealFont {private String text;private String family;private Integer size;private Boolean bold;private Double space;private Integer margin;public String getFamily() {return family == null ? "宋体" : family;}public boolean getBold() {return bold == null ? true : bold;}public SealFont append(String text) {this.text += text;return this;}}/*** <b>* </b><br><br><i>Description</i> :* <br><br>Date: /12/26 ${time} <br>Author : dxl*/public class SealSample {public static void main(String[] args) throws Exception {PrivateSeal_1();}public static void OfficialSeal_1() throws Exception {Seal.builder().size(200).borderCircle(SealCircle.builder().line(4).width(95).height(95).build()).mainFont(SealFont.builder().text("中国四大天王股份有限公司").family("隶书").size(22).space(22.0).margin(4).build()).centerFont(SealFont.builder().text("★").size(60).build()).titleFont(SealFont.builder().text("电子签章").size(16).space(8.0).margin(54).build()).build().draw("D:/test/seal/公章2.png");}public static void OfficialSeal_2() throws Exception {Seal.builder().size(300).borderCircle(SealCircle.builder().line(5).width(140).height(140).build()).mainFont(SealFont.builder().text("中国四大天王股份有限公司").size(35).space(35.0).margin(10).build()).centerFont(SealFont.builder().text("★").size(100).build()).titleFont(SealFont.builder().text("电子签章").size(22).space(10.0).margin(68).build()).build().draw("D:/test/seal/公章2.png");}public static void OfficialSeal_3() throws Exception {Seal.builder().size(300).borderCircle(SealCircle.builder().line(3).width(144).height(100).build()).borderInnerCircle(SealCircle.builder().line(1).width(140).height(96).build()).mainFont(SealFont.builder().text("中国四大天王股份有限公司").size(25).space(12.0).margin(10).build()).centerFont(SealFont.builder().text("NO.514").size(20).build()).titleFont(SealFont.builder().text("电子合同专用章").size(20).space(9.0).margin(64).build()).build().draw("D:/test/seal/公章3.png");}public static void PrivateSeal_1() throws Exception {Seal.builder().size(300).borderSquare(16).mainFont(SealFont.builder().text("刘德").size(120).build()).build().draw("D:/test/seal/私章1.png");}public static void PrivateSeal_2() throws Exception {Seal.builder().size(300).borderSquare(16).mainFont(SealFont.builder().text("刘德华印").size(120).build()).build().draw("D:/test/seal/私章2.png");}}提示:要生成长方形印章,可以参考下,主要在Seal中的方法里。
DrawSeal
package com.hy.util;import java.awt.BasicStroke;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Polygon;import java.awt.font.FontRenderContext;import java.awt.geom.AffineTransform;import java.awt.geom.Rectangle2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Calendar;import java.util.UUID;import javax.imageio.ImageIO;import mons.lang.StringUtils;/*** 勾画圆形公司章** @author ldd*/public class DrawSeal {//生成文件路径public static final String FILE_PATH = "d:/";private final static int WIDTH = 160;private final static int HEIGHT = 110;/*** 画圆形章* @param name1 章的名字* @param name2 公司的名字* @param numCode 公司的数字编码* @return*/public static String drawCircularChapter(String name1, String name2, String numCode){OutputStream out = null;InputStream in = null;//创建缓存BufferedImage bufImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);//获得画布Graphics2D gs = bufImg.createGraphics();//设置颜色gs.setColor(Color.WHITE);//填充区域gs.fillRect(0, 0, WIDTH, HEIGHT);//设置画笔颜色gs.setColor(new Color(204,41,41));//画五角星drawFiveStar(gs, WIDTH/2, (HEIGHT-10)/2, (HEIGHT-10)/6-3);//设置画笔宽度gs.setStroke(new BasicStroke(3));//画圆形边框gs.drawOval(2, 2, WIDTH-4, HEIGHT-10);//设置字体gs.setFont(new Font("宋体", Font.BOLD, 21));// 画数据(合同专用章)drawCenterMessage(gs, name1, WIDTH/2+2, (HEIGHT-10) * 4 / 5);if (StringUtils.isNotEmpty(name2) && name2.length()>11) {int len = name2.length();int fontSize = 18;switch (len) {case 12:fontSize = 20;break;case 13:fontSize = 19;break;case 14:fontSize = 19;break;case 15:fontSize = 18;break;case 16:fontSize = 17;break;case 17:fontSize = 16;break;case 18:fontSize = 15;break;case 19:fontSize = 14;break;case 20:fontSize = 14;break;case 21:fontSize = 12;break;case 22:fontSize = 12;break;case 23:fontSize = 10;break;case 24:fontSize = 10;break;case 25:fontSize = 9;break;default :fontSize = 18;break;}//设置字体gs.setFont(new Font("宋体", Font.PLAIN, fontSize));}//画上方的环形字drawUpperMessage(gs, name2, WIDTH/2, (HEIGHT-10)/2, WIDTH/2-8, (HEIGHT-10)/2-8);//设置字体gs.setFont(new Font("宋体", Font.BOLD, 9));//画下方的环形数字drawBelowNumber(gs, numCode, WIDTH/2, (HEIGHT-10)/2, WIDTH/2-8, (HEIGHT-10)/2+8);//释放此图形的上下文以及它使用的所有系统资源gs.dispose();//输出图片try {StringBuffer fileDir = new StringBuffer();fileDir.append(Calendar.getInstance().get(Calendar.YEAR)).append(File.separator).append(Calendar.getInstance().get(Calendar.MONTH)+1).append(File.separator).append(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).append(File.separator);File ff = new File(FILE_PATH + fileDir.toString());if (!ff.exists()) {ff.mkdirs();}String imgFile = FILE_PATH + fileDir.toString() + UUID.randomUUID() + ".png";out = new FileOutputStream(imgFile);ImageIO.write(bufImg, "png", out);bufImg.flush();out.flush();/*in = new FileInputStream(imgFile);data = new byte[in.available()];in.read(data);*///对字节数组Base64编码/*sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();//返回Base64编码过的字节数组字符串String encodeStr = encoder.encode(data);//将图片文件删除File file = new File(imgFile);if (file.isFile()) {file.delete();}*/return imgFile;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (null != out) {try {out.close();} catch (IOException e) {e.printStackTrace();}}if (null != in) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}return null;}public static void drawCenterMessage(Graphics2D gs, String message, int CENTERX, int CENTERY){if (message != null) {// 根据输入字符串得到字符数组String[] messages2 = message.split("", 0);String[] messages = new String[messages2.length];System.arraycopy(messages2, 0, messages, 0, messages2.length);// 输入的字数int ilength = messages.length;Font f = gs.getFont();FontRenderContext context = gs.getFontRenderContext();Rectangle2D bounds = f.getStringBounds(message, context);// 字符宽度=字符串长度/字符数double char_interval = (bounds.getWidth() / ilength) - 1;int first = 0, second = 0;boolean odd = false;if (ilength % 2 == 1) {first = (ilength - 1) / 2;odd = true;} else {first = (ilength) / 2 - 1;second = (ilength) / 2;odd = false;}if (odd) {gs.drawString(messages[first],(float)(CENTERX - char_interval / 2 - char_interval / 10),(float) CENTERY);// 中心点的右边for (int i = first + 1; i < ilength; i++) {double x = CENTERX + (i - first - 0.6) * char_interval;gs.drawString(messages[i],(float) x,(float) CENTERY);}// 中心点的左边for (int i = first - 1; i > -1; i--) {double x = CENTERX - (first - i + 0.6) * char_interval;gs.drawString(messages[i],(float) x,(float) CENTERY);}} else {// 中心点的右边for (int i = second; i < ilength; i++) {double x = CENTERX + (i - second - 0.1) * char_interval;gs.drawString(messages[i],(float) x,(float) CENTERY);}// 中心点的左边for (int i = first; i > -1; i--) {double x = CENTERX - (first + 1 - i + 0.1) * char_interval;gs.drawString(messages[i],(float) x,(float) CENTERY);}}}}/*** 画上方圆弧的汉字** @param gs* @param message* @param CENTERX* @param CENTERY* @param r*/public static void drawUpperMessage(Graphics2D gs, String message, int CENTERX, int CENTERY, int wr, int hr) {if (message != null) {// 根据输入字符串得到字符数组String[] messages = message.split("", 0);// String[] messages = new String[messages2.length];// System.arraycopy(messages2, 0, messages, 0, messages2.length);// 输入的字数int ilength = messages.length;Font f = gs.getFont();FontRenderContext context = gs.getFontRenderContext();Rectangle2D bounds = f.getStringBounds(message, context);// 字符宽度=字符串长度/字符数double char_interval = (bounds.getWidth() / ilength) - 1;// 上坡度double ascentY = - bounds.getY()-2;double ascentX = - bounds.getX()-2;int first = 0, second = 0;boolean odd = false;if (ilength % 2 == 1) {first = (ilength - 1) / 2;odd = true;} else {first = (ilength) / 2 - 1;second = (ilength) / 2;odd = false;}double r2 = wr - ascentX;double x0 = CENTERX;double y0 = CENTERY - hr + ascentY;// 旋转角度double a = 2 * Math.asin(char_interval / (2 * r2));if (odd) {gs.drawString(messages[first],(float)(x0 - char_interval / 2), (float) y0);// 中心点的右边for (int i = first + 1; i < ilength; i++) {double aa = (i - first) * a;double ax = r2 * Math.sin(aa);double ay = r2 - r2 * Math.cos(aa);AffineTransform transform = AffineTransform.getRotateInstance(aa);Font f2 = f.deriveFont(transform);gs.setFont(f2);gs.drawString(messages[i],(float) (x0 + ax - char_interval / 2 * Math.cos(aa)),(float) (y0 + ay - char_interval / 2 * Math.sin(aa)));}// 中心点的左边for (int i = first - 1; i > -1; i--) {double aa = (first - i) * a;double ax = r2 * Math.sin(aa);double ay = r2 - r2 * Math.cos(aa);AffineTransform transform = AffineTransform.getRotateInstance(-aa);Font f2 = f.deriveFont(transform);gs.setFont(f2);gs.drawString(messages[i],(float) (x0 - ax - char_interval / 2 * Math.cos(aa)),(float) (y0 + ay + char_interval / 2 * Math.sin(aa)));}} else {// 中心点的右边for (int i = second; i < ilength; i++) {double aa = (i - second + 0.3) * a;double ax = r2 * Math.sin(aa);double ay = r2 - r2 * Math.cos(aa);AffineTransform transform = AffineTransform.getRotateInstance(aa);Font f2 = f.deriveFont(transform);gs.setFont(f2);gs.drawString(messages[i],(float) (x0 + ax - char_interval / 2 * Math.cos(aa)),(float) (y0 + ay - char_interval / 2 * Math.sin(aa)));}// 中心点的左边for (int i = first; i > -1; i--) {double aa = (first - i + 0.7) * a;double ax = r2 * Math.sin(aa);double ay = r2 - r2 * Math.cos(aa);AffineTransform transform = AffineTransform.getRotateInstance(-aa);Font f2 = f.deriveFont(transform);gs.setFont(f2);gs.drawString(messages[i],(float) (x0 - ax - char_interval / 2 * Math.cos(aa)),(float) (y0 + ay + char_interval / 2* Math.sin(aa)));}}}}/*** 画下方圆弧数字编码** @param gs* @param message* @param CENTERX* @param CENTERY* @param r*/public static void drawBelowNumber(Graphics2D gs, String message, int CENTERX, int CENTERY, int wr, int hr) {if (message != null) {// 根据输入字符串得到字符数组String[] messages = message.split("", 0);// String[] messages = new String[messages2.length];// System.arraycopy(messages2, 0, messages, 0, messages2.length);// 输入的字数int ilength = messages.length;Font f = gs.getFont();FontRenderContext context = gs.getFontRenderContext();Rectangle2D bounds = f.getStringBounds(message, context);// 字符宽度=字符串长度/字符数double char_interval = (bounds.getWidth() / ilength) + 4;// 上坡度double ascentY = -bounds.getY();double ascentX = -bounds.getY();int first = 0, second = 0;boolean odd = false;if (ilength % 2 == 1) {first = (ilength - 1) / 2;odd = true;} else {first = (ilength) / 2 - 1;second = (ilength) / 2;odd = false;}double r2 = wr - ascentX;double x0 = CENTERX;double y0 = CENTERY - hr + ascentY;// 旋转角度double a = 2 * Math.asin(char_interval / (2 * r2));if (odd) {// 中心点的右边for (int i = first + 1; i < ilength; i++) {double aa = (i - first + 0.5) * a;double ax = r2 * Math.sin(aa);double ay = r2 - r2 * Math.cos(aa);AffineTransform transform = AffineTransform.getRotateInstance(2*Math.PI - aa);Font f2 = f.deriveFont(transform);gs.setFont(f2);gs.drawString(messages[i],(float) (x0 + ax - char_interval / 2 * Math.cos(aa)),2*CENTERY - (float) (y0 + ay - char_interval / 2 * Math.sin(aa)));}// 中心点的左边for (int i = first; i > -1; i--) {double aa = (first - i - 0.5) * a;double ax = r2 * Math.sin(aa);double ay = r2 - r2 * Math.cos(aa);AffineTransform transform = AffineTransform.getRotateInstance(2*Math.PI + aa);Font f2 = f.deriveFont(transform);gs.setFont(f2);gs.drawString(messages[i],(float) (x0 - ax - char_interval / 2 * Math.cos(aa)),2*CENTERY - (float) (y0 + ay + char_interval / 2 * Math.sin(aa)));}} else {// 中心点的右边for (int i = second; i < ilength; i++) {double aa = (i - second + 1) * a;double ax = r2 * Math.sin(aa);double ay = r2 - r2 * Math.cos(aa);AffineTransform transform = AffineTransform.getRotateInstance(2*Math.PI - aa);Font f2 = f.deriveFont(transform);gs.setFont(f2);gs.drawString(messages[i],(float) (x0 + ax - char_interval / 2 * Math.cos(aa)),2*CENTERY - (float) (y0 + ay - char_interval / 2 * Math.sin(aa)));}// 中心点的左边for (int i = first; i > -1; i--) {double aa = (first - i) * a;double ax = r2 * Math.sin(aa);double ay = r2 - r2 * Math.cos(aa);AffineTransform transform = AffineTransform.getRotateInstance(2*Math.PI + aa);Font f2 = f.deriveFont(transform);gs.setFont(f2);gs.drawString(messages[i],(float) (x0 - ax - char_interval / 2 * Math.cos(aa)),2*CENTERY - (float) (y0 + ay + char_interval / 2* Math.sin(aa)));}}}}/*** 画章中间的五角星** @param g* @param x* @param y* @param r*/public static void drawFiveStar(Graphics g, int x, int y, int r) {double ch=72*Math.PI/180;int x1=x,x2=(int)(x-Math.sin(ch)*r),x3=(int)(x+Math.sin(ch)*r),x4=(int)(x-Math.sin(ch/2)*r),x5=(int)(x+Math.sin(ch/2)*r);int y1=y-r,y2=(int)(y-Math.cos(ch)*r),y3=y2,y4=(int)(y+Math.cos(ch/2)*r),y5=y4;int bx=(int)(x+Math.cos(ch)*Math.tan(ch/2)*r);int by=y2;Polygon a=new Polygon();Polygon b=new Polygon();a.addPoint(x2,y2);a.addPoint(x5,y5);a.addPoint(bx,by);b.addPoint(x1,y1);b.addPoint(bx,by);b.addPoint(x3,y3);b.addPoint(x4,y4);g.fillPolygon(a);g.fillPolygon(b);}public static void main(String[] args) {drawCircularChapter(null, "陕西XX有限公司", "A1002");}}
如果觉得《java印章生成》对你有帮助,请点赞、收藏,并留下你的观点哦!