Toggle Theme Editor
Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate Charcoal

Enlargement Or Reduction Of Image With Java F X And Java Swing

Discussion in 'Java Update' started by Joe, 14/9/19.

  1. Joe

    Joe Thành viên VIP

    Hi

    Today I show you how to reduce or to enlarge an image (jpg, png, bmp or gif) and to save it as a new imaging file. The resizing technique is relatively simple if you work with BufferedImage, ImageIO, Graphics2D and SwingFXUtils. To do that you have to analyze the structure of an image. An Image has usually this following structure:

    - the coding technique (jpg, png, bmp or gif)
    - the size (width and length)
    - the IO specific operation

    To access an Image it's more convenient to work with BufferedImage to store the Image data (or pixels).
    PHP:
    BufferedImage bImage ImageIO.read(imageFile);
    With the buffered Image it's now possible to extract the Image width and length

    In JavaFX:
    PHP:
    Image image SwingFXUtils.toFXImage(bImagenull);
    double height image.getHeight();
    double width image.getWidth();
    Or in Java SWING:
    PHP:
    ImageIcon image = new ImageIcon(bImage);
    int height image.getIconHeight();
    int width image.getIconWidth();
    As you see, the dimensional size of JavaFX is more precise than the size of Java SWING: double versus int. With the known dimension Width and Length we can define any ratio and apply it to a new image for either an enlargement or a reduction.
    PHP:
    // new dimensional size
    int w = (int)(ratio width);
    int h = (int)(ration height);
    BufferedImage newBufImg = new BufferedImage(whBufferedImage.TYPE_INT_RGB);
    java.awt.Graphics2D graphics2D newBufImg.createGraphics();
    graphics2D.setBackground(java.awt.Color.WHITE);
    graphics2D.setPaint(java.awt.Color.WHITE);
    graphics2D.fillRect(00wh);
    graphics2D.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION,
                                
    java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(bImage00whnull);
    With the new BufferedImage newBufImg it's possible to create (or save) the enlarged or reduced image file with the same or different suffix sfx which could be .jpg, .png, .bmp or .gif.
    PHP:
    javax.imageio.ImageIO.write(newBufImgsfx, new File(fName)); // create and save BufferedImage
    EXAMPLES
    I show you hereunder 2 examples: JfxResizer and SwingResizer. Both resizers are similarly implemented. Both work with

    - slider to create a defined ratio (or scale)
    - FileChooser and URL for uploading/downloading an image from a local disk or from the Web.

    JfxResizer is also implemented with an external CSS-file (Cascading Style Sheets) to individualize the appearance and can be downloaded from HERE (see bottom.)
    [​IMG]
    The css file joe.css is as following:
    PHP:
    .root {
      -
    fx-font-size11pt;
      -
    fx-basesilver;
    }
    .
    button {
        -
    fx-background-color:
            
    linear-gradient(#f0ff35, #a9ff00),
            
    radial-gradient(center 50% -40%, radius 200%, #b8ee36 45%, #80c800 50%);
        
    -fx-background-radius65;
        -
    fx-background-insets01;
        -
    fx-effectdropshadowthree-pass-box rgba(0,0,0,0.4) , 50.0 );
        -
    fx-text-fill#395306;
    }
    .
    button:hover {
      -
    fx-background-colorbisque;
    }
    .
    label {
        -
    fx-font-size14px;
        -
    fx-font-weightbold;
        -
    fx-text-fill#333333;
        
    -fx-effectdropshadowgaussian rgba(255,255,255,0.5) , 0,0,0,);
    }
    /* slider thumb */
    .slider .thumb {
        -
    fx-background-color:
            
    linear-gradient(#f0ff35, #a9ff00),
            
    radial-gradient(center 50% -40%, radius 200%, #b8ee36 45%, #80c800 50%);
        
    -fx-background-radius65;
        -
    fx-background-insets01;
        -
    fx-effectdropshadowthree-pass-box rgba(0,0,0,0.4) , 50.0 );
        -
    fx-text-fill#395306;
    }
    /*
    CSS for the dialog
    */
    .joe {
        -
    fx-background-colordarkgray;
    }
    .
    joe > *.button-bar > *.container {
       -
    fx-background-colorsilver;
    }
    .
    joe .button {
        -
    fx-background-color:
            
    linear-gradient(#f0ff35, #a9ff00),
            
    radial-gradient(center 50% -40%, radius 200%, #b8ee36 45%, #80c800 50%);
        
    -fx-background-radius65;
        -
    fx-background-insets01;
        -
    fx-effectdropshadowthree-pass-box rgba(0,0,0,0.4) , 50.0 );
        -
    fx-text-fill#395306;
        
    -fx-font-size11pt;
    }
    .
    joe .button:hover {
      -
    fx-background-colorbisque;
    }
    .
    joe .textfield {
      -
    fx-background-colorlightgray;
    }
    .
    joe > *.label.content {
        -
    fx-font-size13px;
        -
    fx-font-weightbold;
        -
    fx-text-fillblue;
    }
    .
    joe:header *.header-panel{
        -
    fx-background-colorsilver;
    }
    .
    joe:header *.header-panel *.label {
        -
    fx-font-size13px;
        -
    fx-font-weightbold;
        -
    fx-text-filldarkblue;
        -
    fx-fill#292929;
    }
    SwingResizer is styled with NimbusLookAndFeel and works with the CopyPasteListener.
    PHP:
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import javax.swing.filechooser.FileNameExtensionFilter;
    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    import java.net.*;
    import java.io.*;
    public class 
    SwingResizer extends JFrame 
      public 
    SwingResizer( ) {
        
    setTitle("Resizing Image in JAVA SWING");
      
        
    JButton imgView = new JButton();
     
        
    JLabel lab = new JLabel("Scaling Ratio: 1.0 (or 100%)");
      
        
    JSlider slider = new JSlider(0501);
        
    slider.setMinorTickSpacing(1);
        
    slider.setPaintTicks(true);     
        
    slider.setPaintLabels(true);
        
    Hashtable<IntegerJLabelpos = new Hashtable<IntegerJLabel>();
        
    pos.put(0, new JLabel("0"));
        
    pos.put(10, new JLabel("1.00"));
        
    pos.put(20, new JLabel("2.00"));
        
    pos.put(30, new JLabel("3.00"));
        
    pos.put(40, new JLabel("4.00"));
        
    pos.put(50, new JLabel("5.00"));
        
    slider.setLabelTable(pos);
        
    slider.addChangeListener(-> {
          
    scale = ((double)((JSlider)e.getSource()).getValue())/10;
          
    lab.setText(String.format("Scaling Ratio: %.2f (or %.2f%%)",scalescale*100));
          if (
    old != scale && scale && bImage != null) {
            
    old scale;
            
    int w = (int)(scale width);
            
    int h = (int)(scale height);
            
    bImg = new BufferedImage(whBufferedImage.TYPE_INT_RGB);
            
    java.awt.Graphics2D graphics2D bImg.createGraphics();
            
    graphics2D.setBackground(Color.WHITE);
            
    graphics2D.setPaint(Color.WHITE);
            
    graphics2D.fillRect(00wh);
            
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                        
    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            
    graphics2D.drawImage(bImage00whnull);
            
    imgView.setIcon(new ImageIcon(bImg));
          }
        });
        
    JButton DOWN = new JButton("DOWNLOAD");
        
    DOWN.addActionListener(-> {
          
    String link getText("WebLink:");
          if (
    link != null) try { // download the image
            
    bImage ImageIO.read(new java.net.URL(link));
            
    int p link.lastIndexOf(".");
            
    sfx = (0)? "jpg":link.substring(p+1);
            
    slider.setValue(10);
            
    setView(imgView);
          } catch (
    Exception ex) {
            
    JOptionPane.showMessageDialog(jf,"Download problems","Alert",JOptionPane.WARNING_MESSAGE); 
          }
        });
        
    JButton UP = new JButton("UPLOAD");
        
    UP.addActionListener(-> {
          
    JFileChooser fChooser = new JFileChooser();
          
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image",
                                                                       
    "jpg""JPG",
                                                                       
    "png""PNG",
                                                                       
    "bmp""BMP",
                                                                       
    "gif""GIF");
          
    fChooser.setFileFilter(filter);
          if (
    fChooser.showOpenDialog(jf) == JFileChooser.APPROVE_OPTION) {
            
    slider.setValue(10);
            
    File file fChooser.getSelectedFile();
            
    String fileName file.getName();
            
    lab.setText("Scaling Ratio: 1.0 (or 100%)");
            
    sfx fileName.substring(fileName.lastIndexOf(".")+1);
            try {
              
    bImage ImageIO.read(file);
              
    setView(imgView);
            } catch (
    Exception ex) {
              
    JOptionPane.showMessageDialog(jf,"Upload problems","Alert",JOptionPane.WARNING_MESSAGE); 
            }
          }
        });
        
    JButton CPY = new JButton("SAVE AS");
        
    CPY.addActionListener(-> {
          try {
            
    String fName getText("Save to:");
            if (
    fName != null && bImg != null) {
              
    javax.imageio.ImageIO.write(bImgsfx, new File(fName));
            }
          } catch (
    Exception ex) {
            
    JOptionPane.showMessageDialog(jf,"Resizing problems","Alert",JOptionPane.WARNING_MESSAGE);
          }
        });
        
    //
        
    setLayout(null);
        
    // x, y, width, height
        
    imgView.setBounds(55985500);
        
    lab.setBounds(40051020030);
        
    slider.setBounds(552598560);
        
    DOWN.setBounds(25058515030);
        
    UP.setBounds(41058515030);
        
    CPY.setBounds(57058515030);
        
    add(imgView);
        
    add(lab);
        
    add(slider);
        
    add(DOWN);
        
    add(UP);
        
    add(CPY);
        
    //
        
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    setResizable(false);
        
    setSize(1010670);
        
    setVisible(true);
        
    jf this;
      }
      
    //
      
    public static void main(String... argsthrows Exception {
        
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        new 
    SwingResizer( ); 
      }
      
    // TextDialog-----------------------------------------------------------------
      
    private String getText(String cTxt) {
        
    JDialog dia = new JDialog(jftrue);
        
    dia.setTitle("SWING Resizer");
        
    JLabel lab = new JLabel(cTxt);
        
    JTextField inp = new JTextField(32);
        
    inp.addMouseListener(new CopyPasteListener(inp));
        
    inp.addActionListener(-> {
          
    txt inp.getText();
          if (
    txt != null && txt.isEmpty()) txt null;
          
    dia.dispose();
        });
        
    JPanel p = new JPanel();
        
    p.add(lab);
        
    p.add(inp);
        
    dia.add(p);
        
    dia.pack();
        
    dia.setLocationRelativeTo(jf);
        
    dia.setVisible(true);
        return 
    txt;
      }
      
    // set ImageView
      
    private void setView(JButton iv) {
        
    ImageIcon image = new ImageIcon(bImage);
        
    height image.getIconHeight();
        
    width image.getIconWidth();
        
    iv.setIcon(image);
        
    iv.revalidate();
        
    bImg bImage;
        
    scale 1;
        
    old 0;
      }
      private 
    JFrame jf;
      private 
    String sfxtxt;
      private 
    BufferedImage bImagebImg;
      private 
    double oldscalewidthheight;
    }
    [​IMG]
     

    Attached Files:

    Last edited: 15/9/19
    tranhuyvc likes this.

Chia sẻ trang này

Loading...