Problems rotating BufferedImage - java

I have some problems with rotating images in Java using the AffineTransform class.
I have the following method for creating a rotated (90 degrees) copy of an image:
private BufferedImage createRotatedCopy(BufferedImage img, Rotation rotation) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage rot = new BufferedImage(h, w, BufferedImage.TYPE_INT_RGB);
double theta;
switch (rotation) {
case CLOCKWISE:
theta = Math.PI / 2;
break;
case COUNTERCLOCKWISE:
theta = -Math.PI / 2;
break;
default:
throw new AssertionError();
}
AffineTransform xform = AffineTransform.getRotateInstance(theta, w / 2, h / 2);
Graphics2D g = (Graphics2D) rot.createGraphics();
g.drawImage(img, xform, null);
g.dispose();
return rot;
}
Rotation is a simple enum with the values NONE, CLOCKWISE and COUNTERCLOCKWISE.
The symptoms of my problems are displayed here:
http://perp.se/so/rotate_problems.html
So, the rotation works OK, but the resulting images aren't anchored to the correct coordinates (or how one should put it). And since I don't really know what the heck I'm doing in the first place (my linear algebra is weak), I don't know how to solve this on my own.
I've tried with some random fiddling with the AffineTransform instance, but it hasn't helped me (of course). I've tried googling (and searching SO), but all examples I've seen basically use the same approach as I do... which doesn't work for me.
Thankful for advice.

If you must express the transform as a single rotation, the anchor point depends on the direction of rotation: Either (w/2, w/2) or (h/2, h/2).
But it's probably simpler to express as translate; rotate; translate, e.g.
AffineTransform xform = new AffineTransform();
xform.translate(0.5*h, 0.5*w);
xform.rotate(theta);
xform.translate(-0.5*w, -0.5*h);
Also consider using getQuadrantRotateInstance instead of getRotateInstance.

Since you only need 90 degree rotation you can avoid using the AffineTransform stuff:
public BufferedImage rotate90DX(BufferedImage bi) {
int width = bi.getWidth();
int height = bi.getHeight();
BufferedImage biFlip = new BufferedImage(height, width, bi.getType());
for(int i=0; i<width; i++)
for(int j=0; j<height; j++)
biFlip.setRGB(height-1-j, width-1-i, bi.getRGB(i, j));
return biFlip;
}
This also avoids cutting off edges of rectangular images.
From: http://snippets.dzone.com/posts/show/2936

You could try an alternative appoach and create an Icon from the image and then use a Rotated Icon.
Or you can try this old code I found in the Sun forums:
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
public class RotateImage {
public static void main(String[] args) throws IOException {
URL url = new URL("https://blogs.oracle.com/jag/resource/JagHeadshot-small.jpg");
BufferedImage original = ImageIO.read(url);
GraphicsConfiguration gc = getDefaultConfiguration();
BufferedImage rotated1 = tilt(original, -Math.PI/2, gc);
BufferedImage rotated2 = tilt(original, +Math.PI/4, gc);
BufferedImage rotated3 = tilt(original, Math.PI, gc);
display(original, rotated1, rotated2, rotated3);
}
public static BufferedImage tilt(BufferedImage image, double angle, GraphicsConfiguration gc) {
double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
int w = image.getWidth(), h = image.getHeight();
int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin);
int transparency = image.getColorModel().getTransparency();
BufferedImage result = gc.createCompatibleImage(neww, newh, transparency);
Graphics2D g = result.createGraphics();
g.translate((neww-w)/2, (newh-h)/2);
g.rotate(angle, w/2, h/2);
g.drawRenderedImage(image, null);
return result;
}
public static GraphicsConfiguration getDefaultConfiguration() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
return gd.getDefaultConfiguration();
}
public static void display(BufferedImage im1, BufferedImage im2, BufferedImage im3, BufferedImage im4) {
JPanel cp = new JPanel(new GridLayout(2,2));
addImage(cp, im1, "original");
addImage(cp, im2, "rotate -PI/2");
addImage(cp, im3, "rotate +PI/4");
addImage(cp, im4, "rotate PI");
JFrame f = new JFrame("RotateImage");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(cp);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
static void addImage(Container cp, BufferedImage im, String title) {
JLabel lbl = new JLabel(new ImageIcon(im));
lbl.setBorder(BorderFactory.createTitledBorder(title));
cp.add(lbl);
}
}

I don't know if this might be your issue.
AffineTransform xform = AffineTransform.getRotateInstance(theta, w / 2, h / 2);
Why not try?
AffineTransform xform = AffineTransform.getRotateInstance(theta);
OR
g.transform(AffineTransform.getRotateInstance(theta));
g.drawImage(img, 0, 0, w/2, h/2, null, null);

Related

Rotate BufferedImage with transparent background

I have an image with transparent background. I'd like to rotate this image to a specific angle and keep the transparent background for the resulting image. For this purpose I use the following method:
public static BufferedImage rotateImage(BufferedImage image, double angle, Color backgroundColor) {
System.out.println(image.getType());
double theta = Math.toRadians(angle);
double sin = Math.abs(Math.sin(theta));
double cos = Math.abs(Math.cos(theta));
int w = image.getWidth();
int h = image.getHeight();
int newW = (int) Math.floor(w * cos + h * sin);
int newH = (int) Math.floor(h * cos + w * sin);
BufferedImage tmp = new BufferedImage(newW, newH, image.getType());
Graphics2D g2d = tmp.createGraphics();
if (backgroundColor != null) {
g2d.setColor(backgroundColor);
g2d.fillRect(0, 0, newW, newH);
}
g2d.fillRect(0, 0, newW, newH);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.translate((newW - w) / 2, (newH - h) / 2);
g2d.rotate(theta, w / 2, h / 2);
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
return tmp;
}
I invoke it with background=null:
BufferedImage image = ImageIO.read(file);
rotateImage(image, 4, null);
ImageIO.write(bi, "PNG", new File("image.png"));
but the background of the resulting image.png is WHITE. What am I doing wrong and how to properly keep the transparent background for image.png?
I'm a bit puzzled about the behavior of Graphics.drawImage(). Maybe somebody else can comment about it.
However, Graphics2D.drawRenderedImage() works a treat. It takes an AffineTransform to control the rotation. The below example nicely works. You probably have additional requirement about the final image size and the location of the rotated image.
import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
public class ImageRotation {
public static void main(String[] args) {
ImageRotation rotation = new ImageRotation();
rotation.rotate("input.png", 45, "output.png");
}
public void rotate(String inputImageFilename, double angle, String outputImageFilename) {
try {
BufferedImage inputImage = ImageIO.read(new File(inputImageFilename));
BufferedImage outputImage = rotateImage(inputImage, angle);
ImageIO.write(outputImage, "PNG", new File(outputImageFilename));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private BufferedImage rotateImage(BufferedImage sourceImage, double angle) {
int width = sourceImage.getWidth();
int height = sourceImage.getHeight();
BufferedImage destImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = destImage.createGraphics();
AffineTransform transform = new AffineTransform();
transform.rotate(angle / 180 * Math.PI, width / 2 , height / 2);
g2d.drawRenderedImage(sourceImage, transform);
g2d.dispose();
return destImage;
}
}
Update
While the above code works for most PNGs, it does not work for the image that alexanoid is using. I've analyzed the image:
It's a grayscale image without a color palette (PNG color type 0) .
It uses simple transparency with a 2 byte long tRNS chunk.
As far as I can tell that's perfectly legal. However, ImageIO does not implement this combination. If the image has no palette, it simply ignores the tRNS chunk and therefore ignores the transparency information. That's most likely a bug.
You basically have two options now:
Look for an alternative library to read PNG files.
Fix the transparency after you have read the PNG file. This only works if know that the image used the particular problematic format.
Input and output for working PNG files
Input image:
Ouptput Image:

Java Graphics2D scale font to fill in background

I'm having troubles scaling font to fit in background width. I have a 1000 height and 350 width background, and I'm trying to scale font when it's bigger than background.
I've done several test with different font and results are the same, some letters missed or blank spaces at the end of text.
This is the code:
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class PruebaStackoverflow {
public static void main(String[] args) {
String titleText = null;
Graphics2D g2D = null;
Font testFont = null;
File imageGrayBackgroundFile = new File(
"resources/pruebaAltaResolucionGris.png");
File destinationImageGray = new File("resources/outputTextGray.png");
BufferedImage background = readImage(imageGrayBackgroundFile);
titleText = "Lorem ipsum dolor sit amet asdkf sdm";
testFont = new Font("Lucida Console", Font.PLAIN, 50);
g2D = background.createGraphics();
g2D.setColor(Color.BLACK);
g2D.setFont(testFont);
g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2D = scaleFontFromFontMetrics(g2D, background, titleText);
g2D.drawString(titleText, 0, 150);
g2D.dispose();
writeImage(destinationImageGray, background);
}
private static Graphics2D scaleFontFromFontMetrics(Graphics2D g2D,
BufferedImage backgroundImage, String text) {
double xScale;
double yScale;
double scale;
Integer backgroundWidth = null;
Integer backgroundHeight = null;
Integer textWidth = null;
Integer textHeigth = null;
backgroundWidth = backgroundImage.getWidth();
backgroundHeight = backgroundImage.getHeight();
Font f = g2D.getFont();
FontMetrics fm = g2D.getFontMetrics(f);
textWidth = fm.stringWidth(text);
textHeigth = fm.getHeight();
xScale = backgroundWidth / (double) textWidth;
yScale = backgroundHeight / (double) textHeigth;
if (xScale > yScale) {
scale = yScale;
} else {
scale = xScale;
}
g2D.setFont(f.deriveFont(AffineTransform.getScaleInstance(scale, scale)));
return g2D;
}
private static BufferedImage readImage(File sourceImage) {
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(sourceImage);
} catch (IOException e1) {
e1.printStackTrace();
}
return bufferedImage;
}
private static void writeImage(File destinationImage,
BufferedImage bufferedImage) {
try {
ImageIO.write(bufferedImage, "png", destinationImage);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Image Saved");
}
}
this is the text to scale "Lorem ipsum dolor sit amet asdkf sdm"
and this is text scaled with affine transformation.
output image with font scaled and 'm' letter missed
I hope that you may help me, thanks
you can measure the length of a string and verify if it fits in your content.
int lengthInPixel = graphics.getFontMetrics().stringWidth("Lorem ipsum dolor sit amet asdkf sdm")
Following on from my comment earlier, here's a solution where the closest font size to the image width is used. The text is drawn to a separate image, resized, then drawn to the final image. This is all done in the createTextImage() method. Note, I have created a background image rather than using a file.
The outcome may not be as crisp as desired, but you could experiment with different algorithms for resizing. Hopefully it'll give you a starting point.
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Main {
public static void main(String[] args) {
String titleText = "Lorem ipsum dolor sit amet asdkf sdm";
Font initialFont = new Font("Lucida Console", Font.PLAIN, 50);
BufferedImage textImg = createTextImage(titleText, 350, 1000, 150,
initialFont, Color.BLACK, Color.GRAY);
writeImage(new File("outputTextGray.png"), textImg);
}
private static BufferedImage createTextImage(String text, int targetWidth,
int targetHeight, int textYOffset, Font font, Color textColor, Color bgColor) {
// The final image
BufferedImage finalImg = createBackgroundImg(targetWidth, targetHeight, bgColor);
Graphics2D finalImgG = finalImg.createGraphics();
Font closestFont = scaleFont(finalImg, font, text);
finalImgG.setFont(closestFont);
// Create new image to fit text
int textWidth = finalImgG.getFontMetrics().stringWidth(text);
int textHeight = finalImgG.getFontMetrics().getHeight();
BufferedImage textImg = createBackgroundImg(textWidth, textHeight * 2, bgColor);
// Draw text
Graphics2D textImgG = textImg.createGraphics();
textImgG.setFont(closestFont);
textImgG.setColor(textColor);
textImgG.drawString(text, 0, textHeight);
// Scale text image
double scale = getScale(textImg.getWidth(), textImg.getHeight(),
targetWidth, targetHeight);
Image resized = textImg.getScaledInstance((int) (textImg.getWidth() * scale),
(int) (textImg.getHeight() * scale), Image.SCALE_SMOOTH);
// Draw text image onto final image
finalImgG.drawImage(resized, 0, textYOffset, null);
return finalImg;
}
private static Font scaleFont(BufferedImage img, Font font, String text) {
Graphics2D g2D = img.createGraphics();
g2D.setFont(font);
double scale = getScale(g2D.getFontMetrics().stringWidth(text),
g2D.getFontMetrics().getHeight(), img.getWidth(),
img.getHeight());
return g2D.getFont().deriveFont(AffineTransform.getScaleInstance(scale, scale));
}
private static double getScale(int width, int height, int targetWidth, int targetHeight) {
assert width > 0 && height > 0 : "width and height must be > 0";
double scaleX = (double) targetWidth / width;
double scaleY = (double) targetHeight / height;
return scaleX > scaleY ? scaleY : scaleX;
}
private static BufferedImage createBackgroundImg(int width, int height, Color color) {
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < bufferedImage.getWidth(); x++) {
for (int y = 0; y < bufferedImage.getHeight(); y++) {
bufferedImage.setRGB(x, y, color.getRGB());
}
}
return bufferedImage;
}
private static void writeImage(File destinationImage,
BufferedImage bufferedImage) {
try {
ImageIO.write(bufferedImage, "png", destinationImage);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Image Saved");
}
}
Something I do to fit a game-screen to a certain resolution, is to pre-calculate the ratio, after testing its maximum bound. Something like this (I changed my actual code to your case):
double calculateScaling( BufferedImage image, String text, Font font ){
//These are final to avoid accidental mending, since they are
//the base for our calculations.
//Belive me, it took me a while to debug the
//scale calculation when I made this for my games :P
/**
* imageWidth and imageHeight are the bounds
*/
final int imageWidth = image.getWidth();
final int imageHeight = image.getHeight();
Graphics2D g2 = image.createGraphics();
FontMetrics fm = g2.getFontMetrics( font );
/**
* requestedStringWidthSize e requestedStringHeightSize are the measures needed
* to draw the text WITHOUT resizing.
*/
final int requestedStringWidthSize = fm.stringWidth( text );
final int requestedStringHeightSize = fm.getHeight();
double stringHeightSizeToUse = imageHeight;
double stringWidthSizeToUse;
double scale = stringHeightSizeToUse/requestedStringHeightSize;
stringWidthSizeToUse = scale*requestedStringWidthSize;
/**
* Checking if fill in height makes the text go out of bound in width,
* if it does, it rescalates it to size it to maximum width.
*/
if( imageWidth < ((int)(Math.rint(stringWidthSizeToUse))) ) {
stringWidthSizeToUse = imageWidth;
scale = stringWidthSizeToUse/requestedStringWidthSize;
//stringHeightSizeToUse = scale*requestedStringHeightSize;
}
g2.dispose(); //we created this to use fontmetrics, now we don't need it.
return scale;
}
In my game, I would store the scale as float instead of double to avoid heavy calculations on the run, but for you it's just a simple scaling, right?
All you have to do now is to study the code and implement it to yours.
I hope I have helped.
Have a nice day. :)

Bufferedimage resize

I am trying to resized a bufferedimage. I am able to store it and show up on a jframe no problems but I can't seem to resize it. Any tips on how I can change this to make it work and show the image as a 200*200 file would be great
private void profPic(){
String path = factory.getString("bottle");
BufferedImage img = ImageIO.read(new File(path));
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
Graphics2D g = dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
g.dispose();
return dimg;
}
Updated answer
I cannot recall why my original answer worked but having tested it in a separate environment, I agree, the original accepted answer doesn't work (why I said it did I cannot remember either). This, on the other hand, did work:
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
If all that is required is to resize a BufferedImage in the resize method, then the Thumbnailator library can do that fairly easily:
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
return Thumbnails.of(img).size(newW, newH).asBufferedImage();
}
The above code will resize the img to fit the dimensions of newW and newH while maintaining the aspect ratio of the original image.
If maintaining the aspect ratio is not required and resizing to exactly the given dimensions is required, then the forceSize method can be used in place of the size method:
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
return Thumbnails.of(img).forceSize(newW, newH).asBufferedImage();
}
Using the Image.getScaledInstance method will not guarantee that the aspect ratio of the original image will be maintained for the resized image, and furthermore, it is in general very slow.
Thumbnailator uses a technique to progressively resize the image which can be several times faster than Image.getScaledInstance while achieving an image quality which generally is comparable.
Disclaimer: I am the maintainer of this library.
Here's some code that I have used to resize bufferedimages, no frills, pretty quick:
public static BufferedImage scale(BufferedImage src, int w, int h)
{
BufferedImage img =
new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
int x, y;
int ww = src.getWidth();
int hh = src.getHeight();
int[] ys = new int[h];
for (y = 0; y < h; y++)
ys[y] = y * hh / h;
for (x = 0; x < w; x++) {
int newX = x * ww / w;
for (y = 0; y < h; y++) {
int col = src.getRGB(newX, ys[y]);
img.setRGB(x, y, col);
}
}
return img;
}
This class resize from a file and get the format name:
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;
import org.apache.commons.io.IOUtils;
public class ImageResizer {
public static void main(String as[]) throws IOException{
File f = new File("C:/Users/samsungrob/Desktop/shuttle.jpg");
byte[] ba = resize(f, 600, 600);
IOUtils.write(ba, new FileOutputStream( new File("C:/Users/samsungrob/Desktop/shuttle_resized.jpg") ) );
}
public static byte[] resize(File file,
int maxWidth, int maxHeight) throws IOException{
int scaledWidth = 0, scaledHeight = 0;
BufferedImage img = ImageIO.read((ImageInputStream) file );
scaledWidth = maxWidth;
scaledHeight = (int) (img.getHeight() * ( (double) scaledWidth / img.getWidth() ));
if (scaledHeight> maxHeight) {
scaledHeight = maxHeight;
scaledWidth= (int) (img.getWidth() * ( (double) scaledHeight/ img.getHeight() ));
if (scaledWidth > maxWidth) {
scaledWidth = maxWidth;
scaledHeight = maxHeight;
}
}
Image resized = img.getScaledInstance( scaledWidth, scaledHeight, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(scaledWidth, scaledHeight, Image.SCALE_REPLICATE);
buffered.getGraphics().drawImage(resized, 0, 0 , null);
String formatName = getFormatName( file ) ;
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(buffered,
formatName,
out);
return out.toByteArray();
}
private static String getFormatName(ImageInputStream iis) {
try {
// Find all image readers that recognize the image format
Iterator iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
// No readers found
return null;
}
// Use the first reader
ImageReader reader = (ImageReader)iter.next();
// Close stream
iis.close();
// Return the format name
return reader.getFormatName();
} catch (IOException e) {
}
return null;
}
private static String getFormatName(File file) throws IOException {
return getFormatName( ImageIO.createImageInputStream(file) );
}
private static String getFormatName(InputStream is) throws IOException {
return getFormatName( ImageIO.createImageInputStream(is) );
}
}
This is a shortened version of what is actually happening in imgscalr, if you just want to use the "balanced" smoothing:
/**
* Takes a BufferedImage and resizes it according to the provided targetSize
*
* #param src the source BufferedImage
* #param targetSize maximum height (if portrait) or width (if landscape)
* #return a resized version of the provided BufferedImage
*/
private BufferedImage resize(BufferedImage src, int targetSize) {
if (targetSize <= 0) {
return src; //this can't be resized
}
int targetWidth = targetSize;
int targetHeight = targetSize;
float ratio = ((float) src.getHeight() / (float) src.getWidth());
if (ratio <= 1) { //square or landscape-oriented image
targetHeight = (int) Math.ceil((float) targetWidth * ratio);
} else { //portrait image
targetWidth = Math.round((float) targetHeight / ratio);
}
BufferedImage bi = new BufferedImage(targetWidth, targetHeight, src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); //produces a balanced resizing (fast and decent quality)
g2d.drawImage(src, 0, 0, targetWidth, targetHeight, null);
g2d.dispose();
return bi;
}
try the imgscalr library. Best lib i found- very fast, good quality and simple to use
BufferedImage thumbnail = Scalr.resize(image, 150);
deprecated link: http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/
Apache 2 License
Check this out, it helps:
BufferedImage bImage = ImageIO.read(new File(C:\image.jpg);
BufferedImage thumbnail = Scalr.resize(bImage, Scalr.Method.SPEED, Scalr.Mode.FIT_TO_WIDTH,
750, 150, Scalr.OP_ANTIALIAS);

Java Image Cut Off

Same question as last time but I will provide more detail.
I am currently rotating images using:
int rotateNum //in main class
double rotationRequired = Math.toRadians(rotateNum);
double locationX = img.getWidth(this) / 2;
double locationY = img.getHeight(this) / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
g2d.drawImage(op.filter((BufferedImage)img, null), imgX, imgY, null);
And then I am actually rotating the image using:
double deltaX = (double)(imgY - otherImg.imgY);
double deltaY = (double)(imgX - otherImg.imgX);
rotateNum = (int)(180 * Math.atan2(deltaY, deltaX) / Math.PI);
My images vary in size. The smaller images don't get cut off (meaning cut off with white space) but the larger ones do, on the left or right side. Resizing the images doesn't work, and I clipped out the white rectangle around the image using the
GIMP.
Example Images:
Before(ignore the grey area to the left)
After:
See the cutoff at the side
The problem is your source image is not exactly quadratic. When you implement the AffineTransform rotation with at.rotate(-rad, width/2, height/2);, it is the same as:
at.translate(width/2,height/2);
at.rotate(rads);
at.translate(-width/2,-height/2);
So, when it execute the last line, it translates to the origin. And if the width is greater than y (or vice versa), than the origin of the transform will be translated to a smaller distance than the side of greater length.
For example, if your width is 30 and your height is 60, than the origin point will be set as (-15,-30) from where the transform was original set. So, when you translate it, say, 90 degrees, the image will end up with "width" 60 and "height" 30, but according to the origin point, the image original bottom will be drawn at (-30,0), so it overflows the AffineTransform in -15 in X axis. Then this part of image will cut.
To correct this, you can use the following code instead:
double degreesToRotate = 90;
double locationX =bufferedImage.getWidth() / 2;
double locationY = bufferedImage.getHeight() / 2;
double diff = Math.abs(bufferedImage.getWidth() - bufferedImage.getHeight());
//To correct the set of origin point and the overflow
double rotationRequired = Math.toRadians(degreesToRotate);
double unitX = Math.abs(Math.cos(rotationRequired));
double unitY = Math.abs(Math.sin(rotationRequired));
double correctUx = unitX;
double correctUy = unitY;
//if the height is greater than the width, so you have to 'change' the axis to correct the overflow
if(bufferedImage.getWidth() < bufferedImage.getHeight()){
correctUx = unitY;
correctUy = unitX;
}
int posAffineTransformOpX = posX-(int)(locationX)-(int)(correctUx*diff);
int posAffineTransformOpY = posY-(int)(locationY)-(int)(correctUy*diff);
//translate the image center to same diff that dislocates the origin, to correct its point set
AffineTransform objTrans = new AffineTransform();
objTrans.translate(correctUx*diff, correctUy*diff);
objTrans.rotate(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(objTrans, AffineTransformOp.TYPE_BILINEAR);
// Drawing the rotated image at the required drawing locations
graphic2dObj.drawImage(op.filter(bufferedImage, null), posAffineTransformOpX, posAffineTransformOpY, null);
Hope it help.
I imagine that it's not the size of the image that matters but rather its eccentricity: images that are more square-like have less of a problem then images that are either more fat or more thin.
I think that your problem is that your center of rotation shouldn't be [width / 2, height / 2] -- it's not that simple. Instead think of the image residing in the left upper portion of a large square the length of the square's side will be the image's width or height, whichever is larger. This is what gets rotated whenever you rotate your image.
For example, please see my reply here: https://stackoverflow.com/a/8720123/522444
This is something that java does unfortunately. One way to solve it is to make the shape a square, so that when rotating no clipping occurs.
This problem is covered in David's "Killer game programming in Java" book, books_google_killer+game+programming+clipping+rotating which is a great book if you want to do any java game programming (Even if it is a bit old).
Edit :: This converting of an image to a square can either be done to the raw image through image editing software, or through java itself. Perhaps roll your own rotating method which can check for such collisions..
Rotating the image may also affect the size of the image. Here is some code I found on the old Sun forums a long time ago (I forget the original poster). It recalculates the size required to display the image at its given angle of rotation:
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
public class RotateImage {
public static void main(String[] args) throws IOException {
URL url = new URL("https://blogs.oracle.com/jag/resource/JagHeadshot-small.jpg");
BufferedImage original = ImageIO.read(url);
GraphicsConfiguration gc = getDefaultConfiguration();
BufferedImage rotated1 = tilt(original, -Math.PI/2, gc);
BufferedImage rotated2 = tilt(original, +Math.PI/4, gc);
BufferedImage rotated3 = tilt(original, Math.PI, gc);
display(original, rotated1, rotated2, rotated3);
}
public static BufferedImage tilt(BufferedImage image, double angle, GraphicsConfiguration gc) {
double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
int w = image.getWidth(), h = image.getHeight();
int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin);
int transparency = image.getColorModel().getTransparency();
System.out.println(transparency);
// BufferedImage result = gc.createCompatibleImage(neww, newh, transparency);
BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
Graphics2D g = result.createGraphics();
g.translate((neww-w)/2, (newh-h)/2);
g.rotate(angle, w/2, h/2);
g.drawRenderedImage(image, null);
return result;
}
public static GraphicsConfiguration getDefaultConfiguration() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
return gd.getDefaultConfiguration();
}
public static void display(BufferedImage im1, BufferedImage im2, BufferedImage im3, BufferedImage im4) {
JPanel cp = new JPanel(new GridLayout(2,2));
addImage(cp, im1, "original");
addImage(cp, im2, "rotate -PI/2");
addImage(cp, im3, "rotate +PI/4");
addImage(cp, im4, "rotate PI");
JFrame f = new JFrame("RotateImage");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(cp);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
static void addImage(Container cp, BufferedImage im, String title) {
JLabel lbl = new JLabel(new ImageIcon(im));
lbl.setBorder(BorderFactory.createTitledBorder(title));
cp.add(lbl);
}
}

Rotating BufferedImage instances

I am having trouble getting a rotated BufferedImage to display. I think the rotation is working just fine, but I can't actually draw it to the screen. My code:
Class extends JPanel {
BufferedImage img;
int rotation = 0;
public void paintComponent(Graphics g) {
g.clearRect(0, 0, getWidth(), getHeight());
img2d = img.createGraphics();
img2d.rotate(Math.toRadians(rotation), img.getWidth() / 2, img.getHeight() / 2);
g.drawImage(img, imgx, imgy, null);
this.repaint();
}
}
This is not working for me. I could not find any way to draw the rotated img2d onto g.
EDIT: I have multiple objects that are being drawn onto g, so I can't rotate that. I need to be able to rotate things individually.
Maybe you should try using AffineTransform like this:
AffineTransform transform = new AffineTransform();
transform.rotate(radians, bufferedImage.getWidth() / 2, bufferedImage.getHeight() / 2);
AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
bufferedImage = op.filter(bufferedImage, null);
Hope this helps.
I would use Graphics2D.drawImage(image, affinetranform, imageobserver).
The code example below rotates and translates an image to the center of the component. This is a screenshot of the result:
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("Test");
frame.add(new JComponent() {
BufferedImage image = ImageIO.read(
new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// create the transform, note that the transformations happen
// in reversed order (so check them backwards)
AffineTransform at = new AffineTransform();
// 4. translate it to the center of the component
at.translate(getWidth() / 2, getHeight() / 2);
// 3. do the actual rotation
at.rotate(Math.PI / 4);
// 2. just a scale because this image is big
at.scale(0.5, 0.5);
// 1. translate the object so that you rotate it around the
// center (easier :))
at.translate(-image.getWidth() / 2, -image.getHeight() / 2);
// draw the image
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(image, at, null);
// continue drawing other stuff (non-transformed)
//...
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
You are rotating the graphics for drawing into your image, not the image. Thats why you see no effect. Apply the rotation to the graphics you are painting on and it will draw the image rotated:
public void paintComponent(Graphics g) {
g.clearRect(0, 0, getWidth(), getHeight());
g.rotate(Math.toRadians(rotation), img.getWidth() / 2, img.getHeight() / 2);
g.drawImage(img, imgx, imgy, null);
this.repaint();
}
This will probably not draw entirely what you expect, the rotation will revolve around the coordinate origin. For the image to be rotate around its center you need to apply a coordinate translation before the rotation, for example:
g.translate(imgx >> 1, imgy >> 1);
The Graphics2D Tutorial has some more examples.
I know this question is old but I came up with a solution that has some advantages:
creates image of correct size.
correct offset.
does not unnecessarily rotate by 0° or 360°.
works for negative angles (e.g. -90°).
works when input is BufferedImage.TYPE_CUSTOM.
As it is, it is assumed that the angle is a multiple of 90°. The only improvement that one might need is to use an Enum for angle instead of just int.
Here's my code:
public static BufferedImage rotateBufferedImage(BufferedImage img, int angle) {
if (angle < 0) {
angle = 360 + (angle % 360);
}
angle %= 360;
if (angle == 0) {
return img;
}
final boolean r180 = angle == 180;
if (angle != 90 && !r180 && angle != 270)
throw new IllegalArgumentException("Invalid angle.");
final int w = r180 ? img.getWidth() : img.getHeight();
final int h = r180 ? img.getHeight() : img.getWidth();
final int type = img.getType() == BufferedImage.TYPE_CUSTOM ? BufferedImage.TYPE_INT_ARGB : img.getType();
final BufferedImage rotated = new BufferedImage(w, h, type);
final Graphics2D graphic = rotated.createGraphics();
graphic.rotate(Math.toRadians(angle), w / 2d, h / 2d);
final int offset = r180 ? 0 : (w - h) / 2;
graphic.drawImage(img, null, offset, -offset);
graphic.dispose();
return rotated;
}
public static BufferedImage rotateBufferedImage(String img, int angle) throws IOException {
return rotateBufferedImage(Paths.get(img), angle);
}
public static BufferedImage rotateBufferedImage(Path img, int angle) throws IOException {
return rotateBufferedImage(ImageIO.read(img.toFile()), angle);
}

Categories