Home >Backend Development >PHP Tutorial >PHP program to generate thumbnails in equal proportions_PHP tutorial
PHP program to generate thumbnails in equal proportions This program is easy to implement, but it is only used to generate thumbnails in equal proportions. You need to upload the file to the server and then operate it with this function. Friends in need can refer to it.
PHP tutorial program to generate thumbnails in equal proportions
This program is easy to implement, but it is only used to generate thumbnails in equal proportions. You need to upload the file to the server and then operate it with this function. Friends in need can refer to it.
function reSizeImg($imgSrc, $resize_width, $resize_height, $isCut=false) {
//Type of picture
$type = substr ( strrchr ( $imgSrc, "." ), 1 );
//Initialize image
if ($type == "jpg") {
$im = imagecreatefromjpeg ( $imgSrc );
}
if ($type == "gif") {
$im = imagecreatefromgif ($imgSrc);
}
if ($type == "png") {
$im = imagecreatefrompng ( $imgSrc );
}
//Target image address
$full_length = strlen ( $imgSrc );
$type_length = strlen ( $type );
$name_length = $full_length - $type_length;
$name = substr ( $imgSrc, 0, $name_length - 1 );
$dstimg = $name . "_s." . $type;$width = imagesx ( $im );
$height = imagesy ($im);//Generate image
//The proportion of the changed image
$resize_ratio = ($resize_width) / ($resize_height);
//Proportion of actual image
$ratio = ($width) / ($height);
if (($isCut) == 1) //Cut image
{
if ($ratio >= $resize_ratio) //High priority
{
$newimg = imagecreatetruecolor ( $resize_width, $resize_height );
Imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, (($height) * $resize_ratio), $height );
ImageJpeg ( $newimg, $dstimg );
}
if ($ratio < $resize_ratio) //width first
{
$newimg = imagecreatetruecolor ( $resize_width, $resize_height );
Imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, $width, (($width) / $resize_ratio) );
ImageJpeg ( $newimg, $dstimg );
}
} else //Do not crop image
{
if ($ratio >= $resize_ratio) {
$newimg = imagecreatetruecolor ( $resize_width, ($resize_width) / $ratio );
Imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, $resize_width, ($resize_width) / $ratio, $width, $height );
ImageJpeg ( $newimg, $dstimg );
}
if ($ratio < $resize_ratio) {
$newimg = imagecreatetruecolor ( ($resize_height) * $ratio, $resize_height );
Imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, ($resize_height) * $ratio, $resize_height, $width, $height );
ImageJpeg ( $newimg, $dstimg );
}
}
ImageDestroy ( $im );
}
The calling method is simple, just reSizeImg directly, the reference is very simple.