php resize image on upload

resize image php
php image resize and save to folder
php gd upload resize image
php image crop and resize
php resize image and save
set image upload size php
jquery image crop and upload php
resize multiple images in codeigniter

I got a form where the user is inserting some data and also uploading an image.

To deal with the image, I got the following code:

define("MAX_SIZE", "10000");
$errors = 0;
$image = $_FILES["fileField"]["name"];
$uploadedfile = $_FILES['fileField']['tmp_name'];
if($image){
    $filename = stripslashes($_FILES['fileField']['name']);
    $extension = strtolower(getExtension($filename));
    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")){
        echo ' Unknown Image extension ';
        $errors = 1;
    } else {
        $newname = "$product_cn.$extension";
        $size = filesize($_FILES['fileField']['tmp_name']);
        if ($size > MAX_SIZE*1024){
            echo "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);
        }
        list($width, $height) = getimagesize($uploadedfile);
        $newwidth = 60;
        $newheight = ($height/$width)*$newwidth;
        $tmp = imagecreatetruecolor($newwidth, $newheight);
        $newwidth1 = 25;
        $newheight1 = ($height/$width)*$newwidth1;
        $tmp1 = imagecreatetruecolor($newwidth1, $newheight1);
        imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        imagecopyresampled($tmp1, $src, 0, 0, 0, 0, $newwidth1, $newheight1, $width, $height);
        $filename = "../products_images/$newname";
        $filename1 = "../products_images/thumbs/$newname";
        imagejpeg($tmp, $filename, 100); // file name also indicates the folder where to save it to
        imagejpeg($tmp1, $filename1, 100);
        imagedestroy($src);
        imagedestroy($tmp);
        imagedestroy($tmp1);
    }
}

getExtension function:

function getExtension($str) {
    $i = strrpos($str, ".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
}

I've wrote some notation in the code since I'm not really familiar with those functions.

For some reason, it doesn't work. When I'm going to the folder "product_images" or "product_images/thumbs", I can't find any image uploaded.

Any idea what's wrong with my code? There should be 60px width image, and 25px width image.

Note: Variables that you don't know where they were declared such as $product_cn were declared before that block of code which works prefectly fine (tested). If you still want a glance at it, feel free to ask for the code.

Thanks in advance!

You can use this library to manipulate the image while uploading. http://www.verot.net/php_class_upload.htm

Try this code this may help you. in this variable $resizeObj = new resize('sample.​png'); you need to link your uploaded picture url. Imagerezise.php <?php  So your photos should be resize able or need to generate thumbnail when user upload those images. So here i will explain how to create thumbnail image in your code php project. Here, i use core php code so you can easily use in your project or any php framework like laravel, codeigniter, cackephp etc.

Here is another nice and easy solution:

$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
    $target_filename = $file_name;
    $ratio = $width/$height;
    if( $ratio > 1) {
        $new_width = $maxDim;
        $new_height = $maxDim/$ratio;
    } else {
        $new_width = $maxDim*$ratio;
        $new_height = $maxDim;
    }
    $src = imagecreatefromstring( file_get_contents( $file_name ) );
    $dst = imagecreatetruecolor( $new_width, $new_height );
    imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
    imagedestroy( $src );
    imagepng( $dst, $target_filename ); // adjust format as needed
    imagedestroy( $dst );
}

Reference: PHP resize image proportionally with max width or weight

Edit: Cleaned up and simplified the code a bit. Thanks @jan-mirus for your comment.

index.php. <title>PHP Image resize to upload</title> <form action="pro.php" method="post" enctype="multipart/form-data"> <input type="file" name="image" /> <input type="submit" name="submit" value="Submit" /> </div> Reference: PHP resize image proportionally with max width or weight. Edit: Cleaned up and simplified the code a bit. Thanks @jan-mirus for your comment.

// This was my example that I used to automatically resize every inserted photo to 100 by 50 pixel and image format to jpeg hope this helps too

if($result){
$maxDimW = 100;
$maxDimH = 50;
list($width, $height, $type, $attr) = getimagesize( $_FILES['photo']['tmp_name'] );
if ( $width > $maxDimW || $height > $maxDimH ) {
    $target_filename = $_FILES['photo']['tmp_name'];
    $fn = $_FILES['photo']['tmp_name'];
    $size = getimagesize( $fn );
    $ratio = $size[0]/$size[1]; // width/height
    if( $ratio > 1) {
        $width = $maxDimW;
        $height = $maxDimH/$ratio;
    } else {
        $width = $maxDimW*$ratio;
        $height = $maxDimH;
    }
    $src = imagecreatefromstring(file_get_contents($fn));
    $dst = imagecreatetruecolor( $width, $height );
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1] );

    imagejpeg($dst, $target_filename); // adjust format as needed


}

move_uploaded_file($_FILES['pdf']['tmp_name'],"pdf/".$_FILES['pdf']['name']);

jpg each time, and then it will overwrite it the next time around. Could any of you guys help me out with this? Thanks! <form action="<?php echo $_server['php  Using PHP and JavaScript its few lines of code to upload and resize an image. 9leassion had developed perfect PHP script it’s verify extension, image size and resize image. It’s very useful image upload script in web projects to reduces servers space.

<form action="<?php echo $_SERVER["PHP_SELF"];  ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">
    <input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />
    <button name="submit" type="submit" class="submitButton">Upload Image</button>
</form>

<?php
    if(isset($_POST['submit'])){
      if (isset ($_FILES['new_image'])){              
          $imagename = $_FILES['new_image']['name'];
          $source = $_FILES['new_image']['tmp_name'];
          $target = "images/".$imagename;
          $type=$_FILES["new_image"]["type"];

          if($type=="image/jpeg" || $type=="image/jpg"){
          move_uploaded_file($source, $target);
          //orginal image making part

          $imagepath = $imagename;
          $save = "images/" . $imagepath; //This is the new file you saving
          $file = "images/" . $imagepath; //This is the original file
          list($width, $height) = getimagesize($file) ;
          $modwidth = 1000;
          $diff = $width / $modwidth;
          $modheight = $height / $diff;   
          $tn = imagecreatetruecolor($modwidth, $modheight) ;
          $image = imagecreatefromjpeg($file) ;
          imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
          echo "Large image: <img src='images/".$imagepath."'><br>";                     
          imagejpeg($tn, $save, 100) ;

          //thumbnail image making part
          $save = "images/thumb/" . $imagepath; //This is the new file you saving
          $file = "images/" . $imagepath; //This is the original file   
          list($width, $height) = getimagesize($file) ;
          $modwidth = 150;
          $diff = $width / $modwidth;
          $modheight = $height / $diff;
          $tn = imagecreatetruecolor($modwidth, $modheight) ;
          $image = imagecreatefromjpeg($file) ;
          imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
        //echo "Thumbnail: <img src='images/sml_".$imagepath."'>";
          imagejpeg($tn, $save, 100) ;
          }
        else{
            echo "File is not image";
            }
      }
    }
?>

how to resize images during the uploading process to save disk space and make sure your Duration: 17:26 Posted: 26 Aug 2017 Crop and resize images with PHP. Now the fun part begins. We will resize the uploaded image and save resized version in uploads folder so you can easily use them later. We can do this from scratch, but there are plenty of useful libraries on the web that does an excellent job. I will use a great ImageManipulator class by Phil Brown. Download it

If you want to use Imagick out of the box (included with most PHP distributions), it's as easy as...

$image = new Imagick();
$image_filehandle = fopen('some/file.jpg', 'a+');
$image->readImageFile($image_filehandle);

$image->scaleImage(100,200,FALSE);

$image_icon_filehandle = fopen('some/file-icon.jpg', 'a+');
$image->writeImageFile($image_icon_filehandle);

You will probably want to calculate width and height more dynamically based on the original image. You can get an image's current width and height, using the above example, with $image->getImageHeight(); and $image->getImageWidth();

Image Upload and Resize it using PHP In this post, we are going to know image Duration: 12:34 Posted: 21 Nov 2017 Are you looking for image upload and Resize PHP script. I had implemented a simple PHP script to re-sizing image into different dimensions. It's very useful to your web projects to save hosting space and bandwidth to reduce the original image to compressed size.

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" enctype=​"multipart/form-data">. <input type="hidden" name="action" value="upload" />. On my previous post I was shown an example how to upload file with php and html.It was based on php simple image upload functionality. Today I am going to show you little bit advance of image uploading.

Image Upload and Resize it using PHP help us to create a thumbnail or resized image from an original file with the help of PHP for JPG,JPEG,PNG,GIF type. High-quality images take times to load on the webpage depending on the number of images.You can create multiple sizes of image file when uploading and use the low and high-quality images when required.In this tutorial, I show how you can compress image size while uploading with PHP.

We are going to write an easy PHP code to upload an image, accept user-​submitted image file data and use it to resize the image. In today's era of web based  The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified. This function will not resize the image to max_w pixels by max_h pixels, those are only the max width's and heights the image can be, it resizes the image to the first 1:1 ratio below max_w and max_h.

Comments
  • WARNING: The script is under GPL, so you either need to buy commercial version ($15) or open your website sources under GPL.
  • It works, but I'm confused - why do you extract the image dimensions twice?
  • This is fantastic. Though it's missing a very important line at the end: move_uploaded_file($_FILES['myFile']['tmp_name'], $destinationFilePath);
  • @jan-mirus It was bc the width and height vars were getting changed in the middle. It wasn't pretty and should be easier to read now.
  • Although this code may help to solve the problem, it doesn't explain why and/or how it answers the question. Providing this additional context would significantly improve its long-term educational value. Please edit your answer to add explanation, including what limitations and assumptions apply.
  • Best answer - no any library requires! move_uploaded_file - should be removed, as imagejpeg move the file to the new destination $target_filename
  • Instead of answering years old questions with accepted answers, try answering new questions without answers
  • Hi, welcome to stackoverflow! Any explanation please with this code?