gpt4 book ai didi

java - java中缩放图像

转载 作者:行者123 更新时间:2023-12-02 04:07:53 25 4
gpt4 key购买 nike

我需要创建一个 Web 服务,该服务将根据用户的姓名缩写生成用户的图标。类似于 this Android 项目,但在服务器端使用 Java。

Image

该图像的大小应该是动态的。我已经有了可以创建一个中间有两个字母的矩形的代码,但它不会缩放文本。

这是迄今为止我的代码:

public BufferedImage getAbbreviationImage(int height, int width, String abbreviation) throws IOException {

int centerX = width/2;
int centerY = height/2;

BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.SCALE_SMOOTH);

Graphics2D g = bufferedImage.createGraphics();
Font font = new Font("Helvetica", Font.BOLD, 90);
g.setFont(font);
g.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);

g.setColor(Color.decode("#3f404c"));
g.fillRect(0, 0, width, height);


// get the bounds of the string to draw.
FontMetrics fontMetrics = g.getFontMetrics();
Rectangle stringBounds = fontMetrics.getStringBounds(abbreviation, g).getBounds();

FontRenderContext renderContext = g.getFontRenderContext();
GlyphVector glyphVector = font.createGlyphVector(renderContext, abbreviation);
Rectangle visualBounds = glyphVector.getVisualBounds().getBounds();

// calculate the lower left point at which to draw the string. note that this we
// give the graphics context the y corridinate at which we want the baseline to
// be placed. use the visual bounds height to center on in conjuction with the
// position returned in the visual bounds. the vertical position given back in the
// visualBounds is a negative offset from the basline of the text.
int textX = centerX - stringBounds.width/2;
int textY = centerY - visualBounds.height/2 - visualBounds.y;

g.setColor(Color.WHITE);
g.drawString(abbreviation, textX, textY);

g.dispose();

return bufferedImage;
}

是否有任何 Java 库可以执行类似的操作,这样我就不必编写自己的代码了。如果没有,那么根据图像大小缩放文本的最佳方法是什么?

学分:我的一些代码取自 HERE

最佳答案

您需要设置附加到 Graphics2D 对象的字体大小。来自甲骨文文档:

public abstract void drawString(String str,
int x,
int y)

Renders the text of the specified String, using the current text attribute state in the Graphics2D context

您应该适当设置所使用的字体大小以匹配矩形的尺寸。像这样的事情:

int lFontSize = 90 * (originalRectangleWidth / newRectangleWidth);
Font font = new Font("Helvetica", Font.BOLD, lFontSize );

地点:

  • 90 是引用字体大小(这是您在示例中设置的值)

  • originalRectangleWidth 是当字体大小为 90 时看起来不错时使用的矩形的大小

  • newRectangleWidth 将是新的矩形宽度

引用文献: Graphics2D (oracle ref) Font (oracle ref)

关于java - java中缩放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34083503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com