Tuesday, November 4, 2008

RotateFilter

import java.awt.image.*;

public class RotateFilter extends ImageFilter{
public RotateFilter() {
}

// Since you flip the image, if the image is delivered in either
// complete scan lines or top-down, left-right order, you won't be
// passing the data to the consumer that way, so filter out those
// flags from the hints.

public void setHints(int hints) {
consumer.setHints(hints & ~(ImageConsumer.COMPLETESCANLINES +
ImageConsumer.TOPDOWNLEFTRIGHT));
}

// Because you exchange x and y coordinates, width is now height and
// height is now width.

public void setDimensions(int width, int height){
consumer.setDimensions(height, width);
}

// To rotate the pixels, create a new array and copy over the
// pixels, reversing the horizontal pixels and then swapping
// x and y.

public void setPixels(int x, int y, int width, int height,
ColorModel model, byte[] pixels, int offset, int scansize) {

// Create a new array for the pixels
byte[] rotatePixels = new byte[pixels.length];
for (int ry=0; ry < height; ry++) {
for (int rx=0; rx < width; rx++) {
// copy in the pixels with reversed x and y
rotatePixels[rx*height + ry] =
pixels[(ry+1)*scansize-rx-1+offset]; }
}
consumer.setPixels(y, x, height, width, model, rotatePixels,
0, height);
}

// To rotate the pixels, create a new array and copy over the
// pixels, reversing the horizontal pixels and then swapping
// x and y.

public void setPixels(int x, int y, int width, int height,
ColorModel model, int[] pixels, int offset, int scansize){
// Create a new array for the pixels
int[] rotatePixels = new int[pixels.length];
for (int ry=0; ry < height; ry++) {
for (int rx=0; rx < width; rx++) {
// copy in the pixels with reversed x and y
rotatePixels[rx*height + ry] =
pixels[(ry+1)*scansize-rx-1+offset];
}
}
consumer.setPixels(y, x, height, width, model, rotatePixels,
0, height);
}
}