Image processing delayed on Java

58 views Asked by At

I have a jframe with a button to crop image, and im using the Marvin libray to manipulate images. Whenever i clic the button the new cropped image is created in the folder after i close the jframe window. I have no idea why this is happening and how to make it work real time. Appreciate any help

Gui.java

      cropBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               System.out.println("Cropped successfully");
           
             ImageManipulator.cropImage(60, 32, 182, 62);
           }
        });

Crop method

 static MarvinImage cropImage(int x, int y, int width, int height) {
        MarvinImage image = MarvinImageIO.loadImage("image.jpeg");
        crop(image.clone(), image, x, y, width, height);
        MarvinImageIO.saveImage(image, String.format("cropped-image-%s.%s", dateFormat.format(new Date()), format));
        return image;
    }
   public static void crop(MarvinImage imageIn, MarvinImage imageOut, int x, int y, int width, int height) {
        x = Math.min(Math.max(x, 0), imageIn.getWidth());
        y = Math.min(Math.max(y, 0), imageIn.getHeight());
        if (x + width > imageIn.getWidth()) {
            width = imageIn.getWidth() - x;
        }

        if (y + height > imageIn.getHeight()) {
            height = imageIn.getHeight() - y;
        }

        crop = checkAndLoadImagePlugin(crop, "org.marvinproject.image.segmentation.crop");
        crop.setAttribute("x", x);
        crop.setAttribute("y", y);
        crop.setAttribute("width", width);
        crop.setAttribute("height", height);
        crop.process(imageIn, imageOut);
    }
1

There are 1 answers

11
thetechnician94 On

I'm not 100% certain, but I think your problem is that you are running your cropping function on the event dispatch thread.

Try giving it its own thread:

  cropBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               System.out.println("Cropped successfully");
               new Thread(new ImageThread()).start();
            }
        });

public class ImageThread implements Runnable{
   @Override
        public void run() {
            ImageManipulator.cropImage(60, 32, 182, 62);
         }
}