在不使用第三方库的情况下在PHP中调整图像大小?

时间:2022-03-12 00:25:50

In one of my applications, I'm using the code snippet below to copy uploaded images to a directory. It works fine but copying large images (> 2MB) takes more time than ideal and I really don't need images this big, so, I'm looking for a way to resize the images. How to achieve this using PHP?

在我的一个应用程序中,我正在使用下面的代码片段将上传的图像复制到目录中。它工作正常,但复制大图像(> 2MB)需要比理想时间更长的时间,我真的不需要这么大的图像,所以,我正在寻找一种方法来调整图像的大小。如何使用PHP实现这一目标?

<?php

$uploadDirectory = 'images/0001/';
$randomNumber = rand(0, 99999); 
$filename = basename($_FILES['userfile']['name']);
$filePath = $uploadDirectory.md5($randomNumber.$filename);

// Check if the file was sent through HTTP POST.

if (is_uploaded_file($_FILES['userfile']['tmp_name']) == true) {

    // Validate the file size, accept files under 5 MB (~5e+6 bytes).

    if ($_FILES['userfile']['size'] <= 5000000) {

        // Move the file to the path specified.

        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $filePath) == true) {

            // ...

        }

    }

}

?>

6 个解决方案

#1


31  

Finally, I've discovered a way that fit my needs. The following snippet will resize an image to the specified width, automatically calculating the height in order to keep the proportion.

最后,我发现了一种符合我需求的方法。以下代码段会将图像调整为指定的宽度,自动计算高度以保持比例。

$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";

copy($_FILES, $resizedDestination);

$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];

$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);

$originalImage = imageCreateFromJPEG($image);

$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);

imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);

imageDestroy($originalImage);
imageDestroy($resizedImage);

To anyone else seeking a complete example, create two files:

对于其他寻求完整示例的人,请创建两个文件:

<!-- send.html -->

<html>

<head>

    <title>Simple File Upload</title>

</head>

<body>

    <center>

        <div style="margin-top:50px; padding:20px; border:1px solid #CECECE;">

            Select an image.

            <br/>
            <br/>

            <form action="receive.php" enctype="multipart/form-data" method="post">
                <input type="file" name="image" size="40">
                <input type="submit" value="Send">
            </form>

        </div>

    </center>

</body>

<?php

// receive.php

$randomNumber = rand(0, 99999);
$uploadDirectory = "images/";
$filename = basename($_FILES['file_contents']['name']);
$destination = $uploadDirectory.md5($randomNumber.$filename).".jpg";

echo "File path:".$filePath."<br/>";

if (is_uploaded_file($_FILES["image"]["tmp_name"]) == true) {

    echo "File successfully received through HTTP POST.<br/>";

    // Validate the file size, accept files under 5 MB (~5e+6 bytes).

    if ($_FILES['image']['size'] <= 5000000) {

        echo "File size: ".$_FILES["image"]["size"]." bytes.<br/>";

        // Resize and save the image.

        $image = $_FILES["image"]["tmp_name"];
        $resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";

        copy($_FILES, $resizedDestination);

        $imageSize = getImageSize($image);
        $imageWidth = $imageSize[0];
        $imageHeight = $imageSize[1];

        $DESIRED_WIDTH = 100;
        $proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);

        $originalImage = imageCreateFromJPEG($image);

        $resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);

        imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
        imageJPEG($resizedImage, $resizedDestination);

        imageDestroy($originalImage);
        imageDestroy($resizedImage);

        // Save the original image.

        if (move_uploaded_file($_FILES['image']['tmp_name'], $destination) == true) {

            echo "Copied the original file to the specified destination.<br/>";

        }

    }

}

?>

#2


8  

I made a function to resize the image by half, the code is below.

我做了一个函数来将图像大小调整一半,代码如下。

        function imgResize($path) {

           $x = getimagesize($path);            
           $width  = $x['0'];
           $height = $x['1'];

           $rs_width  = $width / 2;//resize to half of the original width.
           $rs_height = $height / 2;//resize to half of the original height.

           switch ($x['mime']) {
              case "image/gif":
                 $img = imagecreatefromgif($path);
                 break;
              case "image/jpg":
              case "image/jpeg":
                 $img = imagecreatefromjpeg($path);
                 break;
              case "image/png":
                 $img = imagecreatefrompng($path);
                 break;
           }

           $img_base = imagecreatetruecolor($rs_width, $rs_height);
           imagecopyresized($img_base, $img, 0, 0, 0, 0, $rs_width, $rs_height, $width, $height);

           $path_info = pathinfo($path);    
           switch ($path_info['extension']) {
              case "gif":
                 imagegif($img_base, $path);  
                 break;
            case "jpg":
            case "jpeg":
                 imagejpeg($img_base, $path);
                 break;
              case "png":
                 imagepng($img_base, $path);  
                 break;
           }

        }

and you would be able to call the function with below.

你可以用下面的方法调用这个函数。

$img = imgResize('c:/dir/image.png');

#3


6  

there is 1 very simple image re-size function for all image types that keeps transparency and is very easy to use

对于所有图像类型,有一个非常简单的图像重新调整大小功能,它保持透明度并且非常易于使用

check out :

查看 :

https://github.com/Nimrod007/PHP_image_resize

hope this helps

希望这可以帮助

#4


3  

ImageMagick is the fastest and probably the best way to resize images in PHP. Check out different examples here. This sample shows how to resize and image on upload.

ImageMagick是在PHP中调整图像大小的最快且可能是最好的方法。在这里查看不同的示例。此示例显示如何在上载时调整大小和图像。

#5


0  

You could also use an x*y/width method for resizing and then calling imagecopyresampled() like is shown at http://www.virtualsecrets.com/upload-resize-image-php-mysql.html That page also puts images (after resizing) into mySQL via the PDO.

您还可以使用x * y / width方法进行大小调整,然后调用imagecopyresampled(),如http://www.virtualsecrets.com/upload-resize-image-php-mysql.html所示。该页面还会放置图像(在调整大小之后)通过PDO进入mySQL。

#6


0  

Thanks to Mateus Nunes! i edited his work a bit to get transparent pngs working:

感谢Mateus Nunes!我编辑了他的工作以使透明的png工作:

$source         = $_FILES["..."]["tmp_name"];
$destination    = 'abc/def/ghi.png';
$maxsize        = 45;

$size = getimagesize($source);
$width_orig = $size[0];
$height_orig = $size[1];
unset($size);
$height = $maxsize+1;
$width = $maxsize;
while($height > $maxsize){
    $height = round($width*$height_orig/$width_orig);
    $width = ($height > $maxsize)?--$width:$width;
}
unset($width_orig,$height_orig,$maxsize);
$images_orig    = imagecreatefromstring( file_get_contents($source) );
$photoX         = imagesx($images_orig);
$photoY         = imagesy($images_orig);
$images_fin     = imagecreatetruecolor($width,$height);
imagesavealpha($images_fin,true);
$trans_colour   = imagecolorallocatealpha($images_fin,0,0,0,127);
imagefill($images_fin,0,0,$trans_colour);
unset($trans_colour);
ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY);
unset($photoX,$photoY,$width,$height);
imagepng($images_fin,$destination);
unset($destination);
ImageDestroy($images_orig);
ImageDestroy($images_fin);

#1


31  

Finally, I've discovered a way that fit my needs. The following snippet will resize an image to the specified width, automatically calculating the height in order to keep the proportion.

最后,我发现了一种符合我需求的方法。以下代码段会将图像调整为指定的宽度,自动计算高度以保持比例。

$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";

copy($_FILES, $resizedDestination);

$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];

$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);

$originalImage = imageCreateFromJPEG($image);

$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);

imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);

imageDestroy($originalImage);
imageDestroy($resizedImage);

To anyone else seeking a complete example, create two files:

对于其他寻求完整示例的人,请创建两个文件:

<!-- send.html -->

<html>

<head>

    <title>Simple File Upload</title>

</head>

<body>

    <center>

        <div style="margin-top:50px; padding:20px; border:1px solid #CECECE;">

            Select an image.

            <br/>
            <br/>

            <form action="receive.php" enctype="multipart/form-data" method="post">
                <input type="file" name="image" size="40">
                <input type="submit" value="Send">
            </form>

        </div>

    </center>

</body>

<?php

// receive.php

$randomNumber = rand(0, 99999);
$uploadDirectory = "images/";
$filename = basename($_FILES['file_contents']['name']);
$destination = $uploadDirectory.md5($randomNumber.$filename).".jpg";

echo "File path:".$filePath."<br/>";

if (is_uploaded_file($_FILES["image"]["tmp_name"]) == true) {

    echo "File successfully received through HTTP POST.<br/>";

    // Validate the file size, accept files under 5 MB (~5e+6 bytes).

    if ($_FILES['image']['size'] <= 5000000) {

        echo "File size: ".$_FILES["image"]["size"]." bytes.<br/>";

        // Resize and save the image.

        $image = $_FILES["image"]["tmp_name"];
        $resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";

        copy($_FILES, $resizedDestination);

        $imageSize = getImageSize($image);
        $imageWidth = $imageSize[0];
        $imageHeight = $imageSize[1];

        $DESIRED_WIDTH = 100;
        $proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);

        $originalImage = imageCreateFromJPEG($image);

        $resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);

        imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
        imageJPEG($resizedImage, $resizedDestination);

        imageDestroy($originalImage);
        imageDestroy($resizedImage);

        // Save the original image.

        if (move_uploaded_file($_FILES['image']['tmp_name'], $destination) == true) {

            echo "Copied the original file to the specified destination.<br/>";

        }

    }

}

?>

#2


8  

I made a function to resize the image by half, the code is below.

我做了一个函数来将图像大小调整一半,代码如下。

        function imgResize($path) {

           $x = getimagesize($path);            
           $width  = $x['0'];
           $height = $x['1'];

           $rs_width  = $width / 2;//resize to half of the original width.
           $rs_height = $height / 2;//resize to half of the original height.

           switch ($x['mime']) {
              case "image/gif":
                 $img = imagecreatefromgif($path);
                 break;
              case "image/jpg":
              case "image/jpeg":
                 $img = imagecreatefromjpeg($path);
                 break;
              case "image/png":
                 $img = imagecreatefrompng($path);
                 break;
           }

           $img_base = imagecreatetruecolor($rs_width, $rs_height);
           imagecopyresized($img_base, $img, 0, 0, 0, 0, $rs_width, $rs_height, $width, $height);

           $path_info = pathinfo($path);    
           switch ($path_info['extension']) {
              case "gif":
                 imagegif($img_base, $path);  
                 break;
            case "jpg":
            case "jpeg":
                 imagejpeg($img_base, $path);
                 break;
              case "png":
                 imagepng($img_base, $path);  
                 break;
           }

        }

and you would be able to call the function with below.

你可以用下面的方法调用这个函数。

$img = imgResize('c:/dir/image.png');

#3


6  

there is 1 very simple image re-size function for all image types that keeps transparency and is very easy to use

对于所有图像类型,有一个非常简单的图像重新调整大小功能,它保持透明度并且非常易于使用

check out :

查看 :

https://github.com/Nimrod007/PHP_image_resize

hope this helps

希望这可以帮助

#4


3  

ImageMagick is the fastest and probably the best way to resize images in PHP. Check out different examples here. This sample shows how to resize and image on upload.

ImageMagick是在PHP中调整图像大小的最快且可能是最好的方法。在这里查看不同的示例。此示例显示如何在上载时调整大小和图像。

#5


0  

You could also use an x*y/width method for resizing and then calling imagecopyresampled() like is shown at http://www.virtualsecrets.com/upload-resize-image-php-mysql.html That page also puts images (after resizing) into mySQL via the PDO.

您还可以使用x * y / width方法进行大小调整,然后调用imagecopyresampled(),如http://www.virtualsecrets.com/upload-resize-image-php-mysql.html所示。该页面还会放置图像(在调整大小之后)通过PDO进入mySQL。

#6


0  

Thanks to Mateus Nunes! i edited his work a bit to get transparent pngs working:

感谢Mateus Nunes!我编辑了他的工作以使透明的png工作:

$source         = $_FILES["..."]["tmp_name"];
$destination    = 'abc/def/ghi.png';
$maxsize        = 45;

$size = getimagesize($source);
$width_orig = $size[0];
$height_orig = $size[1];
unset($size);
$height = $maxsize+1;
$width = $maxsize;
while($height > $maxsize){
    $height = round($width*$height_orig/$width_orig);
    $width = ($height > $maxsize)?--$width:$width;
}
unset($width_orig,$height_orig,$maxsize);
$images_orig    = imagecreatefromstring( file_get_contents($source) );
$photoX         = imagesx($images_orig);
$photoY         = imagesy($images_orig);
$images_fin     = imagecreatetruecolor($width,$height);
imagesavealpha($images_fin,true);
$trans_colour   = imagecolorallocatealpha($images_fin,0,0,0,127);
imagefill($images_fin,0,0,$trans_colour);
unset($trans_colour);
ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY);
unset($photoX,$photoY,$width,$height);
imagepng($images_fin,$destination);
unset($destination);
ImageDestroy($images_orig);
ImageDestroy($images_fin);