javaangularspringimagetext

How to draw text on an image in spring backend and return the output as string?


I want to draw text on image which retrieve from file system as url. The output should be string so I can pass to Angular frontend and display the image. Below is my code:

private String addTextToImage(String imagePath, String text, int x, int y) throws Exception {
        URL url = new URL(imagePath);
        // Fetch the image from the URL
        BufferedImage image = null;
        try {
            disableSSLCertificateChecking();
            image = ImageIO.read(url.openStream());
            // Continue processing
        } catch (Exception e) {
            
            logger.error("Error loading image from URL: " + imagePath, e);
            throw new Exception("Failed to load image", e);
        }
        // Get the graphics object from image
        Graphics2D g = (Graphics2D) image.getGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setFont(new Font("Arial", Font.BOLD, 30)); // Set font size and style
        g.setColor(Color.BLACK); // Set text color

        // Draw the text on the image
        g.drawString(text, x, y);
        g.dispose();

        // Save image to disk for debugging (optional)
        ImageIO.write(image, "png", new File("output_with_text.png"));

        // Convert the modified image to a byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] imageBytes = baos.toByteArray();

        // Encode the byte array to Base64 string
        return Base64.getEncoder().encodeToString(imageBytes);

    }

However the code seems not working, no image is displayed and when i navigate to the image url the image is broken, any idea?


Solution

  • Your code seems fine. It does generates the base64 of the image with your text.

    It could be how you are using the output of the api to show the image.

    Add the api data to an img tag with src attribute as "data:image/png;base64,image_data_from_api". The image should show up.

    Code below,

    <img src="data:image/png;base64,image_data_from_api" />