php resize image on upload

后端 未结 12 1411
别跟我提以往
别跟我提以往 2020-11-27 04:09

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


        
相关标签:
12条回答
  • 2020-11-27 04:17

    Download library file Zebra_Image.php belo link

    https://drive.google.com/file/d/0Bx-7K3oajNTRV1I2UzYySGZFd3M/view

    resizeimage.php

    <?php
        require 'Zebra_Image.php';
        // create a new instance of the class
         $resize_image = new Zebra_Image();
         // indicate a source image
        $resize_image->source_path = $target_file1;
        $ext = $photo;
        // indicate a target image
        $resize_image->target_path = 'images/thumbnil/' . $ext;
        // resize
        // and if there is an error, show the error message
        if (!$resize_image->resize(200, 200, ZEBRA_IMAGE_NOT_BOXED, -1));
        // from this moment on, work on the resized image
        $resize_image->source_path = 'images/thumbnil/' . $ext;
    ?>
    
    0 讨论(0)
  • 2020-11-27 04:18

    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.

    0 讨论(0)
  • 2020-11-27 04:19

    I followed the steps at https://www.w3schools.com/php/php_file_upload.asp and http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html to produce this solution:

    In my view (I am using the MVC paradigm, but it could be your .html or .php file, or the technology that you use for your front-end):

    <form action="../../photos/upload.php" method="post" enctype="multipart/form-data">
    <label for="quantity">Width:</label>
      <input type="number" id="picture_width" name="picture_width" min="10" max="800" step="1" value="500">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
    </form>
    

    My upload.php:

    <?php
    /* Get original image x y*/
    list($w, $h) = getimagesize($_FILES['fileToUpload']['tmp_name']);
    $new_height=$h*$_POST['picture_width']/$w;
    /* calculate new image size with ratio */
    $ratio = max($_POST['picture_width']/$w, $new_height/$h);
    $h = ceil($new_height / $ratio);
    $x = ($w - $_POST['picture_width'] / $ratio) / 2;
    $w = ceil($_POST['picture_width'] / $ratio);
    /* new file name */
    //$path = 'uploads/'.$_POST['picture_width'].'x'.$new_height.'_'.basename($_FILES['fileToUpload']['name']);
    $path = 'uploads/'.basename($_FILES['fileToUpload']['name']);
    /* read binary data from image file */
    $imgString = file_get_contents($_FILES['fileToUpload']['tmp_name']);
    /* create image from string */
    $image = imagecreatefromstring($imgString);
    $tmp = imagecreatetruecolor($_POST['picture_width'], $new_height);
    imagecopyresampled($tmp, $image,
        0, 0,
        $x, 0,
        $_POST['picture_width'], $new_height,
        $w, $h);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($path,PATHINFO_EXTENSION));
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            //echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            //echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($path)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
        // if everything is ok, try to upload file
    } else {
        /* Save image */
        switch ($_FILES['fileToUpload']['type']) {
            case 'image/jpeg':
                imagejpeg($tmp, $path, 100);
                break;
            case 'image/png':
                imagepng($tmp, $path, 0);
                break;
            case 'image/gif':
                imagegif($tmp, $path);
                break;
            default:
                exit;
                break;
        }
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        /* cleanup memory */
        imagedestroy($image);
        imagedestroy($tmp);
    }
    ?>
    

    The name of the folder where pictures are stored is called 'uploads/'. You need to have that folder previously created and that is where you will see your pictures. It works great for me.

    NOTE: This is my form:

    The code is uploading and resizing pictures properly. I used this link as a guide: http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html. I modified it because in that code they specify both width and height of resized pictures. In my case, I only wanted to specify width. The height I automatically calculated it proportionally, just keeping proper picture proportions. Everything works perfectly. I hope this helps.

    0 讨论(0)
  • 2020-11-27 04:21

    // 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']);
    
    0 讨论(0)
  • 2020-11-27 04:23

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

    0 讨论(0)
  • 2020-11-27 04:25

    Building onto answer from @zeusstl, for multiple images uploaded:

    function img_resize()
    {
    
      $input = 'input-upload-img1'; // Name of input
    
      $maxDim = 400;
      foreach ($_FILES[$input]['tmp_name'] as $file_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 );
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题