有效地以线程安全的方式使用BufferedImage?

时间:2019-04-27 10:36:20

标签: java swing thread-safety jpanel bufferedimage

假设我有这个简单的javax.swing.JPanel组件,仅用于显示BufferedImage

public class Scratch extends JPanel {
    private BufferedImage image;

    public Scratch(BufferedImage image) {
        this.image = image;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }
}

有时为此组件调用repaint()方法,指示Swing应该重绘它。但是,覆盖的paintComponent方法的使用由Swing内部处理。因此,我无法完全控制何时读取BufferedImage

现在让我们说,我对注入的BufferedImage执行了一些图像处理算法。这些通常有两种执行方式:

  • 读取图像的当前状态并使用setPixel进行更改。
  • 制作当前图像状态的副本(仅对RGB值矩阵感兴趣),通过读取原始矩阵并修改复制的矩阵,然后用副本替换原始矩阵来进行图像处理。以便将新状态而不是原始状态呈现到UI中。

两个问题:

  • 执行这两个过程的最有效(最快)的线程安全方法是什么?以获得最佳图像处理性能。

  • 从自定义线程在原始实例上调用setPixel是线程安全的,还是需要在Swing事件队列中调用它以避免与paintComponent的读取冲突?

也许使用BufferedImage并不是最好的方法,在这种情况下,您可能还会建议其他选项。但是我目前想重点关注BufferedImage的Swing。

1 个答案:

答案 0 :(得分:2)

是的,您永远不知道何时执行面板的repaint()。为了避免组件中出现任何不必要的视图,我将在后台线程中处理图像。这样,我不会在乎(当然我会在意)图像处理将花费多少时间。最后,在处理完图像后,我将其共享到GUI(回到EDT线程)。

值得一提的是,在Swing中用于在后台运行任务的工具是Swing Worker.,Swing worker可以让您在后台执行长时间的任务,然后在适当的线程中更新GUI(EDT-事件分配线程)。

我创建了一个示例,其中框架由图像和“过程图像”按钮组成。

按下按钮时,工作人员开始。它处理图像(在我的情况下将图像裁切为90%),最后用新图像“美观”,轻松地“刷新”视图。

此外,为了回答您的问题:

  

从以下位置在原始实例上调用setPixel是否是线程安全的:   一个自定义线程,还是需要在Swing事件队列中调用它   为了避免与paintComponent的读取冲突?

您不必担心在图像处理任务期间将使用哪种方法。只是,不要在那里更新Swing组件。在此过程之后进行更新。

预览:

enter image description here

源代码:

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

public class TestImage extends JFrame {
    private Scratch scratch;
    private JButton crop;

    public TestImage() {
        super("Process image");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().setLayout(new BorderLayout());
        try {
            BufferedImage img = loadImage();
            scratch = new Scratch(img);
            getContentPane().add(scratch, BorderLayout.CENTER);
        } catch (IOException e) {
            e.printStackTrace();
        }
        crop = new JButton("Process image");
        crop.addActionListener(e -> processImage());
        getContentPane().add(crop, BorderLayout.PAGE_END);
        setSize(500, 500);
        setLocationRelativeTo(null);
    }

    private void processImage() {
        crop.setEnabled(false);
        crop.setText("Processing image...");
        new ImageProcessorWorker(scratch, () -> {
            crop.setEnabled(true);
            crop.setText("Process image");
        }).execute();
    }

    private BufferedImage loadImage() throws IOException {
        File desktop = new File(System.getProperty("user.home"), "Desktop");
        File image = new File(desktop, "img.png");
        return ImageIO.read(image);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new TestImage().setVisible(true));
    }

    public static class Scratch extends JPanel implements ImageView {
        private static final long serialVersionUID = -5546688149216743458L;
        private BufferedImage image;

        public Scratch(BufferedImage image) {
            this.image = image;
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, null);
        }

        @Override
        public BufferedImage getImage() {
            return image;
        }

        @Override
        public void setImage(BufferedImage img) {
            this.image = img;
            repaint(); //repaint the view after image changes
        }
    }

    public static class ImageProcessorWorker extends SwingWorker<BufferedImage, Void> {
        private ImageView view;
        private Runnable restoreTask;

        public ImageProcessorWorker(ImageView v, Runnable restoreViewTask) {
            view = v;
            restoreTask = restoreViewTask;
        }

        @Override
        protected BufferedImage doInBackground() throws Exception {
            BufferedImage image = view.getImage();
            image = crop(image, 0.9d);
            Thread.sleep(5000); // Assume it takes 5 second to process
            return image;
        }

        /*
         * Taken from
         * https://stackoverflow.com/questions/50562388/how-to-crop-image-in-java
         */
        public BufferedImage crop(BufferedImage image, double amount) throws IOException {
            BufferedImage originalImage = image;
            int height = originalImage.getHeight();
            int width = originalImage.getWidth();

            int targetWidth = (int) (width * amount);
            int targetHeight = (int) (height * amount);
            // Coordinates of the image's middle
            int xc = (width - targetWidth) / 2;
            int yc = (height - targetHeight) / 2;

            // Crop
            BufferedImage croppedImage = originalImage.getSubimage(xc, yc, targetWidth, // widht
                    targetHeight // height
            );
            return croppedImage;
        }

        @Override
        protected void done() {
            try {
                BufferedImage processedImage = get();
                view.setImage(processedImage);
                if (restoreTask != null)
                    restoreTask.run();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            super.done();
        }

    }

    public static interface ImageView {
        BufferedImage getImage();

        void setImage(BufferedImage img);
    }
}