Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package view.external;import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics;import java.awt.Image;import java.beans.PropertyChangeEvent;import java.beans.PropertyChangeListener;import java.io.File;import javax.swing.ImageIcon;import javax.swing.JFileChooser;import javax.swing.JPanel;public class ImagePreview extends JPanel
- implements PropertyChangeListener{private int width,height;private final int SIZE=155;private ImageIcon imageIcon;private Color background;private Image image;public ImagePreview(){this.setPreferredSize(new Dimension(SIZE,-1));background=this.getBackground();}@Override
- public void propertyChange(PropertyChangeEvent evt){if(evt.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)){File file=(File)evt.getNewValue();if(file!=null){String path=file.getAbsolutePath();if(extensionIsAccepted(path)){imageIcon=new ImageIcon(path);image=imageIcon.getImage();scalePicture();this.repaint();}}}}@Override
- protected void paintComponent(Graphics g){int panelHeight=this.getHeight();g.setColor(background);g.fillRect(0,0,SIZE,panelHeight);g.drawImage(image,this.getWidth()/2-width/2+5,panelHeight/2-height/2,this);}
- private boolean extensionIsAccepted(String str){str=str.toLowerCase();return str.endsWith(".jpg")||str.endsWith(".jpeg")||str.endsWith(".png")||str.endsWith(".gif");}
- private void scalePicture(){width=image.getWidth(this);height=image.getHeight(this);double ratio=1.0;if(width>=height){ratio=(double)(SIZE-5)/width;width=SIZE-5;height=(int)(height*ratio);}else{if(this.getHeight()>150){ratio=(double)(SIZE-5)/height;height=SIZE-5;width=(int)(width*ratio);}else{int panelHeight=this.getHeight();ratio=(double)panelHeight/height;height=panelHeight;width=(int)(width*ratio);}}
- image=image.getScaledInstance(width,height,Image.SCALE_DEFAULT);}}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement