Preserve aspect ratio for width or height

This commit is contained in:
Andreas Treichel 2018-12-29 19:41:57 +01:00 committed by Christoph M. Becker
parent e1f101d798
commit 3c9af3095c
4 changed files with 65 additions and 2 deletions

2
NEWS
View File

@ -25,6 +25,8 @@ PHP NEWS
falling back to IMG_CROP_SIDES.
. The default $mode parameter of imagecropauto() has been changed to
IMG_CROP_DEFAULT; passing -1 is now deprecated.
. Added support for aspect ratio preserving scaling to a fixed height for
imagescale(). (Andreas Treichel)
- Hash:
. The hash extension is now an integral part of PHP and cannot be disabled

View File

@ -145,6 +145,8 @@ PHP 7.4 UPGRADE NOTES
* Threshold-cropping now uses the algorithm of system libgd
. The default $mode parameter of imagecropauto() has been changed to
IMG_CROP_DEFAULT; passing -1 is now deprecated.
. imagescale() now supports aspect ratio preserving scaling to a fixed height
by passing -1 as $new_width.
- Hash:
. The hash extension cannot be disabled anymore and is always an integral

View File

@ -4757,15 +4757,19 @@ PHP_FUNCTION(imagescale)
RETURN_FALSE;
}
if (tmp_h < 0) {
if (tmp_h < 0 || tmp_w < 0) {
/* preserve ratio */
long src_x, src_y;
src_x = gdImageSX(im);
src_y = gdImageSY(im);
if (src_x) {
if (src_x && tmp_h < 0) {
tmp_h = tmp_w * src_y / src_x;
}
if (src_y && tmp_w < 0) {
tmp_w = tmp_h * src_x / src_y;
}
}
if (tmp_h <= 0 || tmp_h > INT_MAX || tmp_w <= 0 || tmp_w > INT_MAX) {

View File

@ -0,0 +1,55 @@
--TEST--
Scale images and preserve aspect ratio
--SKIPIF--
<?php
if (!extension_loaded('gd')) die("skip gd extension not available\n");
?>
--FILE--
<?php
$img = imagecreatetruecolor ( 256, 384);
$thumbnail = imagescale($img, 64, -1, IMG_BICUBIC);
var_dump(imagesx($thumbnail));
var_dump(imagesy($thumbnail));
$thumbnail = imagescale($img, -1, 64, IMG_BICUBIC);
var_dump(imagesx($thumbnail));
var_dump(imagesy($thumbnail));
$img = imagecreatetruecolor ( 384, 256);
$thumbnail = imagescale($img, 64, -1, IMG_BICUBIC);
var_dump(imagesx($thumbnail));
var_dump(imagesy($thumbnail));
$thumbnail = imagescale($img, -1, 64, IMG_BICUBIC);
var_dump(imagesx($thumbnail));
var_dump(imagesy($thumbnail));
$img = imagecreatetruecolor ( 256, 256);
$thumbnail = imagescale($img, 64, -1, IMG_BICUBIC);
var_dump(imagesx($thumbnail));
var_dump(imagesy($thumbnail));
$thumbnail = imagescale($img, -1, 64, IMG_BICUBIC);
var_dump(imagesx($thumbnail));
var_dump(imagesy($thumbnail));
?>
DONE
--EXPECT--
int(64)
int(96)
int(42)
int(64)
int(64)
int(42)
int(96)
int(64)
int(64)
int(64)
int(64)
int(64)
DONE