ここにこのコードがあります。メインメソッドを呼び出すときに、ユーザーが入力した画像ファイルを最初に表示してから、変更を適用します。私の最初の関数は grayscale() です。クリックすると、現在の画像のグレースケール バージョンが作成されるように、JMenuBar にグレースケール ボタンを用意しました。動作しますが、メソッドが適用された後、新しい画像を JFrame に表示できません。show(); を呼び出してみました。メソッド内ですが、元の画像が再び開かれます。グレースケール関数が機能していることはわかっていますが、結果の画像が表示されないだけです。作成後に image2 を表示するにはどうすればよいですか? 助けてくれてありがとう。
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
public class ImageEdit{
Container content;
static BufferedImage image;
BufferedImage image2;
public ImageEdit(String filename) {
File f = new File(filename);
//assume file is the image file
try {
image = ImageIO.read(f);
}
catch (IOException e) {
System.out.println("Invalid image file: " + filename);
System.exit(0);
}
}
public void show() {
final int width = image.getWidth();
final int height = image.getHeight();
JFrame frame = new JFrame("Edit Picture");
//set frame title, set it visible, etc
content = frame.getContentPane();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add the image to the frame
ImageIcon icon = new ImageIcon(image);
frame.setContentPane(new JLabel(icon));
frame.pack();
//add a menubar on the frame with a single option: saving the image
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenuItem saveAction = new JMenuItem("Save");
fileMenu.add(saveAction);
JMenuItem grayScale = new JMenuItem("Grayscale");
fileMenu.add(grayScale);
grayScale.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
grayscale(width, height);
}
});
//paint the frame
frame.setVisible(true);
}
public void grayscale(int width, int height) {
// create a grayscale image the same size
image2 = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
// convert the original colored image to grayscale
ColorConvertOp grayScale = new ColorConvertOp(
image.getColorModel().getColorSpace(),
image2.getColorModel().getColorSpace(),null);
grayScale.filter(image,image2);
show();
}
public static void main(String[] args) {
ImageEdit p = new ImageEdit(args[0]);
p.show();
}
}