java在图片下方写文字_Java画图给图片底部添加文字标题
Java畫圖 給圖片底部添加文字標題
需求給圖片底部添加文字編號
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* JAVA 畫圖(生成文字水印)
*
* @author 杰寶寶
*
*/
public class ImageUtil {
/**
* @param str
* 生產的圖片文字
* @param oldPath
* 原圖片保存路徑
* @param newPath
* 新圖片保存路徑
* @param width
* 定義生成圖片寬度
* @param height
* 定義生成圖片高度
* @return
* @throws IOException
*/
public void create(String str, String oldPath, String newPath, int width, int height){
try {
File oldFile = new File(oldPath);
Image image = ImageIO.read(oldFile);
File file = new File(newPath);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, width, height);
g2.drawImage(image, 0, 0, width - 25, height - 25, null); //這里減去25是為了防止字和圖重合
/** 設置生成圖片的文字樣式 * */
Font font = new Font("黑體", Font.BOLD, 25);
g2.setFont(font);
g2.setPaint(Color.BLACK);
/** 設置字體在圖片中的位置 在這里是居中* */
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(str, context);
double x = (width - bounds.getWidth()) / 2;
//double y = (height - bounds.getHeight()) / 2; //Y軸居中
double y = (height - bounds.getHeight());
double ascent = -bounds.getY();
double baseY = y + ascent;
/** 防止生成的文字帶有鋸齒 * */
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
/** 在圖片上生成文字 * */
g2.drawString(str, (int) x, (int) baseY);
ImageIO.write(bi, "jpg", file);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
ImageUtil img = new ImageUtil();
img.create("編號:0011", "E:\\111.png", "E:\\222.png", 455, 455);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
原圖:
image.png
生成后:
image.png
總結
以上是生活随笔為你收集整理的java在图片下方写文字_Java画图给图片底部添加文字标题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java cookie p3p_P3P解
- 下一篇: java求职_Java 求职怎么积累知识