# Applying Affine Transformation to Images

• Print
This chapter is from the book

## Rotation, Flip, and Shear

Now that we have described the pan and zoom features in detail, it's time to look at other manipulation functions, which include rotate, flip, and shear. For the sake of convenience, instead of building individual interfaces for each of these functions, we'll build a common interface called GeomManipController for all of them. Again, we'll use the same design pattern we used for scroll and zoom. As mentioned earlier, with this design pattern the GUI is separated from control logic. Let's look at the manipulation operations one by one.

### Rotation

Rotation may not be used as frequently as pan and zoom. Nevertheless, it is important to have it in your image viewer. Typically, rotation is performed around the midpoint of the image, but our interface can provide a method that specifies the rotation center. First, let's specify the get and set methods for the rotation angle property:

• public double getRotationAngle();

• public void setRotationAngle(double theta);

Here are the methods that perform rotation:

• public void rotate(double theta);

• public void rotate(double theta, int rotCenterX, int rotCenterY);

The first method rotates the image around the midpoint of the image. The second one rotates the image around a point specified by the input parameters.

### Flip

We discussed the fundamentals of flip in Chapter 4. The method for flipping an image at any position or at any state is

• public void flip(int flipMode)

The flipMode parameter can be any one of the four values defined in the FlipMode class (see Chapter 6).

### Shear

Just as we specified the magFactor property for the scaling operation, for shear we'll specify the shearFactor property. The get and set methods for this property are

• public double getShearFactor();

• public void setShearFactor(double shear);

The method for shearing an image at any stage of the manipulation is

• public void shear(double shx, double shy);

The shx and shy parameters are the shear factors in the x and y directions, respectively.

### Implementing Rotation, Flip, and Shear

Let's develop the GeomManip class in a manner similar to what we did for pan and zoom. We'll build the controller class first and then the GUI class. Here are the two classes:

1. GeomManip. This class implements the GeomManipController interface.

2. ManipUI. This class implements the slider interfaces for adjusting the rotate and shear values.

Figure 7.13 shows the model-view-controller architecture for the rotation and shear features, which resembles the design for scroll and for zoom. Listing 7.16 shows the code for GeomManip.

FIGURE 7.13 The data flow for rotation and shear

#### LISTING 7.16 The GeomManip class

```package com.vistech.imageviewer;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;

public class GeomManip implements GeomManipController {
protected AffineTransform atx = new AffineTransform();
// Rotation variables
protected double rotationAngle = 0.0;
protected boolean rotateOn = true;
protected int rotationCenterX = 0;
protected int rotationCenterY = 0;
// Shear variables
protected boolean shearOn = true;
protected double shearFactor = 0.0;
protected double shearX =0.0, shearY=0.0;
protected ImageManipulator imageCanvas;
protected int flipMode = 0;

public GeomManip(){}
public GeomManip(ImageManipulator imageCanvas){ this.imageCanvas = imageCanvas;}

public void setImageManipulator(ImageManipulator imageCanvas){
this.imageCanvas = imageCanvas;
}

public synchronized void setFlipMode(int mode){
if(mode == flipMode) return;
int oldmode = flipMode;
flipMode = mode;
}

public int getFlipMode(){ return flipMode;}

public void setShearFactor(double shearFactor){
this.shearFactor = shearFactor;
imageCanvas.setShearFactor(shearFactor);
}
public double getShearFactor(){ return shearFactor;}

public double getShearFactorX(){ return shearX;}
public double getShearFactorY(){return shearY;}

public void setRotationAngle(double rotationAngle){
this.rotationAngle = rotationAngle;
imageCanvas.setRotationAngle(rotationAngle);
}

public double getRotationAngle(){ return rotationAngle;}

public void rotate(double theta){
double ang = this.rotationAngle -theta;
Dimension dim = imageCanvas.getImageSize();
int wid = dim.width;
int ht = dim.height;
setRotationAngle(theta);
atx = imageCanvas.getTransform();
atx.rotate(ang, wid/2, ht/2);
imageCanvas.applyTransform(atx);
}

public void rotate(double theta, int rotCenterX, int rotCenterY){
double ang = this.rotationAngle -theta;
setRotationAngle(theta);
atx = imageCanvas.getTransform();
atx.rotate(ang, rotCenterX, rotCenterY);
imageCanvas.applyTransform(atx);
}

public void resetAndRotate(double theta) {
BufferedImage image = imageCanvas.getOffScreenImage();
int wid = image.getWidth();
int ht = image.getHeight();
setRotationAngle(theta);
atx.setToRotation(theta, wid/2, ht/2);
imageCanvas.applyTransform(atx);
}

public void shear(double shx, double shy){
double shxIncr = shearX -shx;
double shyIncr = shearY -shy;
setShearFactor(shx);
this.shearX = shx;
this.shearY = shy;
atx = imageCanvas.getTransform();
atx.shear(shxIncr, shyIncr);
imageCanvas.applyTransform(atx);
}

public void shearIncr(double shxIncr, double shyIncr){
shearX += shxIncr;
shearY += shyIncr;
setShearFactor(shearX);
atx.shear(shxIncr, shyIncr);
imageCanvas.applyTransform(atx);
}

public void resetAndShear(double shx, double shy){
shearX =shx; shearY = shy;
atx.setToShear(shx,shy);
setShearFactor(shearX);
imageCanvas.applyTransform(atx);
}

public static AffineTransform createFlipTransform(int mode,
int imageWid,
int imageHt){
AffineTransform at = new AffineTransform();
switch(mode){
case FlipMode.NORMAL:
break;
case FlipMode.TOP_BOTTOM:
at = new AffineTransform(new double[] {1.0,0.0,0.0,-1.0});
at.translate(0.0, -imageHt);
break;
case FlipMode.LEFT_RIGHT :
at = new AffineTransform(new double[] {-1.0,0.0,0.0,1.0});
at.translate(-imageWid, 0.0);
break;
case FlipMode.TOP_BOTTOM_LEFT_RIGHT:
at = new AffineTransform(new double[] {-1.0,0.0,0.0,-1.0});
at.translate(-imageWid, -imageHt);
break;
default:
}
return at;
}

public void flip(int mode){
Dimension dim = imageCanvas.getImageSize();
int wid = dim.width;
int ht = dim.height;
AffineTransform flipTx = createFlipTransform(mode,wid,ht);
atx = imageCanvas.getTransform();
atx.concatenate(flipTx);
imageCanvas.applyTransform(atx);
}

public void resetAndFlip(int mode){
atx = new AffineTransform();
flip(mode);
}

public void resetManipulation(){
shearX = 0.0; shearY = 0.0;
rotationAngle = 0.0;
atx = new AffineTransform();
}
}```

Typically, images are rotated about their midpoint. In some situations, however, an image can be rotated around any arbitrary point. The rotate() methods in the GeomManip class meet both of these requirements.

The rotate(theta) method rotates the image about its midpoint, irrespective of where the image is positioned in the viewport. The input parameter theta is the angle of rotation from the original position of the image. When this method is called, the image might have been rotated already. This method therefore computes the difference between current rotation angle and the input. Then it gets the midpoint of the current image on the canvas. It then calls the rotate() method of the AffineTransform class with the difference in angles and the center point of the image as its inputs.

The rotate(theta, rotCenterX, rotCenterY) method rotates the image about any arbitrary point. The resetAndRotate() method implements absolute rotation about the midpoint. The setToRotation() method resets atx and rotates it by a fixed amount.

The shear methods are similar to the scale and rotate methods.

The AffineTransform class doesn't have an explicit flip transformation. We discussed how to implement flip in the preceding section and defined a method called createFlipTransform(). The flip() method uses createFlipTransform() to flip the image at any stage of image manipulation. Note that here we use the concatenate() method to concatenate the flip transformation to the current transformation atx. The resetAndFlip() method resets the current transformation and flips the image in the direction specified in the input.

### User Interface for Rotation and Shear

Implementing rotation and shear is straightforward. We can directly use the transformation methods for rotation and shear in the GeomManip class. But first we need a GUI to operate on the GeomManip class. Figure 7.14 shows a screen shot of a panel that has two tabs: Rotate and Shear. To launch this panel, select the Rotate/Shear option in the Manipulate menu. You can either use the slider or enter a value in the text field. Notice that in the Rotate tab, the angles vary from –360 to +360, thereby enabling rotation in the clockwise or counterclockwise direction. When you move the slider, the text field reflects the slider's current value.

FIGURE 7.14 The Rotate and Shear panel

We'll provide only some code snippets because implementing the GUI involves a large chunk of code. Listing 7.17 shows the code for ManipUI.

#### LISTING 7.17 The ManipUI class

```public class ManipUI extends JPanel{
protected JTabbedPane jtp;
protected int startValue = 0;
protected int minValue = -360, maxValue = 360;
protected JTextField rotateValueField;
protected double rotateValue = 0.0;
protected int rotateStartValue = 0;
protected JSlider rotateSlider;

protected int shearMinValue = -200;
protected int shearMaxValue = 200;
protected JTextField shearValueField;
protected int shearValue = 0;
protected int shearStartValue = 0;
protected JSlider shearSlider;
protected GeomManipController imageViewer;

public ManipUI(GeomManipController manip) {
imageViewer = manip;
createUI();
}

private void createUI() {
JPanel rpanel = createRotatePanel();
JPanel spanel = createShearPanel();
jtp = new JTabbedPane();
}

protected JPanel createRotatePanel() {
JButton resetButton = new JButton("Reset Rotate");
new ActionListener() {
public void actionPerformed(ActionEvent e){
rotateSlider.setValue(rotateStartValue);
rotateValueField.setText((new Double(rotateStartValue)).toString());
imageViewer.rotate(0.0);
}
}
);

rotateValueField = new JTextField(5);
new ActionListener() {
public void actionPerformed(ActionEvent e){
try {
String str = ((JTextField)e.getSource()).getText();
rotateValue = (Double.valueOf(str)).doubleValue();

rotateSlider.setValue((int)rotateValue);
imageViewer.rotate(rotateValue*(Math.PI/180.0));
} catch (Exception e1){}
}
}
);

rotateValueField.setText(Integer.toString(rotateStartValue));
JLabel rotateLabel = new JLabel("Rotate");

rotateSlider = new JSlider(minValue,maxValue,startValue);
rotateSlider.setMajorTickSpacing(120);
rotateSlider.setMinorTickSpacing(12);
rotateSlider.setExtent(12);
rotateSlider.setPaintTicks(true);
rotateSlider.setPaintLabels(true);

new ChangeListener() {
public void stateChanged(ChangeEvent e){
double rotateValueOld = rotateValue;
rotateValue = ((JSlider)(e.getSource())).getValue();
imageViewer.rotate(rotateValue*(Math.PI/180.0));
rotateValueField.setText(Integer.toString((int)rotateValue));
}
}
);

JPanel rotatepan = new JPanel();
// Grid layout
return rotatepan;
}

protected JPanel createShearPanel() {

// Code similar to createRotatePanel
}

public void resetManipulation(){
shearSlider.setValue((int)(shearStartValue*100));
shearValueField.setText(Double.toString(shearStartValue));
rotateValueField.setText(Integer.toString((int)rotateStartValue));
rotateSlider.setValue((int)rotateStartValue);
}
}```

Most of the code in Listing 7.17 is self-explanatory. The rotateSlider event–handling method calls the rotate() method with the current rotateSlider value. Likewise, the shearSlider event–handling method calls the shear() method with the current shearSlider value.

The code snippets that follow, which are from the ImageManip2D application, show how to use the GeomManip and ManipUI classes in an application:

```ImageManipulator viewer = new ImageCanvas2D();
GeomManipController manip = new GeomManip(viewer);

new ActionListener() {
public void actionPerformed(ActionEvent e){
if(manipFrame == null) {
manipFrame = new JFrame();
ManipUI manipui = new ManipUI(manip);
manipFrame.pack();
}
manipFrame.show();
}
}
);```

The rot parameter represents the Rotate/Shear option on the Manipulate menu. The code snippet is the event handler that launches the frame shown in Figure 7.14.

The screen shot in Figure 7.15 shows the image viewer when pan, zoom, rotate, and shear have all been performed. Besides the Lens and Rotate/Shear options, the Manipulate menu also has the option Flip.

FIGURE 7.15 Performing pan, zoom, flip, rotate, and shear together