Libraries Search
Showing posts with label Thumbnail With PHP. Show all posts
Showing posts with label Thumbnail With PHP. Show all posts

Create Thumbnail When Uploading With PHP www.Library82.Blogspot.Com !

ould someone please help me as ive been trying to figure out a way to do this for days. At the moment i have a website that you can upload an image to a folder and the image path is stored on the database. When you click on the gallery a thumbnail is produced on the fly using a script called imageResize. I have now found out that producing images on the fly is a no no and i am now looking into a way how to fix it. The way i want to fix it is by uploading the thumbnail sized image to the folder. Is it possible to run the imageResize script in this file when it is uploading.

So like in the code it checks to see if the file doesn’t exist if it doesn’t exist run the script and upload the thumbnail image? Is that possible?

Here is the add_file.php file which is behind the upload form i have



PHP Code:
================================================================
<?php



 $max_size=5*1024*1024;



 // Check if a file has been uploaded

if(isset($_FILES['uploaded_file']) && preg_match("/image\/jpeg|image\/jpg/i",$_FILES['uploaded_file']['type']) && $_FILES['uploaded_file']['size']<= $max_size)

{

     // Make sure the file was sent without errors

     if($_FILES['uploaded_file']['error'] == 0)

    {

       $target_path = "images/";

      $target_path = $target_path . basename( $_FILES['uploaded_file']['name']);

     

      if(!file_exists($target_path)){



   if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path))

      {

          echo "The file ".  basename($_FILES['uploaded_file']['name']). " has been uploaded";

                           

         $dbLink = new mysqli('localhost', 'root', '', 'gallery');

            if(mysqli_connect_errno()) {

            die("MySQL connection failed: ". mysqli_connect_error());

                                 }         

      

             // Gather all required data

             $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);

             $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);

             $size = intval($_FILES['uploaded_file']['size']);

             $image_path = $dbLink->real_escape_string($target_path);

           $gallery_type = $dbLink->real_escape_string($_POST['gallery_type']);

          $desc = $dbLink->real_escape_string($_POST['desc']);

         

          //query to insert the data i had gathered into the database

          $query = "INSERT INTO `images` (`name`, `size`, `created`, `image_path`, `gallery_type_id`, `desc` )

             VALUES ('{$name}', {$size}, NOW(), '{$image_path}', '{$gallery_type}', '{$desc}')";

         

          //executes the query

          $dbLink->query($query);

      }

   }

    

   else

       {

          echo 'A file with the same name exists please change the file name and try again';

        }

}

 

  else

        {

     echo 'A file was not sent';

      }

}



else

        {

     echo 'The file is too large';

      }

     

 // Echo a link back to the main page

 echo '<p>Click <a href="member-index.php">here</a> to go back</p>';

 ?>
===============================================================
this is the imageResize script i use if you are curious to see what it looks like:

PHP Code:
===============================================================


<?php



error_reporting(E_ALL &~ E_NOTICE);



$image = "C:/wamp/www/Blean_Photos/images/" . $_GET['imageFilename'];



switch(strtolower(substr($_GET['imageFilename'], -3))) {

case "jpg" :

$fileType = "jpeg";

$imageCreateFunction = "imagecreatefromjpeg";

$imageOutputFunction = "imagejpeg";

break;

case "jpeg" :

$fileType = "jpeg";

$imageCreateFunction = "imagecreatefromjpeg";

$imageOutputFunction = "imagejpeg";

break;

case "png" :

$fileType = "png";

$imageCreateFunction = "imagecreatefrompng";

$imageOutputFunction = "imagepng";

break;

}



if(!$_GET['maxWidth']) {

$maxWidth = 100;

} else {

$maxWidth = $_GET['maxWidth'];

}



if(!$_GET['maxHeight']) {

$maxHeight = 150;

} else {

$maxHeight = $_GET['maxHeight'];

}



$size = GetImageSize($image);

$originalWidth = $size[0];

$originalHeight = $size[1];



$x_ratio = $maxWidth / $originalWidth;

$y_ratio = $maxHeight / $originalHeight;



// check that the new width and height aren't bigger than the original values.



if (($originalWidth <= $maxWidth) && ($originalHeight <= $maxHeight)) { // the new values are higher than the original, don't resize or we'll lose quality

$newWidth = $originalWidth;

$newHeight = $originalHeight;

} else if (($x_ratio * $originalHeight) < $maxHeight) {

$newHeight = ceil($x_ratio * $originalHeight);

$newWidth = $maxWidth;

} else {

$newWidth = ceil($y_ratio * $originalWidth);

$newHeight = $maxHeight;

}



$src = $imageCreateFunction($image);

$dst = imagecreatetruecolor($newWidth, $newHeight);



// Resample

$thumbnail = imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

unset($image);

// Output





Header('Content-type: image/' . $fileType);

$imageOutputFunction($dst);



ImageDestroy($src);

ImageDestroy($dst);



?>
===================================================================

Create Thumbnail With PHP www.Library82.Blogspot.Com !

In this post you will find how to create thumbnail images with PHP. Function uses GD library so it doesn't depend on installed utilities like ImageMagick. On the other hand, you will have to install php-gd module - "yum install php-gd". Function will resize JPEG, PNG and GIF images, while PNG and GIF without losing their transparency. Version with GD library is a little bit longer than a version with ImageMagick utilities.

If you are looking for ImageMagick version of PHP thumbnail function, please see Create thumbnail with PHP (1). Both versions will do the same "magic".

==============================================================================

/**
 * function creates a thumbnail image in the same directory with the prefix 'tn'
 * thumb should fit to the defined box (second parameter)
 * only bigger images are processed, while smaller images are just copied
 * function will resize PNG and GIF images, without losing their transparency
 *
 * @param string  $image1_path - full path to the image
 * @param integer $box         - box dimension
 */
function create_thumb($image1_path, $box=200){
    // get image size and type
    list($width1, $height1, $image1_type) = getimagesize($image1_path);

    // prepare thumb name in the same directory with prefix 'tn'
    $image2_path = dirname($image1_path) . '/tn_' .basename($image1_path);

    // make image smaller if doesn't fit to the box
    if ($width1 > $box || $height1 > $box){
        // set the largest dimension
        $width2 = $height2 = $box;
        // calculate smaller thumb dimension (proportional)
        if ($width1 < $height1) $width2  = round(($box / $height1) * $width1);
        else                    $height2 = round(($box / $width1) * $height1);

        // set image type, blending and set functions for gif, jpeg and png
        switch($image1_type){
            case IMAGETYPE_PNG:  $img = 'png';  $blending = false; break;
            case IMAGETYPE_GIF:  $img = 'gif';  $blending = true;  break;
            case IMAGETYPE_JPEG: $img = 'jpeg'; break;
        }
        $imagecreate = "imagecreatefrom$img";
        $imagesave   = "image$img";

        // initialize image from the file
        $image1 = $imagecreate($image1_path);

        // create a new true color image with dimensions $width2 and $height2
        $image2 = imagecreatetruecolor($width2, $height2);

        // preserve transparency for PNG and GIF images
        if ($img == 'png' || $img == 'gif'){
          // allocate a color for thumbnail
            $background = imagecolorallocate($image2, 0, 0, 0);
            // define a color as transparent
            imagecolortransparent($image2, $background);
            // set the blending mode for thumbnail
            imagealphablending($image2, $blending);
            // set the flag to save alpha channel
            imagesavealpha($image2, true);
        }

        // save thumbnail image to the file
        imagecopyresampled($image2, $image1, 0, 0, 0, 0, $width2, $height2, $width1, $height1);
        $imagesave($image2, $image2_path);
    }
    // else just copy the image
    else copy($image1_path, $image2_path);
====================================================================================

I also wrote Resize images with PHP where you can read about resizing all JPG images inside a current directory. After saving images from my camera to the computer, I needed a tool to prepare images for the Web upload. With small command line PHP script, images are converted to the lower resolution and saved to the separate directory.