Creating an Image Placeholder in Java
In this example, We will show simple program about, How to create an Image Placeholder in Java. The example program has been tested and shared in the same post.
#PlaceholderEngine.java
package com.dineshkrish; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * * @author Dinesh Krishnan * */ public class PlaceholderEngine { public void render(int width, int height, File file) { BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // setting all properties for an image. Graphics graphics = img.getGraphics(); graphics.setColor(Color.LIGHT_GRAY); graphics.fillRect(0, 0, width, height); graphics.setColor(Color.BLACK); graphics.setFont(getFont()); // drawing the string on image drawString(graphics, width + " x " + height, width, 0, height / 2 + 5); try { // creating the image ImageIO.write(img, "PNG", file); } catch (IOException e) { System.out.println(e.getMessage()); } } private Font getFont() { return new Font("Arial Black", Font.ITALIC, 30); } private void drawString(Graphics graphics, String s, int width, int XPos, int YPos) { int stringLen = (int) graphics.getFontMetrics().getStringBounds(s, graphics).getWidth(); int start = width / 2 - stringLen / 2; graphics.drawString(s, start + XPos, YPos); } }
#ImagePlaceholder.java
package com.dineshkrish; import java.io.File; /** * * @author Dinesh Krishnan * */ public class ImagePlaceholder { public static void main(String[] args) { int width = 350; int height = 350; File file = new File("image.png"); PlaceholderEngine engine = new PlaceholderEngine(); engine.render(width, height, file); System.out.println("Image created successfully..."); } }
Output
References
1. ImageIO Example
2. Image Width and Height
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet