creating an image using custom font for given font_size in java similar to python

41 views Asked by At

I am using getbbox(text) in pillow to generate image using custom font for given string.I want the same image to be generated using java . But the image size differs from python to java . Not looking for jython approaches. kindly suggest java wrapper for PIL I am using custom font (eg:source serif) to create an image in python using below code :

 def draw_image():
    text="hello"
    font_object = ImageFont.truetype("SourceSerifPro-Regular.ttf", size=32)
    x1, y1, x2, y2 = font_object.getbbox(text)
    print("x values : ",x1," ",x2," ",y1," ",y2)
    print("size : ", (x2-x1 )," ",(y2-y1))
    img = Image.new("L", (x2 - x1 + 1, y2 - y1 + 1), 0)
    ImageDraw.Draw(img).text((-x1, -y1), text, 255, font=font_object, stroke_width=0)
    image_array = np.array(img)

python output: x values : 0 72 6 31 size : 72 25

Java code:

public static BufferedImage createGrayImage()
            throws FileNotFoundException, FontFormatException, IOException {
                 text="hello"
                 font_size=32
                 fontFile="SourceSerifPro-Regular.ttf"                  Fontfont=Font.createFont(Font.TRUETYPE_FONT,FileInputStream(fontFile)).deriveFont(Font.PLAIN,
                font_size);
        FontRenderContext frc = new FontRenderContext(null, true, true);
        GlyphVector glyphVector = font.createGlyphVector(frc, text);
        Rectangle2D bounds = glyphVector.getPixelBounds(frc, 0, 0);

        int width = (int) bounds.getWidth() + 1;
        int height = (int) bounds.getHeight() + 1;
System.out.println(" x values : " + bounds.getMinX() + " " + bounds.getMaxX() + "  " + bounds.getMinY() +" "+ bounds.getMaxY() );
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.black);
        g2d.fillRect(0, 0, width, height);

        g2d.setFont(font);
        g2d.setColor(Color.white);

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.drawGlyphVector(glyphVector, (int) (-(bounds.getMinX())), (int) (-(bounds.getMinY())));
                System.out.println("size : " +image.getWidth()+" "+image.getHeight())
        return image;

    }

java output : x values : 0.0 71.0 -24.0 1.0 size : 71 25

i want the image to be exactly same as generated by python and need java code for that . Kindly help with java code for the same

0

There are 0 answers