새소식

반응형
Language/Java

[Java] 자바 텍스트 들어간 이미지 만드는 방법

  • -
반응형

2023-08-25


사진: Unsplash 의 NEOM


1. 방법

 

 Java에서는 java.awt.image.BufferedImage와 javax.imageio.ImageIO를 사용해서 만들면 됩니다.

 

import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

public class CaptchaGenerator {

    public static BufferedImage createCaptcha(String word, int imgWidth, int imgHeight) {
        BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 배경이미지 설정
        g2d.setColor(new Color(255, 255, 255));
        g2d.fillRect(0, 0, imgWidth, imgHeight);

        // 폰트 및 글자색 설정
        Font font = new Font("Arial", Font.PLAIN, 16); // You can adjust the font settings here
        g2d.setFont(font);
        g2d.setColor(new Color(204, 153, 153));

        // 글자 작성
        FontRenderContext frc = g2d.getFontRenderContext();
        GlyphVector gv = font.createGlyphVector(frc, word);
        g2d.drawGlyphVector(gv, 10, 20); // Adjust the coordinates for text placement

        g2d.dispose();
        return image;
    }

    public static void main(String[] args) throws IOException {
        String word = "your_captcha_word"; // 원하는 문자열로 변경
        int imgWidth = 150;
        int imgHeight = 30;

        BufferedImage captchaImage = createCaptcha(word, imgWidth, imgHeight);
        File output = new File("captcha.png"); //실제 경로를 적어서 따로 설정해두된다.
        ImageIO.write(captchaImage, "png", output);
    }
}

메인 이미지 출처 : 사진: UnsplashNEOM  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.