从上传的图像创build缩略图

我想从用户上传的图像中创build一个缩略图,以便图像不会被挤压。 但也想要一个原始图像的副本..所以我想原始图像发送原始图像到我的服务器,也创build一个拇指版本,并将其发送到我的服务器,所以我可以为每个用户调用每个用户上传自己的图片。

我的用户表有2个表

`user_pic` longblob NOT NULL, `user_pic_small` longblob NOT NULL, 

编码的形象方面,我不是很热,但这是我迄今为止。

Imageupload.php

 > <form id="myForm" action="include/media.profileimage.upload.php" > method="POST" enctype="multipart/form-data" target="ifr1"> > <input type = "file" name = "image_data" class = "input_text" style="width:800px;" > > <input type = "submit" name = "submit" class = "btn_login" value = "Upload"> > </form> 

media.profileimage.upload.php

 if(isset($_FILES['image_data'])){ if(is_uploaded_file($_FILES['image_data']['tmp_name'])) { // prepare the image for insertion $imgData =addslashes (file_get_contents($_FILES['image_data']['tmp_name'])); // get the image info.. $size = getimagesize($_FILES['image_data']['tmp_name']); // our sql query $creator_id = $_SESSION['id']; $sql = "UPDATE users SET user_pic='".$imgData."' WHERE id=$creator_id"; $sql2 = "INSERT INTO userphotos(photo_ownerid,photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES ($creator_id,1,'Profile Picture','Profile Picture','$imgData')"; // insert the image if(!mysql_query($sql)) { echo "Fail. It broke."; }else{ $c=mysql_query($sql2); echo "<script> parent.alert('Image Uploaded','',1000);</script>"; } } } 

将不胜感激任何帮助或指导。 谢谢

更新:

如果你想利用Imagick(如果它安装在你的服务器上)。 注意:我没有使用Imagick的自然writeFile因为我在我的服务器上遇到问题。 文件放内容的作品也是如此。

 <?php /** * * Generate Thumbnail using Imagick class * * @param string $img * @param string $width * @param string $height * @param int $quality * @return boolean on true * @throws Exception * @throws ImagickException */ function generateThumbnail($img, $width, $height, $quality = 90) { if (is_file($img)) { $imagick = new Imagick(realpath($img)); $imagick->setImageFormat('jpeg'); $imagick->setImageCompression(Imagick::COMPRESSION_JPEG); $imagick->setImageCompressionQuality($quality); $imagick->thumbnailImage($width, $height, false, false); $filename_no_ext = reset(explode('.', $img)); if (file_put_contents($filename_no_ext . '_thumb' . '.jpg', $imagick) === false) { throw new Exception("Could not put contents."); } return true; } else { throw new Exception("No valid image provided with {$img}."); } } // example usage try { generateThumbnail('test.jpg', 100, 50, 65); } catch (ImagickException $e) { echo $e->getMessage(); } catch (Exception $e) { echo $e->getMessage(); } ?> 

我一直在使用这个,只是在你存储原始图像并使用该位置创build缩略图后执行该function。 编辑它到你喜欢…

 function makeThumbnails($updir, $img, $id) { $thumbnail_width = 134; $thumbnail_height = 189; $thumb_beforeword = "thumb"; $arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name $original_width = $arr_image_details[0]; $original_height = $arr_image_details[1]; if ($original_width > $original_height) { $new_width = $thumbnail_width; $new_height = intval($original_height * $new_width / $original_width); } else { $new_height = $thumbnail_height; $new_width = intval($original_width * $new_height / $original_height); } $dest_x = intval(($thumbnail_width - $new_width) / 2); $dest_y = intval(($thumbnail_height - $new_height) / 2); if ($arr_image_details[2] == IMAGETYPE_GIF) { $imgt = "ImageGIF"; $imgcreatefrom = "ImageCreateFromGIF"; } if ($arr_image_details[2] == IMAGETYPE_JPEG) { $imgt = "ImageJPEG"; $imgcreatefrom = "ImageCreateFromJPEG"; } if ($arr_image_details[2] == IMAGETYPE_PNG) { $imgt = "ImagePNG"; $imgcreatefrom = "ImageCreateFromPNG"; } if ($imgt) { $old_image = $imgcreatefrom("$updir" . $id . '_' . "$img"); $new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height); $imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img"); } } 

上述function创build统一的缩略图大小的图像。 如果图像的尺寸与指定的缩略图尺寸(比例)不相同,则只在顶部和底部有黑色空格。

我猜你已经弄清楚了这一点。 但是我发现你将图像存储为“longblobs”,导致我认为你正在存储图像的全部二进制内容。

我希望你已经意识到,只需将文件名存储在数据库中,然后使用该信息从“上传”文件夹或类似文件中抓取图片就更有意义了。

提示 – 不保存文件path..只是文件名..根据需要添加您的代码中的path信息。 这样你就有了最大的自由。 如果您需要更改文件夹结构,可以在代码中执行,而不是更改数据库logging。

我知道这是一个古老的问题,但我偶然发现了同样的问题,并尝试使用Alex的答案中给出的function。

但是jpeg结果的质量太低了。 所以我改变了一点function,在我的项目变得更加可用,并将“imagecopyresized”更改为“imagecopyresampled”( 根据这个build议 )。

如果您有关于如何使用此function的问题,请尝试在这里查看有据可查的版本。

 function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) { list($original_width, $original_height, $original_type) = getimagesize($filepath); if ($original_width > $original_height) { $new_width = $thumbnail_width; $new_height = intval($original_height * $new_width / $original_width); } else { $new_height = $thumbnail_height; $new_width = intval($original_width * $new_height / $original_height); } $dest_x = intval(($thumbnail_width - $new_width) / 2); $dest_y = intval(($thumbnail_height - $new_height) / 2); if ($original_type === 1) { $imgt = "ImageGIF"; $imgcreatefrom = "ImageCreateFromGIF"; } else if ($original_type === 2) { $imgt = "ImageJPEG"; $imgcreatefrom = "ImageCreateFromJPEG"; } else if ($original_type === 3) { $imgt = "ImagePNG"; $imgcreatefrom = "ImageCreateFromPNG"; } else { return false; } $old_image = $imgcreatefrom($filepath); $new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background // figuring out the color for the background if(is_array($background) && count($background) === 3) { list($red, $green, $blue) = $background; $color = imagecolorallocate($new_image, $red, $green, $blue); imagefill($new_image, 0, 0, $color); // apply transparent background only if is a png image } else if($background === 'transparent' && $original_type === 3) { imagesavealpha($new_image, TRUE); $color = imagecolorallocatealpha($new_image, 0, 0, 0, 127); imagefill($new_image, 0, 0, $color); } imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height); $imgt($new_image, $thumbpath); return file_exists($thumbpath); } 

以防万一您需要创build最大宽度和最大高度的拇指…

 function makeThumbnails($updir, $img, $id,$MaxWe=100,$MaxHe=150){ $arr_image_details = getimagesize($img); $width = $arr_image_details[0]; $height = $arr_image_details[1]; $percent = 100; if($width > $MaxWe) $percent = floor(($MaxWe * 100) / $width); if(floor(($height * $percent)/100)>$MaxHe) $percent = (($MaxHe * 100) / $height); if($width > $height) { $newWidth=$MaxWe; $newHeight=round(($height*$percent)/100); }else{ $newWidth=round(($width*$percent)/100); $newHeight=$MaxHe; } if ($arr_image_details[2] == 1) { $imgt = "ImageGIF"; $imgcreatefrom = "ImageCreateFromGIF"; } if ($arr_image_details[2] == 2) { $imgt = "ImageJPEG"; $imgcreatefrom = "ImageCreateFromJPEG"; } if ($arr_image_details[2] == 3) { $imgt = "ImagePNG"; $imgcreatefrom = "ImageCreateFromPNG"; } if ($imgt) { $old_image = $imgcreatefrom($img); $new_image = imagecreatetruecolor($newWidth, $newHeight); imagecopyresized($new_image, $old_image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); $imgt($new_image, $updir."".$id."_t.jpg"); return; } } 

希望这段代码有助于为JPG,PNG和GIF格式创build缩略图。

 <?php $file = "D:/server/sites/Sourcefol/high/bucket/kath23.png"; /*Your Original Source Image */ $pathToSave = "D:/server/sites/Sourcefol/high/bucket/New/"; /*Your Destination Folder */ $sourceWidth =60; $sourceHeight = 60; $what = getimagesize($file); $file_name = basename($file);/* Name of the Image File*/ $ext = pathinfo($file_name, PATHINFO_EXTENSION); /* Adding image name _thumb for thumbnail image */ $file_name = basename($file_name, ".$ext") . '_thumb.' . $ext; switch(strtolower($what['mime'])) { case 'image/png': $img = imagecreatefrompng($file); $new = imagecreatetruecolor($what[0],$what[1]); imagecopy($new,$img,0,0,0,0,$what[0],$what[1]); header('Content-Type: image/png'); break; case 'image/jpeg': $img = imagecreatefromjpeg($file); $new = imagecreatetruecolor($what[0],$what[1]); imagecopy($new,$img,0,0,0,0,$what[0],$what[1]); header('Content-Type: image/jpeg'); break; case 'image/gif': $img = imagecreatefromgif($file); $new = imagecreatetruecolor($what[0],$what[1]); imagecopy($new,$img,0,0,0,0,$what[0],$what[1]); header('Content-Type: image/gif'); break; default: die(); } imagejpeg($new,$pathToSave.$file_name); imagedestroy($new); ?> 

你可以使用最简单的方法

 <?php function make_thumb($src, $dest, $desired_width) { /* read the source image */ $source_image = imagecreatefromjpeg($src); $width = imagesx($source_image); $height = imagesy($source_image); /* find the "desired height" of this thumbnail, relative to the desired width */ $desired_height = floor($height * ($desired_width / $width)); /* create a new, "virtual" image */ $virtual_image = imagecreatetruecolor($desired_width, $desired_height); /* copy source image at a resized size */ imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height); /* create the physical thumbnail image to its destination */ imagejpeg($virtual_image, $dest); } $src="1494684586337H.jpg"; $dest="new.jpg"; $desired_width="200"; make_thumb($src, $dest, $desired_width); ?> 
 function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if(strlen($name)) { $ext = getExtension($name); if(in_array($ext,$valid_formats)) { if($size<(1024*1024)) { $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext; $tmp = $_FILES['photoimg']['tmp_name']; if(move_uploaded_file($tmp, $path.$actual_image_name)) { mysql_query("INSERT INTO users (uid, profile_image) VALUES ('$session_id' , '$actual_image_name')"); echo "<img src='uploads/".$actual_image_name."' class='preview'>"; } else echo "Fail upload folder with read access."; } else echo "Image file size max 1 MB"; } else echo "Invalid file format.."; } else echo "Please select image..!"; exit; } 

图像上传与缩略图生成

upload.php的

 <?php function generate_thumb_now($field_name = '',$target_folder ='',$file_name = '', $thumb = FALSE, $thumb_folder = '', $thumb_width = '',$thumb_height = ''){ //folder path setup $target_path = $target_folder; $thumb_path = $thumb_folder; //file name setup $filename_err = explode(".",$_FILES[$field_name]['name']); $filename_err_count = count($filename_err); $file_ext = $filename_err[$filename_err_count-1]; if($file_name != '') { $fileName = $file_name.'.'.$file_ext; } else { $fileName = $_FILES[$field_name]['name']; } //upload image path $upload_image = $target_path.basename($fileName); //upload image if(move_uploaded_file($_FILES[$field_name]['tmp_name'],$upload_image)) { //thumbnail creation if($thumb == TRUE) { $thumbnail = $thumb_path.$fileName; list($width,$height) = getimagesize($upload_image); $thumb_create = imagecreatetruecolor($thumb_width,$thumb_height); switch($file_ext){ case 'jpg': $source = imagecreatefromjpeg($upload_image); break; case 'jpeg': $source = imagecreatefromjpeg($upload_image); break; case 'png': $source = imagecreatefrompng($upload_image); break; case 'gif': $source = imagecreatefromgif($upload_image); break; default: $source = imagecreatefromjpeg($upload_image); } imagecopyresized($thumb_create, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width,$height); switch($file_ext){ case 'jpg' || 'jpeg': imagejpeg($thumb_create,$thumbnail,100); break; case 'png': imagepng($thumb_create,$thumbnail,100); break; case 'gif': imagegif($thumb_create,$thumbnail,100); break; default: imagejpeg($thumb_create,$thumbnail,100); } } return $fileName; } else { return false; } } if(!empty($_FILES['image']['name'])){ $upload_img = generate_thumb_now('image','uploads/','',TRUE,'uploads /thumbs/','400','320'); //full path of the thumbnail image $thumb_src = 'uploads/thumbs/'.$upload_img; //set success and error messages $message = $upload_img?"<span style='color:#008000;'>Image thumbnail created successfully.</span>":"<span style='color:#F00000;'>Some error occurred, please try again.</span>"; }else{ //if form is not submitted, below variable should be blank $thumb_src = ''; $message = ''; } ?> <html> <head>Image upload and generate thumbnail</head> <body> <div class="messages"><?php echo $message; ?></div> <form method="post" enctype="multipart/form-data"> <input type="file" name="image"/> <input type="submit" name="submit" value="Upload"/> </form> <?php if($thumb_src != ''){ ?> <div class="gallery"> <ul> <li><img src="<?php echo $thumb_src; ?>" alt=""></li> </ul> </div> <?php } ?> </body> </html> 
 <?php error_reporting(0); $change=""; $abc=""; define ("MAX_SIZE","4000"); function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if($_SERVER["REQUEST_METHOD"] == "POST") { $image =$_FILES["file"]["name"]; $uploadedfile = $_FILES['file']['tmp_name']; if ($image) { $filename = stripslashes($_FILES['file']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $change='<div class="msgdiv">Unknown Image extension </div> '; $errors=1; } else { $size=filesize($_FILES['file']['tmp_name']); if ($size > MAX_SIZE*1024) { $change='<div class="msgdiv">You have exceeded the size limit!</div> '; $errors=1; } if($extension=="jpg" || $extension=="jpeg" ) { $uploadedfile = $_FILES['file']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); } else if($extension=="png") { $uploadedfile = $_FILES['file']['tmp_name']; $src = imagecreatefrompng($uploadedfile); } else { $src = imagecreatefromgif($uploadedfile); } echo $scr; list($width,$height)=getimagesize($uploadedfile); $newwidth=45; $newheight=45; $tmp=imagecreatetruecolor($newwidth,$newheight); $newwidth1=90; $newheight1=90; $tmp1=imagecreatetruecolor($newwidth1,$newheight1); $tmp2=imagecreatetruecolor($width,$height); imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height); imagecopyresampled($tmp2,$src,0,0,0,0,$width,$height,$width,$height); $filename = "images/1-". $_FILES['file']['name']=time(); $filename1 = "images/2-". $_FILES['file']['name']=time(); $filename2 = "images/3-". $_FILES['file']['name']=time(); imagejpeg($tmp,$filename,100); imagejpeg($tmp1,$filename1,100); imagejpeg($tmp2,$filename2,100); imagedestroy($src); imagedestroy($tmp); imagedestroy($tmp1); }} } if(isset($_POST['Submit']) && !$errors) { // mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'"); $change=' <div class="msgdiv">Image Uploaded Successfully!</div>'; } ?> <html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head> <title>picture demo</title> <link href=".css" media="screen, projection" rel="stylesheet" type="text/css"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" src="js/jquery_002.js"></script> <script type="text/javascript" src="js/displaymsg.js"></script> <script type="text/javascript" src="js/ajaxdelete.js"></script> <style type="text/css"> .help { font-size:11px; color:#006600; } body { color: #000000; background-color:#999999 ; background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left; font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; } .msgdiv{ width:759px; padding-top:8px; padding-bottom:8px; background-color: #fff; font-weight:bold; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; } #container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF } </style> </head><body> <div align="center" id="err"> <?php echo $change; ?> </div> <div id="space"></div> <div id="container" > <div id="con"> <table width="502" cellpadding="0" cellspacing="0" id="main"> <tbody> <tr> <td width="500" height="238" valign="top" id="main_right"> <div id="posts"> &nbsp;&nbsp;&nbsp;&nbsp;<img src="<?php// echo $filename; ?>" /> &nbsp;&nbsp;&nbsp;&nbsp;<img src="<?php// echo $filename1; ?>" /> <form method="post" action="" enctype="multipart/form-data" name="form1"> <table width="500" border="0" align="center" cellpadding="0" cellspacing="0"> <tr><Td style="height:25px">&nbsp;</Td></tr> <tr> <td width="150"><div align="right" class="titles">Picture : </div></td> <td width="350" align="left"> <div align="left"> <input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/> </div></td> </tr> <tr><Td></Td> <Td valign="top" height="35px" class="help">Image maximum size <b>4000 </b>kb</span></Td> </tr> <tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value=" Upload " name="Submit"/></Td></tr> <tr> <td width="200">&nbsp;</td> <td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="200" align="center"><div align="left"></div></td> <td width="100">&nbsp;</td> </tr> </table></td> </tr> </table> </form> </div> </td> </tr> </tbody> </table> </div> </div> </body></html>