0

I have written a small code for simple resizing of any image on my system in java using SWING.

http://ideone.com/9vii2E

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;

class T extends JPanel implements ActionListener {
    /**
     * 
     */
    private static final long serialVersionUID = -2900955352094956729L;
    int x = 0;
    int flag = 0;
    BufferedImage b;
    Image z;
    JButton j, a, cl;
    JTextField ht, wdth;

    T() {
        j = new JButton("Hi");
        a = new JButton("Resizze");
        a.addActionListener(this);
        add(a);
        j.addActionListener(this);
        add(j);
        setBackground(Color.WHITE);

    }

    class tobi implements ActionListener {// for close button of second window
        public void actionPerformed(ActionEvent asd) {
            // if(x==1)
            {
                int gadda = 100, w = 100;
                gadda = Integer.parseInt(ht.getText());
                w = Integer.parseInt(wdth.getText());
                z = z.getScaledInstance(gadda, w, Image.SCALE_SMOOTH);
                setBackground(Color.BLACK);
                j.repaint();
                JButton ttr = (JButton) asd.getSource();
                Window qwe = SwingUtilities.windowForComponent(ttr);
                qwe.setVisible(false);
            }
        }

    }

    public void meth()// method to create second window
    {
        JFrame win = new JFrame();
        win.setTitle("resizze!!");
        win.setLayout(new FlowLayout());
        JLabel height = new JLabel("Height:");
        ht = new JTextField(20);

        JLabel width = new JLabel("Width:");
        wdth = new JTextField(20);
        JButton cl = new JButton("close");

        cl.addActionListener(new tobi());
        win.add(height);
        win.add(ht);
        win.add(width);
        win.add(wdth);
        win.add(cl);
        win.pack();
        win.setVisible(true);
    }

    public void paintComponent(Graphics g) {

        Graphics2D gt = (Graphics2D) g;
        super.paintComponent(g);
        if (x == 1)
            g.drawImage(z, 0, 0, null);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == j) {
            JFileChooser q = new JFileChooser();
            // q.setFileFilter(new
            // FileNameExtensionFilter("Image Files",ImageIO.getReaderFileSuffixes()));
            q.addChoosableFileFilter(new FileNameExtensionFilter("Image Files",
                    "jpg", "jpeg", "png"));
            int option = q.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                File f = q.getSelectedFile();
                try {
                    b = ImageIO.read(f);
                    z = b.getScaledInstance(100, 100, Image.SCALE_SMOOTH);
                } catch (IOException ae) {
                }
            }
            x = 1;
            repaint();
        }

        else if (e.getSource() == a) {
            meth();
        }

    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable(){
    public void run(){
    JFrame j = new JFrame();
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.setSize(500, 500);
        j.add(new T());
        j.setVisible(true);
    j.revalidate();
    j.repaint();

}
});
    }
}

I am asking user to upload the image file and then taking parameters height and width for resizing. After clicking on close button in second window,nothing happens(except for first few times),while the image on first window should be repainted. (Sorry for bad variable names and formatting)

  • you tell me clearly. i went through your code. but it gets width and height, then when we click close button, image resizes. – Kumaresan Perumal Oct 29 '15 at 11:52
  • I tried this code at my end and it is working as expected. I dont see a problem with this. Except you need to fix few of the null issues in your code using check for nulls. – Vivek Singh Oct 29 '15 at 11:55
  • it is responding but only some of the times – user3632784 Oct 29 '15 at 12:17
  • I guess you need to fix issues like handling null and restricting users on the control flow. Like before clicking the resizee button the user must go and select an image. Once the image is loaded then only user should be able to resize it. Again in the resize window, user must input values for resizing, if not then no code should execute in the background. – Vivek Singh Oct 29 '15 at 12:25
  • this is just a prototype basic version ... but it should respond to click .. and I am new to java.. I dont know how null handling can solve this issue – user3632784 Oct 29 '15 at 12:30
  • You must create and display GUI objects on the event thread; otherwise painting won't work properly. Your main() method is not doing that. – FredK Oct 29 '15 at 14:32
  • I didnt know about event thread.. but now I've edited the code..still not refreshing .. is there something more I need to do? or can you point me to some example? – user3632784 Oct 29 '15 at 15:08
  • You might want to have a look at [The Perils of Image.getScaledInstance()](https://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html) and [this example](http://stackoverflow.com/questions/11959758/java-maintaining-aspect-ratio-of-jpanel-background-image/11959928#11959928) and [this example](http://stackoverflow.com/questions/14115950/quality-of-image-after-resize-very-low-java/14116752#14116752) – MadProgrammer Oct 29 '15 at 21:37

1 Answers1

1

You have a whole bunch of issues, variable naming only been one of them...

g.drawImage(z, 0, 0, null); should be g.drawImage(z, 0, 0, this);, this ensures that if the image is still be processed for some reason, the component can respond to any of it's changes and update schedule new repaints of it's own accord

Don't ignore exceptions

try {
    b = ImageIO.read(f);
    z = b.getScaledInstance(100, 100, Image.SCALE_SMOOTH);
} catch (IOException ae) {

}

should be (at the very least)

try {
    b = ImageIO.read(f);
    z = b.getScaledInstance(100, 100, Image.SCALE_SMOOTH);
} catch (IOException ae) {
    ae.printStackTrace();
}

This will help you solve probable issues in your code.

I'd also change the above to

try {
    b = ImageIO.read(f);
    z = b;
} catch (IOException ae) {
    ae.printStackTrace();
}

so you are presented with the original image first (this is just my opinion), but since you don't have any real scaling properties at this point, it makes sense to me.

You're shadowing the cl variable, declaring it as a instance field, but re-declaring it again as a local variable in meth. I don't if this will be an issue, but you need to be aware of it.

z = z.getScaledInstance(gadda, w, Image.SCALE_SMOOTH); should be z = b.getScaledInstance(gadda, w, Image.SCALE_SMOOTH);. You want to scale from the source, otherwise you are going to have a lot of pixelation issues.

You also calling j.repaint(); which is just repainting the button, which is clearly not what you want to do, instead you should just be calling repaint() on the panel itself

You should also have a look at The Perils of Image.getScaledInstance() and this example and this example for examples of how you might produce better scaling operations

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I couldn't understand what's wrong with drawImage () – user3632784 Oct 30 '15 at 09:40
  • The last parameter to drawImage is an ImageObserver, which JComponent implements, this allows the component to monitor the image for changes (in the image data as its been loaded/processed) and schedule repaints itself. It's a good habit to pass this as the ImageObserver parameter – MadProgrammer Oct 30 '15 at 10:09
  • Sorry, copy and paste issue :P – MadProgrammer Oct 30 '15 at 10:10
  • I implemented some of your suggestions as well as added cropping ability...but now nothing is displayed in the window.. can you help me out [new_code](http://ideone.com/JRqS7R) – user3632784 Oct 30 '15 at 16:52
  • `Graphics#clip` isn't doing what you think or want it to do, instead use `BufferedImage#subImage` – MadProgrammer Oct 30 '15 at 23:12
  • I edited paintComponent and still not properly cropping [code](http://ideone.com/36Hr1K) – user3632784 Oct 31 '15 at 09:33