工具类
java操作图片,给一个大图片贴小图片,给图片添加文字并调整文字颜色,大小,字体间距,把本地图片或者网络图片加载到缓冲区
主要方法:
- imageIoRead方法,把图片加载到缓冲区
- mergeImage方法,给一张图片贴 图片,并生成新图片
- drawTextInImg给图片上写多行文字文字,自动居中,并可以调整字体间距。
drawString调整字体间距
package com.img;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
/**
*
* 类名称:ImageUtil
* 类描述: 图片操作工具类 把图片加载到内存,给图片 贴图,给图片添加文字
* 创建时间:2021年7月30日 上午10:27:13
* @version
*/
public class ImageUtil {
/**
* 解析本地图片或者http网络图片,并把图片加载到缓冲区
* @param path 图片路径(本地路径或者网络图片http访问路径)
* @throws IOException 抛出异常
*/
public BufferedImage imageIoRead(String path) throws IOException {
BufferedImage bufferedImage;
if(path.contains("http")){
//网络图片
bufferedImage = ImageIO.read(new URL(path));
}else{
//本地图片
bufferedImage = ImageIO.read(new File(path));
}
return bufferedImage;
}
/**
* 给一张图片贴 图片,并生成新图片
* @param bigPath 底图路径
* @param smallPath 要贴的图片路径
* @param outPath 合成输出图片路径
* @param x 贴图的位置
* @param y 贴图的位置
* @param smallWidth 要贴的图片宽度
* @param smallHeight 要贴的图片高度
* @throws IOException 抛出io异常
*/
public void mergeImage( String bigPath,
String smallPath,
String outPath,
String x,
String y,
int smallWidth,
int smallHeight ) throws IOException {
try {
//加载图片
BufferedImage small = imageIoRead(smallPath);
BufferedImage big = imageIoRead(bigPath);
//得到2d画笔对象
Graphics2D g = big.createGraphics();
float fx = Float.parseFloat(x);
float fy = Float.parseFloat(y);
int x_i = (int)fx;