2
我在這裏有這個代碼。我希望它在調用main方法時首先顯示用戶輸入的圖像文件,然後對其應用更改。我的第一個功能是灰度()。我在JMenuBar中提供了一個灰度按鈕,當點擊它時,它會創建當前圖像的灰度版本。它可以工作,但是在應用該方法後,我無法在JFrame中顯示新圖像。我試過調用show();在方法內,但是隻是再次打開原始圖像。我知道灰度函數正在完成它的工作,它只是不顯示結果後的圖像。如何在創建image2後顯示它?謝謝您的幫助。更改ImageIcon顯示在JFrame中
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();
}
}
爲了比較,有一個工作實施例中(這裏)(http://stackoverflow.com/questions/7708204/set-color-as-int-value-for-use-in-setrgbint- X-INT-Y-INT-RGB-方法的Java/7708521#7708521)。 – trashgod
@trashgod我認爲該來源看起來很熟悉,甚至在查看其中的其他問題沒有顯示爲「已訪問」之前檢查了用戶配置文件。我忘了我正在翻轉32和64位操作系統'並使用新的瀏覽器。 :P –
爲了儘快提供更好的幫助,請發佈[SSCCE](http://pscode.org/sscce.html)。另外,請在代碼中生成圖像,就像我在答案中所做的那樣。順便說一句 - 我刪除了我剛纔提出的一個早期評論,我相信我已經提到了SSCCE的(偉大的,美妙的)概念。傻我。 –