开发者

Calculating Largest Possible Rectangle

I'm uploading some images to website. They're all sorts of different dimensions. How can I determine the l开发者_C百科argest 4:3 rectangle that I could get out of that particular image without rotating the image?


If the aspect ratio is less than 4:3, keep the original width and use a height of width*3/4. If the aspect ratio is greater than 4:3, keep the original height and use a width of height*4/3.


IIUC this problem is very similar to the common problem of maximizing an image in a given rectangular area.

Supposing your screen is W * H pixels (with W = 4 * H / 3) and that the image is dx * dy then you can stretch the image to maximize it inside the screen using a scale factor of

sf = min(W / dx, H / dy)

because W / dx would be a scale factor that makes the image the same width of your screen and H / dy would be the scale factor that make it the same height instead.

Taking the minimum of the two will ensure that the image can entirely fit and that no pixel will get outside the screen... taking the maximum instead will ensure that the screen will be completely covered with (part of) the image and could be useful if you are trying to get a wallpaper out of an image.

Once you have the scale factor the formulas needed for centering are easy:

x0 = (W - dx * sf) / 2
y0 = (H - dy * sf) / 2

and you simply need to draw the image scaled by sf starting at position (x0, y0).


First rotate your image so that its aspect ratio is at least 1. Now if your aspect ratio is larger than 4/3, keep the height and crop the width; if the aspect ratio is smaller, keep the width and crop the height.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜