[ACCEPTED]-Zoom in and out of images in Java-zooming
Accepted answer
You can easily achieve this by using scale 6 transforms on the original image.
Assuming 5 your the current image width newImageWidth
, and the current 4 image height newImageHeight
, and the current zoom level 3 zoomLevel
, you can do the following:
int newImageWidth = imageWidth * zoomLevel;
int newImageHeight = imageHeight * zoomLevel;
BufferedImage resizedImage = new BufferedImage(newImageWidth , newImageHeight, imageType);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newImageWidth , newImageHeight , null);
g.dispose();
Now, replace 2 the original image, originalImage
, in your display area 1 by resizedImage
.
You can also use it as follows :
public class ImageLabel extends JLabel{
Image image;
int width, height;
public void paint(Graphics g) {
int x, y;
//this is to center the image
x = (this.getWidth() - width) < 0 ? 0 : (this.getWidth() - width);
y = (this.getHeight() - width) < 0 ? 0 : (this.getHeight() - width);
g.drawImage(image, x, y, width, height, null);
}
public void setDimensions(int width, int height) {
this.height = height;
this.width = width;
image = image.getScaledInstance(width, height, Image.SCALE_FAST);
Container parent = this.getParent();
if (parent != null) {
parent.repaint();
}
this.repaint();
}
}
Then you 3 can put it to your frame and with the method 2 that zooms with a zooming factor, for which 1 I used percent values.
public void zoomImage(int zoomLevel ){
int newWidth, newHeight, oldWidth, oldHeight;
ImagePreview ip = (ImagePreview) jLabel1;
oldWidth = ip.getImage().getWidth(null);
oldHeight = ip.getImage().getHeight(null);
newWidth = oldWidth * zoomLevel/100;
newHeight = oldHeight * zoomLevel/100;
ip.setDimensions(newHeight, newWidth);
}
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.