picture demo

Creating a thumbnail from an uploaded image

I’m wanting to create a thumbnail from a user uploaded image so the image doesn’t look squashed. But also would like a copy of the original image.. So I would like the original image to send the original image to my server and also create a thumb version and send it to my server so I can call each of them for each user that uploads their own image. My user table has 2 tables

`user_pic` longblob NOT NULL, `user_pic_small` longblob NOT NULL, 
> 
method="POST" enctype="multipart/form-data" target="ifr1"> > > >
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 $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 ""; > > > 

9 Answers 9

If you want to take advantage of Imagick (if it is installed on your server). Note: I didn’t use Imagick’s nature writeFile because I was having issues with it on my server. File put contents works just as well.

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 ."); > > // example usage try < generateThumbnail('test.jpg', 100, 50, 65); >catch (ImagickException $e) < echo $e->getMessage(); > catch (Exception $e) < echo $e->getMessage(); > ?> 

I have been using this, just execute the function after you store the original image and use that location to create the thumbnail. Edit it to your liking.

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"); >> 

The above function creates images with a uniform thumbnail size. If the image doesn’t have the same dimensions as the specified thumbnail size (proportionally), it just has blackspace on the top and bottom.

for image quality, in this code, how would be added? I tried to make a thumbnail from it, works like a charm, but the quality of this (at least for JPG images) it’s a bit low. thanks for that piece of code!

Читайте также:  Log file path in java

see Pedro’s answer below: stackoverflow.com/a/31880023/1482904. the solution lies in, as Pedro says, changing: «imagecopyresized» to «imagecopyresampled» . Although if you want more control I would suggest moving to ImageMagick to create your thumbnails, it is a lot more robust if your hosting provider supports it (a simple phpinfo() should show you if its an added extension). I personal use this: github.com/verot/class.upload.php/blob/master/src/…

with Imagick function It is reporting an error -> Only variables should be passed by reference on line 22. (reset(explode(‘.’, $img));)

You Can Use The Simplest Method

 $src="https://stackoverflow.com/questions/11376315/1494684586337H.jpg"; $dest="new.jpg"; $desired_width="200"; make_thumb($src, $dest, $desired_width); ?> 

I’m guessing you have already figured this one out. But I see that you are storing the images as «longblobs» leading me to think you are storing the entire binary content of the pic.

I hope you have realized that it makes much more sense to simply store the file names in your DB and then use that info to grab the pics out of an «upload» folder or similar.

TIP — dont save a file path.. just the file name .. add the path info in your code as needed. That way you have the most freedom down the line. If you need to change folder structure, you can do it in your code rather than changing DB records.

I know this is an old question, but I stumbled upon the same problem and tried to use the function given in Alex’s answer.

But the quality in the jpeg result was too low. So I changed the function a little bit to become more usable in my project and changed the «imagecopyresized» to «imagecopyresampled» (according to this recomendation).

If you are having questions about how to use this function, then try taking a look at the well documented version here.

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); > 

just in case you need to create thumb with a max width and a max height .

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; >> 

Hope this code helps for creating Thumbnail for JPG, PNG & GIF formats.

 imagejpeg($new,$pathToSave.$file_name); imagedestroy($new); ?> 

Doesn’t this just copy the image without resizing? It looks like the thumbnail size variables aren’t used in the actual image copy.

Читайте также:  Число месяц год php

Image Upload with thumbnail generate

upload.php

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?"Image thumbnail created successfully.":"Some error occurred, please try again."; >else < //if form is not submitted, below variable should be blank $thumb_src = ''; $message = ''; >?>Image upload and generate thumbnail
  • picture demo
  • ?>

    Just be careful as you need to type case ‘jpg’: case ‘jpeg’: for [stackoverflow.com/a/207006/5028489](multiple conditions) in a switch statement. Also, I would use the mimetype of the file to check its type and not execute the default imagejpeg() if the correct extension is not detected and throw or return instead.

    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 ""; > 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; > 

    Welcome to Stack Overflow! While this code snippet may solve the problem, it doesn’t explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

     $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='
    Unknown Image extension
    '; $errors=1; > else < $size=filesize($_FILES['file']['tmp_name']); if ($size >MAX_SIZE*1024) < $change='
    You have exceeded the size limit!
    '; $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 users set img='$big',img_small='$small' where user_id='$user'"); $change='
    Image Uploaded Successfully!
    '; > ?> .help < font-size:11px; color:#006600; >body < color: #000000; background-color:#999999 ; background:#999999 url() 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
             
     
    Picture :
     
    Picture :
    Image maximum size 4000 kb
     
     

    Try adding some comments to your answer. Posting 200 lines of code with no explanation is not going to help anybody, ever. Why did you do it like this? What does it solve? What is the outcome? Also, limit your answer to the relevant portions only. not to mention you’re using tables for layout and (I believe) attributes that have been deprecated or removed from tr and td elements (like width , align , etc).

    Welcome to Stack Overflow! While this code snippet may solve the problem, it doesn’t explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Flaggers / reviewers: For code-only answers such as this one, downvote, don’t delete!

    Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.

    Источник

    Оцените статью