Scaling Shearing Translating and Rotating a drawn image

With this example will shall show you four fundamental graphical transformations that you should know when you try to construct you own custom graphical environment or develop simple graphics.

In short in order to perform Scaling, Shearing, Translation and Rotation to a drwan Image one should take the following steps:

  • Load an image from a source using Toolkit.getDefaultToolkit().getImagemethod
  • Use an ImageObserver to monitor the loading of the image. When the image is fully load the user will be notified
  • Create a class that extedns Component and override the paint method.
  • Use AffineTransform class and its methods scale, translate, shear, rotate to set up the transformations
  • Use AffineTransformOp class an its method filter to perform this transformations to the buffered Image
  • And simply paint the buffered image in a new Frame
Now let’s take a look at the code:
package com.javacodegeeks.snippets.desktop;

import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;

public class ManipulateImage {

  static Image image;

  public static void main(String[] args) {

// The image URL - change to where your image file is located!

String imageURL = "image.png";

// This call returns immediately and pixels are loaded in the background

image = Toolkit.getDefaultToolkit().getImage(imageURL);

// Create a frame

Frame frame = new Frame();

// Add a component with a custom paint method

frame.add(new CustomPaintComponent());

// Display the frame

int frameWidth = 300;

int frameHeight = 300;

frame.setSize(frameWidth, frameHeight);



  * To draw on the screen, it is first necessary to subclass a Component 
  * and override its paint() method. The paint() method is automatically called 
  * by the windowing system whenever component's area needs to be repainted.
  static class CustomPaintComponent extends Component {

public void paint(Graphics g) {

  // Retrieve the graphics context; this object is used to paint shapes

  Graphics2D g2d = (Graphics2D)g;

  AffineTransform affineTransform = new AffineTransform();

  double scalex = .5;

  double scaley = 1;

  affineTransform.scale(scalex, scaley);

  double shiftx = .1;

  double shifty = .3;

  affineTransform.shear(shiftx, shifty);

  double x = 50;

  double y = 50;

  affineTransform.translate(x, y);

  double radians = -Math.PI/4;


  g2d.drawImage(image, affineTransform, this);




This was an example on how to perform scaling, shearing translating and rotating a drawn image.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button