Код: Выделить всё
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);
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... -as-string