package com.mon.utils;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;/*** 背景图生成工具类* by.白名 ykbaiming@*/public class BackgroundImageSynthesisUtils {/*** 合成纯色背景图** @param width宽度* @param height 高度* @param colorCode tgb 颜色代码* @param outPath 输出路径* @return*/public static boolean createBackgroundImg(Integer width, Integer height, String colorCode, String outPath) {BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);String[] colorArr = formatColorCode(colorCode);if (colorArr == null) {return false;}File backgroundImg = new File(outPath);if (!backgroundImg.exists()) {backgroundImg.mkdirs();}return writeImage(bufferedImage, "PNG", backgroundImg, colorArr);}/*** 格式化颜色参数** @param colorCode* @return*/private static String[] formatColorCode(String colorCode) {if (!colorCode.contains("rgba")) {return null;}colorCode = colorCode.replaceAll("rgba\\(", "").replaceAll("\\)", "");return colorCode.split(",");}/*** 通过指定参数写一个图片*/private static boolean writeImage(BufferedImage bi, String picType, File file, String[] colorArr) {Graphics g = bi.getGraphics();g.setColor(new Color(Integer.parseInt(colorArr[0]), Integer.parseInt(colorArr[1]), Integer.parseInt(colorArr[2])));for (int i = 0; i < bi.getWidth(); i++) {for (int j = 0; j < bi.getHeight(); j++) {g.drawLine(i, j, bi.getWidth(), bi.getHeight());}}g.dispose();boolean val = false;try {val = ImageIO.write(bi, picType, file);} catch (IOException e) {e.printStackTrace();}return val;}}
900字范文,内容丰富有趣,生活中的好帮手!