六、添加艺术字到图片

(一)FontUtils 工具类(功能:读取艺术字体文件,转换成 Font 对象)

import org.springframework.util.StringUtils;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author 咸鱼
 * @date 2018/12/17 21:21
 */
public final class FontUtils {
    private static Map<String, File> fontMap = new HashMap<>();

    /*
     * 扫描所有的艺术字体包
     */
    static {
        InputStream resourceAsStream = FontUtils.class.getClassLoader().getResourceAsStream("application.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
            String fontFilePath = properties.getProperty("font.path");
            if (StringUtils.isEmpty(fontFilePath)) {
                System.out.println("未配置艺术字体文件路径");
            } else {
                File file = new File(fontFilePath);
                File[] files = file.listFiles();
                if (files != null && files.length > 0){
                    for (File tempFile : files){
                        String fileName = tempFile.getName();
                        String fontName = fileName.substring(0, fileName.indexOf("."));
                        fontMap.put(fontName, tempFile);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                resourceAsStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     *  引入自定义的字体
     * @param fontName 字体样式
     * @param fontSize  字体大小
     * @return 字体对象
     */
    public static Font getFont(String fontName, float fontSize) {
        Font font = null;
        File file = fontMap.get(fontName);
        if (file != null){
            try(FileInputStream fileInputStream = new FileInputStream(file)) {
                Font tempFont = Font.createFont(Font.TRUETYPE_FONT, fileInputStream);
                //当参数为 float 类型,才是设置文字大小
                font = tempFont.deriveFont(fontSize);
            } catch (IOException | FontFormatException e) {
                e.printStackTrace();
            }
        }
        return font;
    }
    /**
     * 将字符串按照自定义的间隔写入
     * @param str   目标字符串
     * @param x     写入的位置的x轴
     * @param y     写入的位置的y轴
     * @param rate  写入间隔
     * @param g     画布
     * @param fontSize  字体的大小
     */
    public static void drawString(String str,int x,int y,int rate, Graphics2D g,int fontSize){
        String tempStr="";
        int tempx=x;
        while (str.length()>0){
            tempStr=str.substring(0, 1);
            str=str.substring(1, str.length());
            //使图形去除锯齿状,可以得到多么细腻的图形
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
            g.drawString(tempStr, tempx, y);
            tempx = tempx + fontSize - rate;
        }
    }
}

(二)ImageUtils工具类

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

/**
 * @author 咸鱼
 * @date 2018/12/17 21:50
 */
public final class ImageUtils {
    /**
     * 获取文字字体(艺术字)
     * @param fontName 字体名
     * @param fontSize 字体大小
     * @return 字体
     */
    public static Font getFont(String fontName, int fontSize){
        return getFont(fontName, null, fontSize);
    }

    /**
     * 获取文字字体
     * @param fontName 字体名
     * @param fontStyle 字体样式
     * @param fontSize 字体大小
     * @return 字体
     */
    public static Font getFont(String fontName, Integer fontStyle, int fontSize){
        Font defaultFont = new Font("宋体", Font.BOLD, fontSize);
        Font font;
        if (fontStyle != null){
            //普通字体
            font = new Font(fontName, fontStyle, fontSize);
        } else {
            //艺术字
            font = FontUtils.getFont(fontName, fontSize);
            if (font == null){
                //默认字体
                font = defaultFont;
            }
        }
        return font;
    }

    /**
     * 在图片上添加文字
     * @param pressText 水印文字
     * @param srcImageFile 原图路径
     * @param desImageFile 目标图路径
     * @param fontColor 字体颜色
     * @param font 字体对象
     * @param x 横坐标
     * @param y 纵坐标
     * @param alpha 透明度
     */
    public static void pressText(String pressText, String srcImageFile, String desImageFile,
                                 Color fontColor, Font font,
                                 int x, int y, float alpha) {
        try {
            File img = new File(srcImageFile);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            g.setColor(fontColor);
            g.setFont(font);
            //设置透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            // 在指定坐标(图片居中)绘制水印文字
            g.drawString(pressText, (width - (getLength(pressText) * font.getSize())) / 2 + x,
                    (height - font.getSize()) / 2 + y);
            g.dispose();
            // 输出到文件流
            ImageIO.write(image, "JPEG", new File(desImageFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 绘制水印图片
     * @param pressImgFile 水印图片
     * @param srcImageFile 原图
     * @param desImageFile 目标图
     * @param x 横坐标
     * @param y 纵坐标
     * @param alpha 透明度
     */
    public static void pressImage(String pressImgFile, String srcImageFile,String desImageFile,
                                        int x, int y, float alpha) {
        try {
            File img = new File(srcImageFile);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            // 水印图片
            Image imgIcon = ImageIO.read(new File(pressImgFile));
            int imgIconWidth = imgIcon.getWidth(null);
            int imgIconHeight = imgIcon.getHeight(null);
            //设置透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            //居中绘制水印图片
            g.drawImage(imgIcon, (width - imgIconWidth) / 2 + x,
                    (height - imgIconHeight) / 2 + y, imgIconWidth, imgIconHeight, null);
            //释放画板
            g.dispose();
            ImageIO.write(image,"JPEG", new File(desImageFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 得到文本长度的一半
     * @param text 文本
     * @return 文本总长度的一半
     */
    public static int getLength(String text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if ((text.charAt(i) + "").getBytes().length > 1) {
                //中文2个字节
                length += 2;
            } else {
                //非中文1个字节
                length += 1;
            }
        }
        return length / 2;
    }

    /**
     * 图像类型转换
     * @param srcImageFile 原图路径
     * @param formatName  目标图格式
     * @param desImageFile 目标图路径
     */
    public static void convert(String srcImageFile, String formatName, String desImageFile) {
        try {
            File imageFile = new File(srcImageFile);
            if (imageFile.canRead() && imageFile.canWrite()) {
                BufferedImage src = ImageIO.read(imageFile);
                ImageIO.write(src, formatName, new File(desImageFile));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

(三)准备好字体包

在这里插入图片描述

(四)配置 艺术字体 文件路径
application.properties

font.path=E:\demo\font

(五)测试

public static void main(String[] args) throws ClassNotFoundException {

        //普通字体
        Font systemFont = getFont("宋体", Font.BOLD, 30);
        pressText("我有一只小毛驴","e:/demo/test.jpg", "e:/demo/student_pressText1.jpg",
                Color.RED, systemFont,
                0, 0, 0.5f);
        //艺术字体
        Font customFont = getFont("新蒂剪纸体", 30);
        pressText("我有一只小毛驴","e:/demo/test.jpg", "e:/demo/student_pressText2.jpg",
                Color.RED, customFont,
                0, 0, 0.5f);
        //绘制水印图片
        pressImage("e:/demo/student.jpg", "e:/demo/test.jpg","e:/demo/abc_pressImage.jpg",
                0, 0, 0.5f);

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值