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

问题描述 投票:-1回答:1

假设我有这个简单的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。

java swing thread-safety jpanel bufferedimage
1个回答
2
投票

你是对的,你永远不知道小组的repaint()何时会被执行。为了避免组件中的任何非想要的视图,我将在后台线程中处理图像。这样,我不会那么在乎(当然我会)图像处理需要多长时间。最后,在处理完图像后,我会将其分享给GUI(返回EDT线程)。

值得一提的是,在Swing中在后台运行任务的工具是一个Swing Worker.。一个swing工作者将允许你在后台执行长时间的任务,然后在适当的线程中更新GUI(EDT - 事件调度线程)。

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

按下按钮时,工作人员启动。它处理图像(在我的情况下,它将图像裁剪为90%),最后用新图像“刷新”视图,非常简单。

另外,为了回答你的问题:

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

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

预习:

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.