Skip to content

Instantly share code, notes, and snippets.

@BobTheBuilderBot
Created October 17, 2012 10:49
Show Gist options
  • Select an option

  • Save BobTheBuilderBot/3904934 to your computer and use it in GitHub Desktop.

Select an option

Save BobTheBuilderBot/3904934 to your computer and use it in GitHub Desktop.
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImagePanel extends JPanel {
private BufferedImage image;
private boolean imageLoaded = false;
private double rotValue = 0;
private double scaleValue = 1;
public void loadImage(String imageFilename) {
try {
image = ImageIO.read(new File(imageFilename));
imageLoaded = true;
scaleValue = 1;
repaint();
} catch (IOException e) {
e.printStackTrace();
}
}
public void zoom(float zoom) {
scaleValue = zoom;
repaint();
}
public void rotate(int rot) {
rotValue = rot;
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(imageLoaded) {
draw(image, g);
}
}
private void draw(BufferedImage image, Graphics g) {
int width = (int) (image.getWidth() * scaleValue);
int height = (int) (image.getHeight() * scaleValue);
BufferedImage newImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D newImageGfx = newImage.createGraphics();
AffineTransform transform = new AffineTransform();
transform.rotate(Math.toRadians(rotValue), getWidth() / 2, getHeight() / 2);
newImageGfx.setTransform(transform);
int x = (getWidth() - width) / 2;
int y = (getHeight() - height) / 2;
newImageGfx.drawImage(image, x, y, width, height, null);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.drawImage(newImage, 0, 0, null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment