基本上,我所要做的就是使用JFileChooser从用户的计算机上打开位图图像,然后用一个简单的过滤器编辑个人像素。我希望能够像打开它一样保存图像,但在此之前,我需要弄清楚如何使用JFileChooser实际打开文件。我的问题是,我设置inputFile等于什么input.getSelectedFIle()是,这将工作,但它是在一个if语句。这就是说,我该如何解决这个问题,并且在if语句之外使用该文件?另外,是否有一种特殊的方式可以在应用过滤器后保存位图图像?Java JFileChooser来选择位图图像
这是我的代码;它可能包含了一些错误,由于我测试的东西来尝试解决问题:
import java.awt.Component;
import java.io.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
public class JavaImage
{
private static Component parent;
public static void main(String[] args) throws IOException
{
FileInputStream in;
//try catch around the image selection
try
{
JFileChooser input = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"BMP Images", "bmp");
input.setFileFilter(filter);
int returnVal = input.showOpenDialog(parent);
File inputFile = input.getSelectedFile();
if(returnVal == JFileChooser.APPROVE_OPTION) {
inputFile = input.getSelectedFile();
Scanner scan = new Scanner(inputFile);
}
new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream("output.bmp");
//user selected bitmap image file
in=FileInputStream(inputFile);
int i = 0;
int counter = 0;
//edits the actual pixels of the bitmap image
while((i==in.read())&&i!=-1) {
if (++counter>54) // skip past Bitmap headers
{
//use BGR format subpixels to process
int b =i; //stores blue byte
int g = in.read(); //read green bye
int r = in.read();//read red byte
//greyscale
int gray = (r+g+b)/3;
b=gray; g=gray; b=gray;
out.write(b);// output the blue byte
out.write(g);// output the green byte
i=r; //prep red byte for output
}
out.write(i);
}
in.close();
out.close();
}
//the error message if user enters a non bitmap file
catch (IOException ImageError)
{
JOptionPane.showConfirmDialog(null, "No such file");
}
}
}
为一体,=的FileInputStream(INPUTFILE)变化';''来in = new FileInputStream(inputFile);' – 2015-03-24 22:01:45
接下来请澄清一下这句话:''我的问题是我设置inputFile等于input.getSelectedFIle()的值,它可以工作,但它在if语句中“'。这是什么意思?为什么不把所有的东西放在if区块?为什么使用扫描仪来显示一个位图文件,这个文件显然不是文本文件。 – 2015-03-24 22:02:21
另外,只有在'returnVal == JFileChooser.APPROVE_OPTION'时调用'input.getSelectedFile()',而不是在测试之前。否则你陷入困境。 – 2015-03-24 22:08:37