Java scale image

Sephiroth_by_Wen_JR.jpg



Complete source code below will show you, how to scale an image in java using AffineTransform class. It will scale base on x and y axis.

************************************************************************
COMPLETE SOURCE CODE FOR : ScaleImage.java
************************************************************************


import java.awt.Image;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.BorderLayout;
import java.awt.Dimension;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.geom.AffineTransform;

import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.ImageIcon;

public class ScaleImage extends JPanel implements ActionListener
{
JScrollPane scrollBar;
JPanel panelB;
JButton button;
JTextField textFieldX;
JTextField textFieldY;
JFrame myWindow;
ImageIcon ii;

AffineTransform at=new AffineTransform();

Image myImage;

double x=0.3;
double y=0.3;

public ScaleImage()
{
//CHANGE Sephiroth_by_Wen_JR.jpg TO IMAGE THAT YOU WANT
myImage=Toolkit.getDefaultToolkit().getImage("Sephiroth_by_Wen_JR.jpg");

ii=new ImageIcon(myImage);

JLabel labelX=new JLabel("X : ");
JLabel labelY=new JLabel("Y : ");
textFieldX=new JTextField("0.3",10);
textFieldY=new JTextField("0.3",10);
button=new JButton("Refresh");

button.addActionListener(this);

panelB=new JPanel();
panelB.add(labelX);
panelB.add(textFieldX);
panelB.add(labelY);
panelB.add(textFieldY);
panelB.add(button);

setPreferredSize(new Dimension((int)(ii.getIconWidth()*x),(int)(ii.getIconHeight()*y)));
scrollBar=new JScrollPane(this);

myWindow=new JFrame("Scale image");
myWindow.getContentPane().setLayout(new BorderLayout());
myWindow.getContentPane().add(scrollBar,BorderLayout.CENTER);
myWindow.getContentPane().add(panelB,BorderLayout.SOUTH);
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setSize(500,500);
myWindow.setLocationRelativeTo(null);
myWindow.setVisible(true);
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{
x=Double.parseDouble(textFieldX.getText());
y=Double.parseDouble(textFieldY.getText());

setPreferredSize(new Dimension((int)(ii.getIconWidth()*x),(int)(ii.getIconHeight()*y)));

myWindow.repaint();
scrollBar.revalidate();
}
}

public void paint(Graphics g)
{
at.setToScale(x,y);
Graphics2D g2d=(Graphics2D)g;
g2d.drawImage(myImage,at,this);
}

public static void main(String[]args)
{
ScaleImage si=new ScaleImage();
}
}


************************************************************************
JUST COMPILE AND EXECUTE
Note : Make sure Sephiroth_by_Wen_JR.jpg locate at same location with this source file
************************************************************************