Drawing Filled Rectangle over a BufferedImage

John Fox picture John Fox · Jul 24, 2012 · Viewed 16.5k times · Source

So I am attempting to create an application that can black-out sections of a survey that contains sensitive information. However I've run into a bit of a problem.

What I want to do is draw filled black rectangles over a BufferedImage given x, y, width, and height of desired region to black out, then write that new image back to my filesystem. Here's 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 whatever reason the image in the resource doesn't change after this code segment. Any ideas on what I'm doing wrong?

Answer

Gilbert Le Blanc picture Gilbert Le Blanc · Feb 4, 2020

I created a runnable example of your code, and it worked fine for me. I ran this code using Java 8.

Here's the altered image. I drew the black square on an image I had.

Altered Image

And here's the code I ran. I read the original image directly from my file system.

package com.ggl.testing;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageProcessing implements Runnable {

    public static void main(String[] args) {
        new ImageProcessing().run();
    }

    @Override
    public void run() {
        File imageFile = new File("C:\\Users\\Owner\\Pictures\\Saved Pictures\\Analog Clock Calendar.jpg");
        BufferedImage img;
        try {
            img = ImageIO.read(imageFile);
        } catch (IOException e1) {
            e1.printStackTrace();
            return;
        }

        Graphics2D graph = img.createGraphics();
        graph.setColor(Color.BLACK);
        graph.fill(new Rectangle(100, 100, 100, 100));
        graph.dispose();

        try {
            ImageIO.write(img, "jpg", 
                    new File("altered.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

My conclusion is that you either didn't read the image correctly, your x, y, width, and/or height were outside the limits of the image, or something else that I'm missing.