在保持宽高比的同时缩小图像的最有效方法?
Most efficent way to scale down an image while maintaining aspect ratio?
所以我有一个显示我的图像的字段,我的最大高度可以是 375,最大宽度是 775。我希望它尽可能接近这些值之一以获得最大尺寸,同时保持宽高比这是我想出的,它实际上看起来工作得很好,但我想有一个我没有想到的更好的方法。
InputStream in = new ByteArrayInputStream(fileData);
BufferedImage buf = ImageIO.read(in);
int maxWidth = 775;
int maxHeight = 375;
int newWidth;
int newHeight;
float height = buf.getHeight();
float width = buf.getWidth();
float ratio = (float) 0.0;
if(height > maxHeight || width > maxWidth)
{
if (height > width)
{
ratio = (height/width);
}
else if(width > height)
ratio = (width/height);
while(height > maxHeight || width > maxWidth)
{
if (height > width)
{
height -= ratio;
width -= 1;
}
else if(width > height)
{
width -= ratio;
height -= 1;
}
}
}
newWidth = (int) width;
newHeight = (int) height;
// Call method to scale image to appropriate size
byte[] newByte = scale(fileData, newWidth, newHeight);
您知道您将使用两个最大值之一(如果您不这样做,图像仍然可以按比例放大)。
所以这只是一个确定哪个的问题。如果图像的这个宽高比大于最大面积比,那么宽度就是你的限制因素,所以你将宽度设置为最大,并根据你的比例确定高度。
相同的过程可以应用于更小的比率
代码如下所示
float maxRatio = maxWidth/maxHeight;
if(maxRatio > ratio) {
width = maxWidth;
height = width / ratio;
} else {
height = maxHeight;
width = height * ratio;
}
所以我有一个显示我的图像的字段,我的最大高度可以是 375,最大宽度是 775。我希望它尽可能接近这些值之一以获得最大尺寸,同时保持宽高比这是我想出的,它实际上看起来工作得很好,但我想有一个我没有想到的更好的方法。
InputStream in = new ByteArrayInputStream(fileData);
BufferedImage buf = ImageIO.read(in);
int maxWidth = 775;
int maxHeight = 375;
int newWidth;
int newHeight;
float height = buf.getHeight();
float width = buf.getWidth();
float ratio = (float) 0.0;
if(height > maxHeight || width > maxWidth)
{
if (height > width)
{
ratio = (height/width);
}
else if(width > height)
ratio = (width/height);
while(height > maxHeight || width > maxWidth)
{
if (height > width)
{
height -= ratio;
width -= 1;
}
else if(width > height)
{
width -= ratio;
height -= 1;
}
}
}
newWidth = (int) width;
newHeight = (int) height;
// Call method to scale image to appropriate size
byte[] newByte = scale(fileData, newWidth, newHeight);
您知道您将使用两个最大值之一(如果您不这样做,图像仍然可以按比例放大)。
所以这只是一个确定哪个的问题。如果图像的这个宽高比大于最大面积比,那么宽度就是你的限制因素,所以你将宽度设置为最大,并根据你的比例确定高度。
相同的过程可以应用于更小的比率
代码如下所示
float maxRatio = maxWidth/maxHeight;
if(maxRatio > ratio) {
width = maxWidth;
height = width / ratio;
} else {
height = maxHeight;
width = height * ratio;
}