[英]Scaling image in java
我有一個創建Web服務的要求,該服務將基於用戶的姓名縮寫生成用戶的圖標。 類似於此 Android項目,但在服務器端使用Java。
該圖像的大小應該是動態的。 我已經有將創建一個中間有兩個字母的矩形的代碼,但是它沒有縮放文本。
到目前為止,這是我的代碼:
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對象的字體的大小。 從oracle文檔中:
public abstract void drawString(String str,
int x,
int y)
使用Graphics2D上下文中的當前文本屬性狀態呈現指定字符串的文本
您應該設置適當使用的字體大小以匹配矩形的尺寸。 像這樣:
int lFontSize = 90 * (originalRectangleWidth / newRectangleWidth);
Font font = new Font("Helvetica", Font.BOLD, lFontSize );
哪里:
90是參考字體大小(這是您在示例中設置的大小)
當字體大小為90時,originalRectangleWidth將是您使用的矩形的大小
newRectangleWidth將是新的矩形寬度
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.