import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.springframework.util.Assert;
public class ImageUtils {
/**
* 图片合成
*
* @param backgroundPath 底图
* @param smallPath 小图
* @param type 生成图片类型jpg,png...
* @param resultPaht 生成图片保存路径
*/
public static void image(String backgroundPath, String smallPath, String type, String resultPaht) {
try {
Assert.hasText(backgroundPath, "底图路径为空");
Assert.hasText(smallPath, "小图路径为空");
BufferedImage small = getBufferedImageFromUrl(smallPath);
BufferedImage image = getBufferedImageFromUrl(backgroundPath);
//生成画笔
Graphics g = image.getGraphics();
g.drawImage(small, image.getWidth() - small.getWidth(), image.getHeight() - small.getHeight(),
image.getWidth(), image.getHeight(), null);
ImageIO.write(image, type, new File(resultPaht));
} catch (IOException e) {
throw new RuntimeException("合成图片失败", e);
}
}
/**
* 根据图片url获取图片
*
* @param url
* @return
* @throws IOException
*/
private static BufferedImage getBufferedImageFromUrl(String url) throws IOException {
if (url.startsWith("https://") || url.startsWith("http://")) {
return ImageIO.read(new URL(url));
} else {
return ImageIO.read(new File(url));
}
}
}
Graphics.drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)方法:
img:小图
x:小图左顶点在地图x轴的位置
y:小图左顶点在地图y轴的位置
width:生成新图的宽度
height:生成新图的高度
observer:检测图片改变的“图片观察者”,实际中基本用不到。因为这个观察者类在java设计中有严重缺陷,会导致图片绘制不及时,所以图片更新的工作往往都是由开发者自己来做