栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 生成根据图片内容生成图片包含格式有【png jepg GIF tiff wbmp】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 生成根据图片内容生成图片包含格式有【png jepg GIF tiff wbmp】

生成图片代码 其中一种webp格式无法生成

需引入的maven包

        
            com.twelvemonkeys.imageio
            imageio-tiff
            3.3.2
        
import sun.font.FontDesignMetrics;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;


public class CreateImages {
    public static void main(String[] args) {
        
        create(BufferedImage.TYPE_INT_RGB, "PNG", "测试数据54545454545454545", "test");
        create(BufferedImage.TYPE_INT_RGB, "JPEG", "测试数据54545454545454545", "test");
        create(BufferedImage.TYPE_INT_RGB, "GIF", "测试数据54545454545454545", "test");
        create(BufferedImage.TYPE_INT_RGB, "tiff", "测试数据54545454545454545", "test");
        create(BufferedImage.TYPE_BYTE_BINARY, "WBMP", "测试数据54545454545454545", "test");
        //暂时无法生成
        //create(BufferedImage.TYPE_INT_RGB, "webp", "测试数据54545454545454545", "test");

    }

    public static void create(int type, String formatName, String content, String pictureName) {
        String property = System.getProperty("user.dir") + "/src/main/resources/img/";
        File file = new File(property);
        if (!file.exists()) {
            file.mkdirs();
        }

        try {
            //字体字号
            int fontSize = 15;
            //文字字体
            String fontFamily = "雅黑";
            //字体字形
            int style = Font.ROMAN_baseLINE;
            //获取字体在画布中的大小
            Font f = new Font(fontFamily, style, fontSize);
            FontMetrics fm = FontDesignMetrics.getMetrics(f);
            int fontWidth = fm.stringWidth(content);
            int fontHeight = fm.getHeight();

            //初始化画布大小,根据字体像素大小进行调整
            int width = fontWidth + (fontWidth >> 1);
            int height = fontHeight + (fontHeight >> 1);

            //初始化图片的大小和背景色
            BufferedImage bi = new BufferedImage(width, height, type);
            Graphics2D g2 = bi.createGraphics();
            g2.setColor(Color.WHITE);
            g2.fillRect(0, 0, width, height);

            //在画布上写入字体
            Font font = new Font(fontFamily, style, fontSize);
            g2.setFont(font);

            //字体颜色
            g2.setPaint(Color.black);
            g2.drawString(content, (width - fontWidth) >> 1, (height >> 1) + (fontHeight >> 2));
            g2.dispose();

            //输出图片
            ImageIO.write(bi, formatName, new File(property + pictureName + "." + formatName));
        } catch (IOException ie) {
            ie.printStackTrace();

        }
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/530845.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号