Created
January 27, 2024 04:03
-
-
Save uphoon/bdad4aa424de0851da12643fca810abd to your computer and use it in GitHub Desktop.
Combine image and text with Base64 encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.*; | |
import java.awt.image.BufferedImage; | |
import java.io.ByteArrayOutputStream; | |
import javax.imageio.ImageIO; | |
import java.util.Base64; | |
public class ImageWithTextToBase64 { | |
public static void main(String[] args) { | |
String imagePath = "path/to/your/image.jpg"; | |
String textToAdd = "Your Text Here"; | |
try { | |
BufferedImage image = ImageIO.read(new File(imagePath)); | |
// Create a graphics context on the image | |
Graphics2D g2d = image.createGraphics(); | |
Font font = new Font("Arial", Font.BOLD, 36); | |
g2d.setFont(font); | |
g2d.setColor(Color.BLACK); | |
int textWidth = g2d.getFontMetrics().stringWidth(textToAdd); | |
int x = (image.getWidth() - textWidth) / 2; | |
int y = image.getHeight() / 2; | |
g2d.drawString(textToAdd, x, y); | |
g2d.dispose(); | |
// Convert the image to Base64 | |
ByteArrayOutputStream baos = new ByteArrayOutputStream(); | |
ImageIO.write(image, "jpg", baos); | |
byte[] imageBytes = baos.toByteArray(); | |
String base64Image = Base64.getEncoder().encodeToString(imageBytes); | |
// Print or use the Base64 encoded image as needed | |
System.out.println("Base64 Encoded Image:\n" + base64Image); | |
} catch (Exception e) { | |
System.out.println("Error: " + e.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment