在PHP中调整图像大小而不使用第三方库?

在PHP中调整图像大小而不使用第三方库?,php,image,image-resizing,Php,Image,Image Resizing,在我的一个应用程序中,我使用下面的代码片段将上传的图像复制到一个目录。它工作得很好,但复制大图像(>2MB)需要比理想情况更多的时间,我真的不需要这么大的图像,所以,我正在寻找一种方法来调整图像的大小。如何使用PHP实现这一点 <?php $uploadDirectory = 'images/0001/'; $randomNumber = rand(0, 99999); $filename = basename($_FILES['userfile']['name']); $filePa

在我的一个应用程序中,我使用下面的代码片段将上传的图像复制到一个目录。它工作得很好,但复制大图像(>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) {

            // ...

        }

    }

}

?>

是PHP中调整图像大小的最快、可能也是最好的方法。看看不同的例子。此示例演示了如何使用。

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

$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);
对于任何其他寻求完整示例的人,请创建两个文件:

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

简单文件上传
选择一个图像。




您也可以使用x*y/width方法来调整大小,然后调用imagecopyresampled(),如该页面所示,还可以通过PDO将图像(调整大小后)放入mySQL。

我制作了一个小函数来调整图像大小,函数如下:

function resize_image($path, $width, $height, $update = false) {
   $size  = getimagesize($path);// [width, height, type index]
   $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
   if ( array_key_exists($size['2'], $types) ) {
      $load        = 'imagecreatefrom' . $types[$size['2']];
      $save        = 'image'           . $types[$size['2']];
      $image       = $load($path);
      $resized     = imagecreatetruecolor($width, $height);
      $transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
      imagesavealpha($resized, true);
      imagefill($resized, 0, 0, $transparent);
      imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $size['0'], $size['1']);
      imagedestroy($image);
      return $save($resized, $update ? $path : null);
   }
}
下面是您如何使用它:

if ( resize_image('dir/image.png', 50, 50, true) ) {// resize image.png to 50x50
   echo 'image resized!';
}

有一个非常简单的图像重新大小的所有图像类型,保持透明度,是非常容易使用的功能

退房:

希望这有帮助

感谢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);

上传前检查文件大小,可能重复我已经看过大多数教程,我创建了自己的代码来调整JPEG图像大小,但问题是此代码链接到iphone应用程序,所以我有点困惑,如果可以的话,你们中的任何人都可以使用我粘贴的代码提供一些示例代码@Mateununes我看不到您在提供的代码中执行调整大小的任何地方。向我们展示您的is_upload_file()函数和move_upload_file函数。它是否工作与iphone无关。PHP是服务器端。既然可以使用像GD这样经过验证的库,为什么还要执行另一个进程呢?@Overv Speed。GD相当慢。脚本不错,但是$img_base返回了一个资源id。现在我们如何保存修改后的图像?更新后也保存图像。脚本不错,不过我认为它也需要一个案例“jpg”,因为它不认识这个扩展。当我遇到这个问题时,我已经添加了jpg案例。我建议使用
imagecopyresampled
,而不是
imagecopyresized
(相同的签名),它允许在调整大小时平滑边缘(特别是PNG)。这将禁用PNG中的透明度files@Nimrod007,我们可以用白色来代替透明。这将是“安全的”第三行实际做什么?您应该指出复制函数要求允许在php.ini中打开url。是否有一个回调函数,用于图像大小函数完成时?例如我只想在图像大小调整时运行代码。
$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);