Skip to content
Advertisement

Mirroring an Image in Java

Background info: I’ve made a program that uploads an image using JFileChooser and fills in the space of the JFrame. I then apply filters via buttons. Currently 3 of my 4 filters work, or all except my mirror one. It randomly (or I guess not so randomly as there’s always a reason, I just don’t know what I did) worked a couple times.

My Question: I’ve attempted following a tutorial but had to make slight changes so that I can save it to a new file via a button that has a JFile Chooser. Currently when I save it, it does not mirror however my other filters do what there supposed to with the same slight changes. What is wrong with my mirror logic? Any help is appreciated!

My code:

Global Variables:

JavaScript

Upload file:

JavaScript

Save File:

JavaScript

grayScale method that works:

JavaScript

Mirror method that doesn’t work:

JavaScript

GUI (For Reference):

My GUI

Advertisement

Answer

So, speculation, you start out by doing…

JavaScript

And you end by doing this…

JavaScript

But, getImg is still pointing to the source (unmodified) image. If you’re using this to display the result to the user, then you’re displaying the wrong image. Based on you other “filter” operations, you’re modifying the getImg directly.

Now, having said that, your code is, questionable, at best.

Let me explain…

JavaScript

How do you know selFile1 is not null or that it points to a valid File? You’ve done no checking here. Also, what’s the point of reading the file twice, especially when you do res = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); immediately after it?

This raises another question, what happens if the image loading fails? You carry on trying to use the getImg reference anyway, which may contain “dirty” data or worse, be null.

Instead, I might do something more like…

JavaScript

Now you could also isolate the write within a inner try-catch, but the point is try and do some preemptive checking to prevent known issues from crashing your code.

Oh, and you might find…

JavaScript

And much simpler way to mirror an image

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement