Drawing to a BufferedImage sometimes, but consistently, yields weird results

So on two occasions I’ve written two programs that do almost the exact same thing: search an image for pixels of a user-determined color and draw over them with another user-determined color.

So I get the image, then call createGraphics on it, then with two for() loops go over every pixel, and if

new Color(image.getRGB(x, y)).equals(userSubmittedColor1)

I draw over it like so

graphics.setColor(userSubmittedColor2);
graphics.fillRect(x, y, 1, 1);

Then I use ImageIO.write() to save the image as a PNG, appending “_recolored.png” to the original image’s file name.

Now in most cases it just works, but sometimes, the color is a completely different one from userSubmittedColor2, or the image isn’t altered at all. In these cases, no matter how often I re-try it, the color being drawn is reliably not the one being input by the user.

I have absolutely no idea what causes this. I’ve looked in the debugger and the color is alright.