Once in a while you'll encounter this problem and the logic usually remains the same regardless of what language you're using.
Use cases are:
- Resize to given width and height, ignoring image aspect ratio
- Resize to given width, keeping height in the correct aspect ratio
- Resize to height, keeping height in the correct aspect ratio
The tutorial/example below is given in PHP, but if you skim the lines of code its just some common control statements that are used.
01.
if
(!
file_exists
(
$resized_file
)) {
02.
$image_info
= image_get_info(
$input_file
);
03.
$w
=
$image_info
[
'width'
];
04.
$h
=
$image_info
[
'height'
];
05.
06.
if
(!
$reso
[
'keep_ratio'
]) {
07.
$w
=
intval
(
$reso
[
'width'
] != -1 ?
$reso
[
'width'
] :
$image_info
[
'width'
] * (
$reso
[
'height'
] /
$image_info
[
'height'
]));
08.
$h
=
intval
(
$reso
[
'height'
] != -1 ?
$reso
[
'height'
] :
$image_info
[
'height'
] * (
$reso
[
'width'
] /
$image_info
[
'width'
]));
09.
}
10.
11.
else
{
12.
// Check if resize needed ...
13.
if
((
$image_info
[
'width'
] >
$reso
[
'width'
]) || (
$image_info
[
'height'
] >
$reso
[
'height'
])) {
14.
// Compare ratios to determine which side is longer
15.
// If width ratio < height ratio, then use height/width, otherwise width/height
16.
$resize_by_width
= ((
$image_info
[
'width'
] /
$reso
[
'width'
]) > (
$image_info
[
'height'
] /
$reso
[
'height'
]));
17.
18.
$resize_ratio
= (
$resize_by_width
?
$reso
[
'width'
] /
$image_info
[
'width'
] :
$reso
[
'height'
] /
$image_info
[
'height'
]);
19.
20.
$w
=
$image_info
[
'width'
] *
$resize_ratio
;
21.
$h
=
$image_info
[
'height'
] *
$resize_ratio
;
22.
}
23.
}
24.
25.
image_resize(
$input_file
,
$resized_file
,
$w
,
$h
);
26.
}
Hopefully thats fairly easy to translate into another programming language.