如何浏览图像在Java中设置Jlabel

时间:2019-06-05 06:01:06

标签: java

我尝试浏览图像并将其设置为Jlabel,但是。我得到了错误    BufferedImage thumbanail = Thumbnails.of(image).size(250,200).asBufferedImage();这行代码错误指示大小。 jLabel 7我已更改了变量名imagelabel,在此图像需要在浏览器后重新显示

enter image description here

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        JFileChooser ch = new JFileChooser();
        ch.showOpenDialog(null);
        File f = ch.getSelectedFile();
        String filename = f.getAbsolutePath();
        jTextField5.setText(filename);     

        try {
                File image = new File(filename);                  
                BufferedImage thumbanail = Thumbnails.of(image).size(250,200).asBufferedImage();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(thumbanail, "jpeg",os);
                InputStream is = new ByteArrayInputStream(os.toByteArray());
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                for(int readnum;(readnum = is.read(buf))!=-1;)
                {
                        bos.write(buf,0,readnum);
                }
                    ImageIcon viewimage = new ImageIcon(thumbanail);
                    imagelabel.setIcon(viewimage);           

        } catch (IOException ex) {
            Logger.getLogger(emploee.class.getName()).log(Level.SEVERE, null, ex);
        }

1 个答案:

答案 0 :(得分:1)

首先,您可以选择图片并调整其大小以填充JLabel并将其添加为ImageIcon。如果不缩放,图像将被裁剪。

  JFileChooser fc = new JFileChooser();
    if(fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){
        BufferedImage img = ImageIO.read(fc.getSelectedFile());
        ImageIcon imageIcon = new ImageIcon(new 
        ImageIcon(img).getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
        yourLabel.setIcon(imageIcon);
      }

这里20,20是您需要设置的图像的宽度和高度。