[php] 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,

I'm not crash hot with the image side of coding but this is what I have so far.

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

Would appreciate any help or guidence. Thankyou

This question is related to php image gd thumbnails

The answer is


UPDATE:

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.

<?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();
}
?>

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.


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.


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

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

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

Image Upload with thumbnail generate

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>

You Can Use The Simplest Method

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

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

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

?>

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

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to gd

Extension gd is missing from your system - laravel composer Update Install GD library and freetype on Linux imagecreatefromjpeg and similar functions are not working in PHP Creating a thumbnail from an uploaded image CentOS: Enabling GD Support in PHP Installation Enabling/installing GD extension? --without-gd Crop image in PHP

Examples related to thumbnails

Carousel with Thumbnails in Bootstrap 3.0 How to display Woocommerce Category image? Creating a thumbnail from an uploaded image Create thumbnail image Generate preview image from Video file? Get img thumbnails from Vimeo? Facebook Post Link Image How do I resize an image using PIL and maintain its aspect ratio?