我正在尝试计算图像中心(添加水印)以下 - add-water-to-image,结果显示负x,对于某些图像,这里是数学部分:
int centerX = (sourceImage.getWidth() - (int) rect.getWidth()) / 2;
int centerY = sourceImage.getHeight() / 2;
和整个功能:
public void addTextWatermark(String text, File sourceImageFile, File destImageFile, int textSize) {
try {
BufferedImage sourceImage = ImageIO.read(sourceImageFile);
Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();
// initializes necessary graphic properties
AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f);
g2d.setComposite(alphaChannel);
g2d.setColor(Color.BLACK.darker());
//Font(fontName, fontStyle, foneSize)
g2d.setFont(new java.awt.Font("Arial", Font.BOLD, textSize));
FontMetrics fontMetrics = g2d.getFontMetrics();
//text - input text , g2d - Graphics2D
Rectangle2D rect = fontMetrics.getStringBounds(text, g2d);
// calculates the coordinate where the String is painted
int centerX = (sourceImage.getWidth() - (int) rect.getWidth()) / 2;
int centerY = sourceImage.getHeight() / 2;
// paints the textual watermark
g2d.drawString(text, centerX, centerY);
ImageIO.write(sourceImage, "png", destImageFile);
g2d.dispose();
} catch (IOException ex) {
System.out.println(ex.getMessage().toString());
}
}
1 - 有没有办法确保数学适用于所有图像?
2 - 此钙化中jpg
和png
之间是否存在差异?
感谢。
修改的
导致它的图像尺寸为:
1到大(3000 * 3000)。
2到小(60 * 60)。
使用textSize(g2d.setFont(new java.awt.Font("Arial", Font.BOLD, textSize));
) - 32或更少。
答案 0 :(得分:0)
所以我找到了两种方法来处理这个问题:
1-如果x或y小于0,我使用resize-image
调整图像大小 2-如果水印很小,只需增加文字大小 - g2d.setFont(new java.awt.Font("Arial", Font.BOLD, textSize));
感谢@jon Skeet的所有帮助。