Monday, September 28, 2009

Potentially Useful Functions (#1 in a series)

The original aim of this blog was for me to impart my knowledge of programming, or for people to point out bugs and problems with my code. Either way, it was supposed to be about programming rather than subliminal advertising for my games.

This post aims to correct that, so to get things started here's two nice small graphics function that someone somewhere may find useful:-

This one rotates an image:-


public static Image rotateImage(Image inputImage, float ang_deg, ImageObserver ob) {
BufferedImage sourceBI = new BufferedImage(inputImage.getWidth(ob), inputImage.getHeight(ob), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = (Graphics2D) sourceBI.getGraphics();
g.drawImage(inputImage, 0, 0, null);

AffineTransform at = new AffineTransform();

// rotate 45 degrees around image center
at.rotate(ang_deg * Math.PI / 180.0, sourceBI.getWidth()/2, sourceBI.getHeight()/2);

// instantiate and apply affine transformation filter
BufferedImageOp bio;
bio = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);

BufferedImage destinationBI = bio.filter(sourceBI, null);

return destinationBI;
}


And this one scales an image

public static Image scaleImage(Image inputImage, int w, int h, ImageObserver ob) {
BufferedImage sourceBI = new BufferedImage(inputImage.getWidth(ob), inputImage.getHeight(ob), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = (Graphics2D) sourceBI.getGraphics();
g.drawImage(inputImage, 0, 0, null);

AffineTransform at = new AffineTransform();

// scale image
float sx = (float)w / (float)inputImage.getWidth(ob);
float sy = (float)h / (float)inputImage.getHeight(ob);
//at.scale(w / inputImage.getWidth(ob), h / inputImage.getHeight(ob));
at.scale(sx, sy);

//at.rotate(45 * Math.PI / 180.0, sourceBI.getWidth()/2, sourceBI.getHeight()/2);

// instantiate and apply affine transformation filter
BufferedImageOp bio;
bio = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);

BufferedImage destinationBI = bio.filter(sourceBI, null);

return destinationBI;
}



Needless to say, if anyone knows a better way to do this, or just tweaks to the above code, please let me know.

No comments: