Rotate image
I have a problem when rotate image. After i rotate, i save the image and the background of image change to black. I occor with some picture as:
http://i209.photobucket.com/albums/bb132/bocanguoi/ti01.gif
http://i209.photobucket.com/albums/bb132/bocanguoi/db01.gif
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class RotateImage {
public static void main(String[] args) throws IOException {
String filePath = "c:/ti01.gif";
String fileout = "c:/ti02.gif";
writeImage(rotateImage(readImage(filePath), 45), fileout);
}
private static void writeImage (BufferedImage toWrite, String fileout) throws IOException {
File f = new File(fileout);
String ext = fileout.substring(fileout.length() - 3, fileout.length());
String filetype = "jpeg";
ImageIO.write((RenderedImage)toWrite, filetype, f);
}
private static BufferedImage readImage (String filename) throws IOException {
File imagein = new File(filename);
BufferedImage bi = ImageIO.read(imagein);
return bi;
}
private static BufferedImage rotateImage (BufferedImage bi, int rotations) {
rotations = rotations % 4;
int newWidth = bi.getWidth();
int newHeight = bi.getHeight();
int moveX = 0;
int moveY = 0;
if (rotations % 2 != 0) {
newHeight = bi.getWidth();
newWidth = bi.getHeight();
}
if (rotations > 1)
moveY = newHeight;
if (rotations > 0 && rotations < 3)
moveX = newWidth;
BufferedImage rbi = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2d = rbi.createGraphics();
AffineTransform af = new AffineTransform();
af.concatenate(AffineTransform.getTranslateInstance(moveX, moveY));
af.concatenate(AffineTransform.getRotateInstance((rotations * 0.5) * Math.PI));
g2d.drawImage((Image) bi, af, null);
return rbi;
}
}

