PDA

View Full Version : Maintaining aspect ratio when resizing images



Richard
11-27-2011, 08:11 PM
I'm creating a full screen game at the moment for my A2 project in computing, and I need to find a way of resizing images so something that is a square on a 1920x1080 (16:9) native monitor would be resized to still appear square on something that was 800x600 (4:3) native, not that anyone's monitor is 800x600 native nowadays anyway.

At the moment I'm using getScaledInstance in the Image class, but I'm wondering how to maintain the aspect ratio.

Thanks.

Wyn
11-27-2011, 08:42 PM
Why can't my Java class be this challenging.


import java.io.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGEncodeParam;

class AspectRatio {
public static void main(String args[]) {
File file = new File("path");

try {
FileInputStream fis = new FileInputStream(file);
InputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = null;

Image image = (Image)ImageIO.read(bis);

int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);

int thumbWidth = 100;//Specify image width in px
int thumbHeight = 100;//Specify image height in px

double thumbRatio = (double)thumbWidth/(double)thumbHeight;
double imageRatio = (double)imageWidth/(double)imageHeight;

if(thumbRatio<imageRatio) {
thumbHeight = (int) (thumbWidth/imageRatio);
} else {
thumbWidth = (int) (thumbHeight*imageRatio);
}

BufferedImage thumbImage =
new BufferedImage(thumbWidth,thumbHeight,BufferedImage .TYPE_INT_RGB);

Graphics2D graphics = thumbImage.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_INTER POLATION,RenderingHints.VALUE_INTERPOLATION_BILINE AR);
graphics.drawImage(image,0, 0, thumbWidth, thumbHeight,null);

ByteArrayOutputStream out = new ByteArrayOutputStream();

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);

int look = 100;
look = Math.max(0,Math.min(quality,100));
param.setQuality((float)quality/100.0f,false);

String format = "jpg";

encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
ImageIO.write(thumbImage,format, new File("path"));
} catch(IOException ioExcep) {
ioExcep.printStackTrace();
}catch(Exception excep) {
excep.printStackTrace();
}
}
}

Richard
11-27-2011, 09:00 PM
Seems somewhat overcomplicated... I thought it would just involve some maths and percentage calculations. I saw that code when I was searching, but it doesn't output it how I'd like it to. I'll edit this thread when I work out the maths behind it. I have a Resolution class that contains the dimensions and the aspect ratios, so I might be able to do something with that.