【问题标题】:Resize images in PHP without using third-party libraries?在不使用第三方库的情况下在 PHP 中调整图像大小?
【发布时间】:2012-03-27 21:05:25
【问题描述】:

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

            // ...

        }

    }

}

?>

【问题讨论】:

  • 检查文件大小上传,stackoverflow.com/questions/4112575/…
  • Resize image on server的可能重复
  • 我已经看过大部分教程,我已经创建了自己的代码来调整 JPEG 图像的大小,但问题是这段代码链接到一个 iphone 应用程序,所以我是有点困惑,如果你们中的任何人都可以使用我粘贴的代码提供一些示例代码!
  • @MateusNunes 我没有看到您在提供的代码中执行调整大小的任何地方。向我们展示您的 is_uploaded_file() 函数和 move_uploaded_file 函数。它的工作与iphone无关。 PHP是服务器端。

标签: php image image-resizing


【解决方案1】:

我做了一个调整图片大小的小功能,功能如下:

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!';
}

【讨论】:

  • 不错的脚本,但 $img_base 正在返回资源 ID。现在我们如何保存修改后的图像?
  • 已更新以保存图像。
  • 不错的脚本,虽然我认为它也需要一个大小写“jpg”,因为它无法识别该扩展名。
  • 我在遇到这个问题时也添加了 jpg 案例
  • 我建议使用imagecopyresampled 而不是imagecopyresized(相同的签名),它可以在调整大小时使边缘更平滑(尤其是对于png)。
【解决方案2】:

最后,我发现了一种适合我需要的方法。下面的sn-p会将图片resize到指定的宽度,自动计算高度以保持比例。

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

<?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/>";

        }

    }

}

?>

【讨论】:

  • 这将禁用 PNG 文件的透明度
  • @Nimrod007,我们可以用白色替换透明度。那将是“安全的”
  • 第 3 行实际上是做什么的?
  • 你应该在php.ini中指明复制功能需要allow_url_open
【解决方案3】:

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

【讨论】:

    【解决方案4】:

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

    退房:

    https://github.com/Nimrod007/PHP_image_resize

    希望对你有帮助

    【讨论】:

    • 图片尺寸功能完成时有回调函数吗?例如...我想仅在图像调整大小时运行代码。
    【解决方案5】:

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

    【讨论】:

      【解决方案6】:

      ImageMagick 是在 PHP 中调整图像大小的最快也可能是最好的方法。查看不同的示例here。此示例显示如何resize and image on upload

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多