creative one2018
creative one2018

Reputation: 29

How to Browser the image set the Jlabel in java

i am tried to browser the image and set into Jlabel but. i got the error of BufferedImage thumbanail = Thumbnails.of(image).size(250,200).asBufferedImage(); this line of the code error indicate the size . jLabel 7 i have changed the variable name imagelabel here image needs to diplay after browser the image

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);
        }

Upvotes: 0

Views: 47

Answers (1)

sudesh regmi
sudesh regmi

Reputation: 546

First, you can choose the picture and resize that to fill the JLabel and add to it as ImageIcon. if you don't scale the image will be cropped.

  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);
      }

Here 20,20 are width and height of image you need to set.

Upvotes: 1

Related Questions