Home > Article > Backend Development > PHP uploads images and generates images of specified size in proportion_PHP tutorial
php uploads images and generates images of specified sizes proportionally This is an image thumbnail function. Give the uploaded new image to $srcfile and then press $thumbwidth to reduce the image width to the maximum size and $thumbheitht to reduce the image height to the maximum size to generate a small image.
php tutorial upload images and generate images of specified size according to proportion
This is an image thumbnail function. Give the uploaded new image to $srcfile and then press $thumbwidth to reduce the image width to the maximum size and $thumbheitht to reduce the image height to the maximum size to generate a small image.
Image thumbnail function
Parameter description:
$srcfile original image address;
$dir New picture directory
$thumbwidth reduces the maximum image width
$thumbheitht Reduce the maximum size of the image height
$ratio defaults to a proportional scaling of 1, which means it is reduced to a fixed size.
*/
function makethumb($srcfile,$dir,$thumbwidth,$thumbheight,$ratio=0)
{
//Check whether the file exists
if (!file_exists($srcfile))return false;
//Generate a new file with the same name, but in a different directory
$imgname=explode('/',$srcfile);
$arrcount=count($imgname);
$dstfile = $dir.$imgname[$arrcount-1];
//Thumbnail size
$tow = $thumbwidth;
$toh = $thumbheight;
if($tow < 40) $tow = 40;
if($toh < 45) $toh = 45;
//Get picture information
$im ='';
If($data = getimagesize($srcfile)) {
If($data[2] == 1) {
$make_max = 0;//gif is not processed
If(function_exists("imagecreatefromgif")) {
$im = imagecreatefromgif($srcfile);
} elseif($data[2] == 2) {
If(function_exists("imagecreatefromjpeg")) {
$im = imagecreatefromjpeg($srcfile);
} elseif($data[2] == 3) {
If(function_exists("imagecreatefrompng")) {
$im = imagecreatefrompng($srcfile);
}
}
If(!$im) return '';
$srcw = imagesx($im);
$srch = imagesy($im);
$towh = $tow/$toh;
$srcwh = $srcw/$srch;
If($towh <= $srcwh){
$ftow = $tow;
$ftoh = $ftow*($srch/$srcw);
} else {
$ftoh = $toh;
$ftow = $ftoh*($srcw/$srch);
}
If($ratio){
$ftow = $tow;
$ftoh = $toh;
}
//Shrink the image
If($srcw > $tow || $srch > $toh || $ratio) {
If(function_exists("imagecreatetruecolor") && function_exists("imagecopyresampled") && @$ni = imagecreatetruecolor($ftow, $ftoh)) {
imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftow, $ftoh, $srcw, $srch);
} elseif(function_exists("imagecreate") && function_exists("imagecopyresized") && @$ni = imagecreate($ftow, $ftoh)) {
Imagecopyresized($ni, $im, 0, 0, 0, 0, $ftow, $ftoh, $srcw, $srch);
} else {
return '';
}
If(function_exists('imagejpeg')) {
Imagejpeg($ni, $dstfile);
} elseif(function_exists('imagepng')) {
Imagepng($ni, $dstfile);
}
}else {
//If smaller than the size, copy directly
copy($srcfile,$dstfile);
}
Imagedestroy($im);
If(!file_exists($dstfile)) {
return '';
} else {
return $dstfile;
}
}
?>