Home >Backend Development >PHP Tutorial >Upload files to generate thumbnails_PHP tutorial
Yesterday, the company suddenly asked for an upload file with attachments, as well as an image upload function and a thumbnail effect. I will post my code below.
First, let’s take a look at the up.htm file. The code is as follows:
if($_FILES['image']['name']){
If($_FILES['image']['size']){
If($_FILES['image']['type'] == "image/pjpeg"){
$im = @imagecreatefromjpeg($_FILES['image']['tmp_name']);
$n_bmp.='.jpg';
}elseif($_FILES['image']['type'] == "image/x-png"){
$im = @imagecreatefrompng($_FILES['image']['tmp_name']);
$n_bmp.='.png';
}elseif($_FILES['image']['type'] == "image/gif"){
$im = @imagecreatefromgif($_FILES['image']['tmp_name']);
$n_bmp.='.gif';
}
}
ResizeImage($im,120,60,md5(date("Y-m-d H:i:s")));
ImageDestroy ($im);
$tag=1;
}
function ResizeImage($im,$maxwidth,$maxheight,$name){
$width = imagesx($im);
$height = imagesy($im);
if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){
if($maxwidth && $width > $maxwidth){
$widthratio = $maxwidth/$width;
$RESIZEWIDTH=true;
}
if($maxheight && $height > $maxheight){
$heightratio = $maxheight/$height;
$RESIZEHEIGHT=true;
}
if($RESIZEWIDTH && $RESIZEHEIGHT){
if($widthratio < $heightratio){
$ratio = $widthratio;
}else{
$ratio = $heightratio;
}
}elseif($RESIZEWIDTH){
$ratio = $widthratio;
}elseif($RESIZEHEIGHT){
$ratio = $heightratio;
}
$newwidth = $width * $ratio;
$newheight = $height * $ratio;
if(function_exists("imagecopyresampled")){
$newim = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
}else{
$newim = imagecreate($newwidth, $newheight);
imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
}
ImageJpeg ($newim,$name . ".jpg");
ImageDestroy ($newim);
}else{
ImageJpeg ($im,$name . ".jpg");
}
}
It’s that simple. The one on the previous page is to generate the file into the directory, and the other is to generate the binary and display it on the web page. Of course, you can also save it to the database. Then read it out.