UI出错,无法传递2个文本字段中的数据或用户在单击按钮压缩图像时选择的路径。
以下是代码:
// this is the button when clicked should compress the image
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
File imageFile = new File("myimage.jpg");
File compressedImageFile = new File("myimage_compressed.jpg");
try
{
InputStream is = new FileInputStream(imageFile);
OutputStream os = new FileOutputStream(compressedImageFile);
float quality = 0.5f;
// create a BufferedImage as the result of decoding the supplied InputStream
BufferedImage image = ImageIO.read(is);
// get all image writers for JPG format
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
if (!writers.hasNext())
throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
// compress to a given quality
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
// appends a complete image stream containing a single image and
//associated stream and image metadata and thumbnails to the output
writer.write(null, new IIOImage(image, null, null), param);
// close all streams
is.close();
os.close();
ios.close();
writer.dispose();
}
catch(IOException e)
{
System.out.println(e);
}
}
// this is the button for choosing an image file
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser=new JFileChooser();
FileNameExtensionFilter imgfilter=new FileNameExtensionFilter("Image files", "jpg");
chooser.setFileFilter(imgfilter);
chooser.showOpenDialog(null);
File f=chooser.getSelectedFile();
String filename=f.getAbsolutePath();
jTextField1.setText(filename);
}
// this is the button for choosing the destination folder for compressed image to be saved
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser=new JFileChooser();
FileNameExtensionFilter imgfilter=new FileNameExtensionFilter("Image files", "jpg");
chooser.setFileFilter(imgfilter);
chooser.showOpenDialog(null);
File f=chooser.getSelectedFile();
String filename=f.getAbsolutePath();
jTextField1.setText(filename);
}
在这里我有两个文本区域和两个按钮,一个按钮用于从m / c中选择图像,另一个按钮用于选择要保存图像的目标文件夹。
用于压缩图像文件的第三个按钮。
答案 0 :(得分:0)
您的代码
部分// this is the button for choosing an image file
和
部分// this is the button for choosing the destination folder for compressed image to be saved
完全相同,jButton6
应该更改,jtextfield1
应根据您的用户界面进行更改。
我会解决这个问题。
祝你好运