开发者

Resizing images maintaining aspect ratio

I want to resize the images while开发者_开发问答 maintaining the aspect ratio for displaying images on the web page. The maximum image size can be 640x480. What equation can be used to resize the images? I don't care about the newly resized image size. The resolution should be near to 640x480 pixels


I explain using C pseudo-code. First calculate the aspect ratio of the image you want to resize ("testImage"):

double rat = (double)testImage.Width / (double)testImage.Height;

Then we compare it with the aspect ratio of a 640x480 picture. If testImage's ratio ("rat") is bigger than the ratio of a 640x480 picture, then we know if we resize the picture so that its Width becomes 640, its height will not be more than 480. If testImage's aspect ratio is smaller, then we can resize the picture so that height becomes 480 without the width exceeding 640 pixels.

const double rat640x480 = 640.0 / 480.0;
if (rat > rat640x480)
    testImage.Resize(Width := 640, Height := 640 / rat);
else
    testImage.Resize(Width := 480 * rat, Height := 480);


Code in JAVA becomes

double ratio640x480 = 640.0 / 480.0;
double sourceRatio = (double) bitmap.getWidth() / (double) bitmap.getHeight();

if (sourceRatio > ratio640x480)
    bitmap = Bitmap.createScaledBitmap(bitmap, 640, (int) (640 / sourceRatio), true);
else
    bitmap = Bitmap.createScaledBitmap(bitmap, (int) (480 * sourceRatio), 480, true);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜