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

Discussão em 'Angular' iniciado por Tracy, Outubro 24, 2024.

  1. Tracy

    Tracy Guest

    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?

    Continue reading...

Compartilhe esta Página