java圆形印章生成

公章绘制

概述


使用场景

如果需要生成一个公章,但又不想通过三方付费生成公章,但生成的公章没有数字证书、时间戳、电子存证等一系列依据法律法规设定的电子签名技术的。


绘制思路

相关变量

    private final static int CANVASSIZE = 508; // 画布大小(宽高)
    private final static int BORDERWIDTH = 6;// 圆形边框宽度
    private final static int FONTBASESIZE = 60;// 字体基础大小
    private final static int RGB = 0xFF4141; // 文字颜色、边框颜色、五角星颜色
    private final static int STARRADIO = 80; // 五角星长半径(中心点到顶点距离)
    private final static String FONTFAMILYNAME = "FangSong_GB2312";//字体
    private final static float ZOOMRADIO = 1.4f;//字体y轴缩放比例
    private final static int ANGLE = MyAngleEnum.ANGLE_150.getAngle();//底部文字空白角度


1. 生成画布


●规定画布宽高都为a,然后创建一个BufferedImage对象,用于在内存中存储图像数据。然BufferedImage对象使用createGraphics()方法创建一个Graphics2D对象,Graphics2D提供了一系列绘制和变换方法,可以进行文字、图像、几何形状等元素的绘制。

        int fontTextLen = companyName.length;
        int fontSize = FONTBASESIZE - fontTextLen; // 动态设置大小
        BufferedImage bufferedImage = new BufferedImage(CANVASSIZE, CANVASSIZE, BufferedImage.TYPE_4BYTE_ABGR);
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//其他图形抗锯齿
        Graphics2D g2d = bufferedImage.createGraphics();
        g2d.setRenderingHints(hints);
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0));
        g2d.fillRect(0, 0, CANVASSIZE, CANVASSIZE);
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1));
        g2d.setStroke(new BasicStroke(BORDERWIDTH));
        g2d.setPaint(Color.decode(String.valueOf(RGB)));

 
2.绘制圆


●使用Graphics2D中的drawOval绘制椭圆的方法来绘制印章外圆。
●获取绘制圆的左上角的X坐标和左上角的Y坐标,假设圆形边框的宽度为b,绘制圆的左上角坐标就为(b/2,b/2),然后获取要绘制的圆的宽度和高度,因为是圆所以宽度和高度相等,宽高都为(a-b-1),因为精度问题所以多减一,然后使用Graphics2D中的drawOval方法进行绘制。

        g2d.drawOval(BORDERWIDTH / 2, BORDERWIDTH / 2, CANVASSIZE - BORDERWIDTH - 1, CANVASSIZE - BORDERWIDTH - 1);  // 由于计算精度问题,需要多减一。


3.绘制五角星


●基本公式(求旋转后点坐标公式)
在平面坐标上,任意点P(x1,y1),绕一个坐标点Q(x2,y2)旋转θ角度后,新的坐标设为(x, y)的计算公式:
x= (x1 - x2)*cos(θ) - (y1 - y2)*sin(θ) + x2 ;
y= (x1 - x2)*sin(θ) + (y1 - y2)*cos(θ) + y2 ;

6CB1898EA7962092586E2694DC740261.png


●画布中心点为五角星中心点O,中心点O坐标为(a/2,a/2),五角星长半径(线段AO长度)为r
●计算五角星五个顶点坐标,先计算A点坐标,因为A点在O点正上方,可知A点坐标为(a/2,a/2-r),
原点O到五个顶点的距离都相等,因此可以使用点旋转公式求得其他角的坐标。角AOB,角BOC,角COD,
角DOE,角EOA都为2π/5,因此可以得出其余四个点相对于A点旋转的角度,然后带入公式求顶点坐标。
最终求得的坐标:A(a/2,a/2-r);B(a/2+sin(0.4π)*r,a/2-cos(0.4π)*r);C (a/2+sin(0.2π)*r,a/2+cos(0.2π)*r);D(a/2-sin(0.2π)*r,a/2+cos(0.2π)*r);E (a/2-sin(0.4π)*r,a/2-cos(0.4π)*r)
●然后将点按ACOD,BDOE,CEOA,DBOA,ECOB分成五组,使用Graphics2D中的fillPolygon方法(绘制多边形的方法)分别通过五组的点绘制五个多边形,五个多边形组合起来就是一个五角星。
五组多边形单独绘制效果图以及最终效果图

截屏2023-11-27 11.40.18.png

// 绘制五角星。五角星分别有5个顶点,1个中心。绘制五个四边形,绘制方法:每个顶点(称为'A'点)连接不相邻的两个顶点(称为'B'点、'C'点),五角星的正中心点(称为'D'点),'B'点、'C'点分别连接'D'点。
        int canvasHalfSize = CANVASSIZE / 2;
        // 顶点坐标(5个)point0:中心点正上方顶点,从point0右边开始数顶点依次为point1,point2,point3,point4
        int[] point0 = new int[]{canvasHalfSize, canvasHalfSize - STARRADIO};
        int[] point1 = new int[]{canvasHalfSize + (int) (Math.sin(0.4 * Math.PI) * STARRADIO), canvasHalfSize - (int) (Math.cos(0.4 * Math.PI) * STARRADIO)};
        int[] point2 = new int[]{canvasHalfSize + (int) (Math.sin(0.2 * Math.PI) * STARRADIO), canvasHalfSize + (int) (Math.cos(0.2 * Math.PI) * STARRADIO)};
        int[] point3 = new int[]{canvasHalfSize - (int) (Math.sin(0.2 * Math.PI) * STARRADIO), canvasHalfSize + (int) (Math.cos(0.2 * Math.PI) * STARRADIO)};
        int[] point4 = new int[]{canvasHalfSize - (int) (Math.sin(0.4 * Math.PI) * STARRADIO), canvasHalfSize - (int) (Math.cos(0.4 * Math.PI) * STARRADIO)};
        // 中心坐标
        int[] point5 = new int[]{canvasHalfSize, canvasHalfSize};
        // 绘制5个四边形
        Polygon polygon = new Polygon();
        polygon.addPoint(point0[0], point0[1]);
        polygon.addPoint(point2[0], point2[1]);
        polygon.addPoint(point5[0], point5[1]);
        polygon.addPoint(point3[0], point3[1]);
        g2d.fillPolygon(polygon);
        polygon = new Polygon();
        polygon.addPoint(point1[0], point1[1]);
        polygon.addPoint(point3[0], point3[1]);
        polygon.addPoint(point5[0], point5[1]);
        polygon.addPoint(point4[0], point4[1]);
        g2d.fillPolygon(polygon);
        polygon = new Polygon();
        polygon.addPoint(point2[0], point2[1]);
        polygon.addPoint(point4[0], point4[1]);
        polygon.addPoint(point5[0], point5[1]);
        polygon.addPoint(point0[0], point0[1]);
        g2d.fillPolygon(polygon);
        polygon = new Polygon();
        polygon.addPoint(point3[0], point3[1]);
        polygon.addPoint(point0[0], point0[1]);
        polygon.addPoint(point5[0], point5[1]);
        polygon.addPoint(point1[0], point1[1]);
        g2d.fillPolygon(polygon);
        polygon = new Polygon();
        polygon.addPoint(point4[0], point4[1]);
        polygon.addPoint(point2[0], point2[1]);
        polygon.addPoint(point5[0], point5[1]);
        polygon.addPoint(point1[0], point1[1]);
        g2d.fillPolygon(polygon);


4.绘制文字


●字体动态设置大小:文字的基础字体大小减去文字的长度,然后对文字进行拉伸,拉伸后的长度为文字基本长度的1.4倍。
●计算文字绘制位置,这里采取的方法是先将文字移动到同一位置,然后再进行旋转操作。
●首先进行文字平移,文字在水平方向上平移的距离为画布的一半减去字体尺寸的一半,y轴不做平移。对文字设置一个padding值,padding值根据字体拉伸进行一个变化,值为(拉伸的值*1.2)
所有文字平移效果图:

截屏2023-11-27 14.02.06.png

截屏2023-11-27 14.15.44.png


●对文字进行一个旋转操作将所有文字都旋转到空白区域左边位置也就是图中“这”字的位置,文字的旋转中心点为画布中心点,旋转的度数根据文字空白区域的角度进行一个动态的计算,代码中对底部空白部分角度进行了一个枚举,枚举的角度x有60,75,90,105,120,135,150这7个值,Graphics2D中的rotate方法是从右边开始旋转的,因此可以求出角度为 (1+x/360)*π,
●然后计算每个字相隔的角度,文字部分所占的角度为360度减去空白区域的角度x,假设文字个数为n,每个字之间间隔的度数是相等的,因此每个字相隔的角度为(360-x)*π/(180n-180),然后所有文字相较于前一个文字进行一个相隔角度的旋转(第一个文字不需要再进行旋转)。
最终绘制效果图:

截屏2023-11-27 14.55.44.png

        Font font = new Font(FONTFAMILYNAME, Font.ROMAN_BASELINE, fontSize);
        AffineTransform transform = new AffineTransform();
        transform.scale(1.0, ZOOMRADIO); // 将字体在垂直方向拉伸
        Font stretchedFont = font.deriveFont(transform);
        g2d.setFont(stretchedFont);
        int fontHalfSize = fontSize / 2;
        g2d.translate(canvasHalfSize - fontHalfSize, 0);
        g2d.rotate((1+ (double) ANGLE /360)*Math.PI, fontHalfSize, canvasHalfSize);
        float paddingRate = (ZOOMRADIO * 1.2f);
        double theta = (double) (360 - ANGLE)* Math.PI/(180*companyName.length-180);
        for (int i = 0; i < companyName.length; i++) {
            if (i != 0) {
                g2d.rotate(theta, fontHalfSize, canvasHalfSize);
            }
            g2d.drawString(String.valueOf(companyName[i]), 0, fontSize * paddingRate);
        }
        g2d.dispose();
        store(bufferedImage, outputFilePath);


使用示例

1.完整源码

package com.recky.seal;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @ClassName:CustomSealUtil
 * @Description:
 * @Auther: zhouruiqi
 * @Date: 2023/11/21
 **/
public class CustomSealUtil {
    private final static int CANVASSIZE = 508; // 画布大小(宽高)
    private final static int BORDERWIDTH = 6;// 圆形边框宽度
    private final static int FONTBASESIZE = 60;// 字体基础大小
    private final static int RGB = 0xFF4141; // 文字颜色、边框颜色、五角星颜色
    private final static int STARRADIO = 80; // 五角星长半径(中心点到顶点距离)
    private final static String FONTFAMILYNAME = "FangSong_GB2312";//字体
    private final static float ZOOMRADIO = 1.4f;//字体y轴缩放比例
    private final static int ANGLE = MyAngleEnum.ANGLE_150.getAngle();//底部文字空白角度


    public static void gennerSeal(String text, String outputFilePath) throws Exception {
        char[] companyName = text.toCharArray();
        int fontTextLen = companyName.length;
        int fontSize = FONTBASESIZE - fontTextLen; // 动态设置大小
        BufferedImage bufferedImage = new BufferedImage(CANVASSIZE, CANVASSIZE, BufferedImage.TYPE_4BYTE_ABGR);
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//其他图形抗锯齿
        Graphics2D g2d = bufferedImage.createGraphics();
        g2d.setRenderingHints(hints);
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0));
        g2d.fillRect(0, 0, CANVASSIZE, CANVASSIZE);
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1));
        g2d.setStroke(new BasicStroke(BORDERWIDTH));
        g2d.setPaint(Color.decode(String.valueOf(RGB)));
        // 绘制圆
        g2d.drawOval(BORDERWIDTH / 2, BORDERWIDTH / 2, CANVASSIZE - BORDERWIDTH - 1, CANVASSIZE - BORDERWIDTH - 1);  // 由于计算精度问题,需要多减一。
        // 绘制五角星。五角星分别有5个顶点,1个中心。绘制五个四边形,绘制方法:每个顶点(称为'A'点)连接不相邻的两个顶点(称为'B'点、'C'点),五角星的正中心点(称为'D'点),'B'点、'C'点分别连接'D'点。
        int canvasHalfSize = CANVASSIZE / 2;
        // 顶点坐标(5个)point0:中心点正上方顶点,从point0右边开始数顶点依次为point1,point2,point3,point4
        int[] point0 = new int[]{canvasHalfSize, canvasHalfSize - STARRADIO};
        int[] point1 = new int[]{canvasHalfSize + (int) (Math.sin(0.4 * Math.PI) * STARRADIO), canvasHalfSize - (int) (Math.cos(0.4 * Math.PI) * STARRADIO)};
        int[] point2 = new int[]{canvasHalfSize + (int) (Math.sin(0.2 * Math.PI) * STARRADIO), canvasHalfSize + (int) (Math.cos(0.2 * Math.PI) * STARRADIO)};
        int[] point3 = new int[]{canvasHalfSize - (int) (Math.sin(0.2 * Math.PI) * STARRADIO), canvasHalfSize + (int) (Math.cos(0.2 * Math.PI) * STARRADIO)};
        int[] point4 = new int[]{canvasHalfSize - (int) (Math.sin(0.4 * Math.PI) * STARRADIO), canvasHalfSize - (int) (Math.cos(0.4 * Math.PI) * STARRADIO)};
        // 中心坐标
        int[] point5 = new int[]{canvasHalfSize, canvasHalfSize};
        // 绘制5个四边形
        Polygon polygon = new Polygon();
        polygon.addPoint(point0[0], point0[1]);
        polygon.addPoint(point2[0], point2[1]);
        polygon.addPoint(point5[0], point5[1]);
        polygon.addPoint(point3[0], point3[1]);
        g2d.fillPolygon(polygon);
        polygon = new Polygon();
        polygon.addPoint(point1[0], point1[1]);
        polygon.addPoint(point3[0], point3[1]);
        polygon.addPoint(point5[0], point5[1]);
        polygon.addPoint(point4[0], point4[1]);
        g2d.fillPolygon(polygon);
        polygon = new Polygon();
        polygon.addPoint(point2[0], point2[1]);
        polygon.addPoint(point4[0], point4[1]);
        polygon.addPoint(point5[0], point5[1]);
        polygon.addPoint(point0[0], point0[1]);
        g2d.fillPolygon(polygon);
        polygon = new Polygon();
        polygon.addPoint(point3[0], point3[1]);
        polygon.addPoint(point0[0], point0[1]);
        polygon.addPoint(point5[0], point5[1]);
        polygon.addPoint(point1[0], point1[1]);
        g2d.fillPolygon(polygon);
        polygon = new Polygon();
        polygon.addPoint(point4[0], point4[1]);
        polygon.addPoint(point2[0], point2[1]);
        polygon.addPoint(point5[0], point5[1]);
        polygon.addPoint(point1[0], point1[1]);
        g2d.fillPolygon(polygon);
        // 绘制文字
        Font font = new Font(FONTFAMILYNAME, Font.ROMAN_BASELINE, fontSize);
        AffineTransform transform = new AffineTransform();
        transform.scale(1.0, ZOOMRADIO); // 将字体在垂直方向拉伸
        Font stretchedFont = font.deriveFont(transform);
        g2d.setFont(stretchedFont);
        int fontHalfSize = fontSize / 2;
        g2d.translate(canvasHalfSize - fontHalfSize, 0);
        g2d.rotate((1+ (double) ANGLE /360)*Math.PI, fontHalfSize, canvasHalfSize);//
        float paddingRate = (ZOOMRADIO * 1.2f);
        double theta = (double) (360 - ANGLE)* Math.PI/(180*companyName.length-180);
        for (int i = 0; i < companyName.length; i++) {
            if (i != 0) {
                g2d.rotate(theta, fontHalfSize, canvasHalfSize);
            }
            g2d.drawString(String.valueOf(companyName[i]), 0, fontSize * paddingRate);
        }
        g2d.dispose();
        store(bufferedImage, outputFilePath);
    }

    private static byte[] buildBytes(BufferedImage image) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outStream);
        return outStream.toByteArray();
    }

    private static void store(BufferedImage srcImage, String targetFilePath) throws Exception {
        store(buildBytes(srcImage), targetFilePath);
    }

    private static void store(byte[] srcBytes, String targetFilePath) throws IOException {
        File file = new File(targetFilePath);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bos.write(srcBytes);
        bos.close();
        fos.close();
    }
    private enum MyAngleEnum {
        ANGLE_60(60),
        ANGLE_75(75),
        ANGLE_90(90),
        ANGLE_105(105),
        ANGLE_120(120),
        ANGLE_135(135),
        ANGLE_150(150);
        private int angle;
        MyAngleEnum(int angle) {
            this.angle = angle;
        }
        public int getAngle() {
            return angle;
        }
    }
}

2. 使用demo 

package com.recky.demo;

import com.recky.seal.CustomSealUtil;

public class Main {
    public static void main(String[] args) throws Exception {
        CustomSealUtil.gennerSeal("这是一个测试印章","/Users/zhouruiqi/Desktop/test3.png"); 
    }
}

  • 14
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
要实现 Java 中的印章签名,可以使用数字证书和印章图片。具体操作步骤如下: 1. 获取数字证书和私钥,并使用私钥对印章图片进行签名。可以使用 Java 中的 KeyStore 类和 PrivateKey 接口来获取证书和私钥。 ``` KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(new FileInputStream("path/to/certificate.pfx"), "password".toCharArray()); String alias = keyStore.aliases().nextElement(); X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, "password".toCharArray()); BufferedImage stamp = ImageIO.read(new FileInputStream("path/to/stamp.png")); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(privateKey); ByteArrayOutputStream stampBytes = new ByteArrayOutputStream(); ImageIO.write(stamp, "png", stampBytes); byte[] stampData = stampBytes.toByteArray(); signature.update(stampData); byte[] signedData = signature.sign(); ``` 2. 将签名后的印章图片和证书一起写入 PDF 文件中。可以使用 iText 库来操作 PDF 文件。 ``` PdfReader reader = new PdfReader("path/to/unsigned.pdf"); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("path/to/signed.pdf")); PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("I am the author"); appearance.setLocation("Beijing"); appearance.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, "signature"); PdfTemplate template = PdfTemplate.createTemplate(stamper.getWriter(), stamp.getWidth(), stamp.getHeight()); Graphics2D g2d = template.createGraphics(stamp.getWidth(), stamp.getHeight()); g2d.drawImage(stamp, 0, 0, null); g2d.dispose(); PdfImage image = PdfImage.getImage(template); appearance.setImage(image); ExternalSignature pks = new PrivateKeySignature(privateKey, "SHA-256", "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, new X509Certificate[]{cert}, null, null, null, 0, MakeSignature.CryptoStandard.CMS); stamper.close(); reader.close(); ``` 以上就是 Java 实现印章签名的基本步骤。需要注意的是,本例中使用了 BouncyCastle 库来实现签名算法,需要预先引入该库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值