工具类-Java输入特定的字符串生成背景色字体的图片
1.编写LogoImageUtils工具类
package com.zhangsan.utils;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* @ClassName LogoImageUtils
* @Description TODO
* @Author ZhangSan_Plus
* @Date 2021/9/9 20:16
* @Version 1.0
**/
@Component
public class LogoImageUtils {
/**
* @param response
* @param fontSize 字体大小
* @param height 高
* @param value 字符串
* @param width 高
* @param
* @return void
* @author ZhangSan_Plus
* @description //TODO 根据特定的字符生成图片
* @date 20:55 2021/9/9
**/
public static void paint(int width, int height, int fontSize, String value, HttpServletResponse response) {
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
//白底
graphics2D.setColor(Color.WHITE);
graphics2D.fillRect(0, 0, width, height);
//黑字
graphics2D.setColor(Color.BLACK);
Font font = new Font("黑体", Font.BOLD, fontSize);
graphics2D.setFont(font);
//支付居中
FontMetrics fontMetrics = graphics2D.getFontMetrics(font);
int x = (width - fontMetrics.stringWidth(value)) / 2;
int y = height / 2 - font.getSize() * 4 / 5 + fontMetrics.getHeight();
graphics2D.drawString(value, x, y);
graphics2D.dispose();
try {
//此处可以可以使用 ImageIO.write(bufferedImage, "jpg", new File(value));来生成到对应的文件目录下
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.此处编写LogoController进行测试
package com.zhangsan.controller;
import com.zhangsan.utils.LogoImageUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName LogoController
* @Description TODO
* @Author ZhangSan_Plus
* @Date 2021/9/9 20:17
* @Version 1.0
**/
@RestController
@RequestMapping("/api/zhangsan")
public class LogoController {
@GetMapping("getLogoImage")
public void getLogoImage(@RequestParam("str") String str, HttpServletResponse response) {
LogoImageUtils logoImageUtils = new LogoImageUtils();
logoImageUtils.paint(400, 400, 80, str, response);
}
}
3.查看展示效果吧
本文作者:张三Blog
本文链接:https://www.cnblogs.com/zhangsan-plus/p/16503261.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步