I am trying to bring the functionality of the Matlab's imrotate function to Java. In details, as I have stored an image's pixel values in a 2d array, I want to rotate this image around its center with a specified angle. Most of the answers I have found (using AffineTransform and Graphics2D with BufferedImage) were graphics-oriented and I was not able to produce the result I need as I do not need to draw it visually. For example, the following function returned an image whose all pixel values were 0 (I commented out the visualization part)
public static BufferedImage rotateImage(BufferedImage img, double angle) {
double rads = Math.toRadians(angle);
double sin = Math.abs(Math.sin(rads)), cos = Math.abs(Math.cos(rads));
int w = img.getWidth();
int h = img.getHeight();
int newWidth = (int) Math.floor(w * cos h * sin);
int newHeight = (int) Math.floor(h * cos w * sin);
BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = rotated.createGraphics();
AffineTransform at = new AffineTransform();
at.translate((newWidth - w) / 2, (newHeight - h) / 2);
int x = w / 2;
int y = h / 2;
at.rotate(rads, x, y);
g2d.setTransform(at);
// g2d.drawImage(img, 0, 0, this);
// g2d.setColor(Color.RED);
// g2d.drawRect(0, 0, newWidth - 1, newHeight - 1);
// g2d.dispose();
return rotated;
Any help or suggestion is much appreciated. Also, please tell me if you need further details.
UPDATE: I think I should clarify my question better. So I have a fingerprint image and I need to extract a sub-image from it. After that, I have to rotate the sub-image based on an angle provided. What I have tried was: First, load the image in as a BufferedImage. Then, I extracted the sub-image as a 2-dimensional array of integers. Finally, I need to apply the rotation. As I did some research, I know it sounds silly and I probably am but I tried to create a BufferedImage with the sub-image's 2d array, then rotate with the method given down there. Yet, I was not successful. I look forward to hearing your comments on what I did wrong conceptually or programmatically. Thank you very much.
CodePudding user response:
As pointed out in comments, the following answer might be useful for this question: