Drawing a Filled Rectangle Over a BufferedImage

So, I'm trying to create an application that can clip polling sections containing sensitive information. However, I ran into some problem.

What I want to do is draw the filled black rectangles above the BufferedImage given x, y, width and height of the desired area to darken, and then write this new image back to my file system. Here is my code.

File imageFile = new File("images/template.jpg"); BufferedImage img = ImageIO.read(imageFile); Graphics2D graph = img.createGraphics(); graph.setColor(Color.BLACK); graph.fill(new Rectangle(x, y, width, height)); graph.dispose(); ImageIO.write(img, "jpg", new File("images/template.jpg")); 

For any reason, the image in the resource does not change after this code segment. Any ideas on what I'm doing wrong?

+13
java bufferedimage graphics2d
source share
4 answers

Make sure your x, y and width, height really fit in the image. You are probably drawing somewhere outside the borders of the image. A step in debug mode to check for println () variables, etc.

0
source share

I know this is an old question, but maybe it can be useful to someone, I think you are using this

 graph.drawImage(x,y,width,height); //First you draw the image graph.setColor(Color.black); //Then set the color to black graph.fillRect(img.getX(), img.getY(), img.getWidth(), img.getHeight());// Finally draw a black rectangle on it 

By the way, it's hard to find a solution without code. Hope this will be helpful.

-one
source share

It's very late, but you save the image, not the graph you create. I think it should be BufferedImage again to save

-one
source share

You only need to replace this line:

 Graphics2D graph = img.createGraphics(); 

with this:

 Graphics2D graph = img.getGraphics(); 
-2
source share

All Articles