1、
public static void createDateImage(String imageUrl) throws Exception{
int width = 110;
int height = 30;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String s = sdf.format(date);
File file = new File(imageUrl);
Font font = new Font("Serif", Font.BOLD, 10);
// 创建一个画布
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取画布的画笔
Graphics2D g2 = (Graphics2D) bi.getGraphics();
// 开始绘图
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, width, height);
g2.setPaint(new Color(0, 0, 0));
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(s, context);
double x = (width - bounds.getWidth()) / 2;
double y = (height - bounds.getHeight()) / 2;
double ascent = -bounds.getY();
double baseY = y + ascent+2;
g2.drawString(s, 10, (int) baseY);
ImageIO.write(bi, "png", file);
g2.dispose();
changeImgBackColor(imageUrl);
}
public static void changeImgBackColor(String path) throws IOException {
BufferedImage bi = ImageIO.read(new FileInputStream(path));
Image image = (Image) bi;
//将原图片的二进制转化为ImageIcon
ImageIcon imageIcon = new ImageIcon(image);
int width = imageIcon.getIconWidth();
int height = imageIcon.getIconHeight();
//图片缓冲流
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
graphics2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
int alpha = 255;
//这个背景底色的选择,选择的是比较偏的位置,可以修改位置。背景色选择不知道有没有别的更优的方式
int RGB=bufferedImage.getRGB(width-1, height-1);
for(int i = bufferedImage.getMinX(); i < width; i++) {
for(int j = bufferedImage.getMinY(); j < height; j++) {
int rgb = bufferedImage.getRGB(i, j);
int r = (rgb & 0xff0000) >>16;
int g = (rgb & 0xff00) >> 8;
int b = (rgb & 0xff);
int R = (RGB & 0xff0000) >>16;
int G = (RGB & 0xff00) >> 8;
int B = (RGB & 0xff);
//a为色差范围值,渐变色边缘处理,数值需要具体测试,50左右的效果比较可以
int a = 45;
if(Math.abs(R-r) < a && Math.abs(G-g) < a && Math.abs(B-b) < a ) {
alpha = 0;
} else {
alpha = 255;
}
rgb = (alpha << 24)|(rgb & 0x00ffffff);
bufferedImage.setRGB(i,j,rgb);
}
}
ImageIO.write(bufferedImage, "png", new File(path));
graphics2D.dispose();
}
public static String createDatePicture(String path,String date) {
String datePictureFilePAth="";
//日期图片
String datePicturePAth = path + date + File.separator + OcrConstantUtil.INFO_DATE+ File.separator;
datePictureFilePAth = datePicturePAth+ImagesUtils.getDateName()+OcrConstantUtil.IMAGE_TYPE_PNG;
try{
File imageFile = new File(datePictureFilePAth);
if (!imageFile.exists()) {
//图片路径处理
filePathExists(datePicturePAth);
//创建日期图片
createDateImage(datePictureFilePAth);
}
return datePictureFilePAth;
}catch (Exception e){
logger.error(e.getMessage());
return datePictureFilePAth;
}
}