이미지를 불러와서 상단에 캡션을 넣는 방법이다.
기존 thumbnailator의 filter로 캡션을 넣을 수는 있지만 캡션의 배경색 지정이 안되어서 직접 Graphics를 활용하였다.
int WIDTH = 400;
int HEIGHT = 400;
BufferedImage originalImage = ImageIO.read(new File(filename));
BufferedImage thumbnailImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbnailImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, WIDTH, HEIGHT, null);
graphics2D.dispose();
String text = "홍길동"; // 캡션에 들어가는 글자
Font font = new Font("Monospaced", Font.PLAIN, 20); // 폰트 지정
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.WHITE); // foreground 색
attributedText.addAttribute(TextAttribute.BACKGROUND, Color.GRAY); // background 색
Graphics g = thumbnailImage.getGraphics();
g.setFont(font);
g.setColor(Color.WHITE);
g.drawString(attributedText.getIterator(), 20, 30);
ImageIO.write(thumbnailImage, "jpg", new File(filename));
캡션의 위치는 기본적으로 TOP_LEFT로 지정이 되는데 우측에서 표시되게 하려면 계산 로직이 필요한것 같다.
아래 코드를 참고해서 구현하자.
https://www.codeproject.com/Tips/773878/Drawing-Text-with-Wrapping-and-Text-Alignment
반응형