Teo*_*Teo 3 java bufferedimage resize
我怎样才能调整图像大小并保持其纵横比?
这是我使用的方法:
private static BufferedImage resizeImage(BufferedImage originalImage,
int type) {
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
return resizedImage;
}
Run Code Online (Sandbox Code Playgroud)
该type变量:
BufferedImage original = ImageIO.read(new File(imagePath));
int type = original.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
: original.getType();
Run Code Online (Sandbox Code Playgroud)
问题是一些图像被正确调整大小,但其他图像由于IMG_WIDTH和IMG_HEIGHT而失去了宽高比.
有没有办法获得原始图像尺寸,然后应用某种比例调整大小来维持调整大小的图像的纵横比?
你为什么不使用originalImage.getWidth()和originalImage.getHeight()?然后您可以轻松计算纵横比.不要忘记int/int = int,所以你需要这样做
double ratio = 1.0 * originalImage.getWidth() / originalImage.getHeight();
or
double ratio = (double) originalImage.getWidth() / originalImage.getHeight();
Run Code Online (Sandbox Code Playgroud)
关于额外的数学,你可以计算
int height = (int) IMG_WIDTH/ratio;
int width = (int) IMG_HEIGHT*ratio;
Run Code Online (Sandbox Code Playgroud)
然后看看哪个更适合您的需求并调整大小(IMG_WIDTH, height)或(width, IMG_HEIGHT)
| 归档时间: |
|
| 查看次数: |
8565 次 |
| 最近记录: |