user3148226
user3148226

Reputation: 31

How do I draw a rectangle on an existing png image using java

I have png image which is saved in my local PC. I want to open(Load) this image and draw a rectangle on this image @ specified location (x, y, width, Height) using java. Can anybody help me to do this...

Equivalent C# code is below. I want a java version for the same


Image oriImage = // load from file
Rectangle rect = new Rectangle(0, 1824, 1080, 96);
Bitmap eleImg = new Bitmap(oriImage, (int)(oriImage.Width / rate), (int)(oriImage.Height / rate));

Graphics g = Graphics.FromImage(eleImg);
g.DrawRectangle(new Pen(Color.Red, 5), rect);

Upvotes: 2

Views: 10049

Answers (2)

Yiorgos
Yiorgos

Reputation: 131

Just a hint for anyone trying to implement this solution:

In order for the changes to be actually saved to the image, you need to add a few lines:

[...]
g2d.dispose();
try {
    ImageIO.write(img, "png", image_file);
} catch (Exception e) {
    System.out.println("[ERROR] Could not save image.");
}

where image_file = the file you opened (the same you used in ImageIO.read, presumably)

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347332

You make use of the 2D Graphics API

BufferedImage img = ImageIO.read(...);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.RED);
g2d.drawRect(0, 0, 100, 100);
g2d.dispose();

Take a look at

For more details

Upvotes: 8

Related Questions