javascript - 通过 JS 发送时,PHP 图片上传不调整大小

标签 javascript php upload image-uploading image-resizing

我在上传通过 JS 发送到 PHP 的图像时遇到问题。我可以很好地上传图像,但我会在将图像移动到新目的地之前调整图像。我也可以毫无问题地重命名图像。这里的问题实际上只是调整大小

经过大量搜索后,我在 SO 上看到了很多关于此的问题,这就是我到达现在位置的方式,但没有一个能 100% 回答这个问题。如果您知道 SO 上已有问题/答案,请将我链接到正确的文章。

非常感谢任何帮助,谢谢。

这是JS

        var test = document.querySelector('#afile');
        test.addEventListener('change', function() {
            var file = this.files[0];

            var fd = new FormData();
            fd.append('afile', file);
            // These extra params aren't necessary but show that you can include other data.
            fd.append('id', burgerId);

            var xhr = new XMLHttpRequest();
            // why wont this work in the actions directory?
            xhr.open('POST', 'actions/upload.php', true);

            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    var percentComplete = (e.loaded / e.total) * 100;
                    var uploadProcess = document.getElementById('uploadProcess');
                    uploadProcess.setAttribute('style', 'width: ' + percentComplete + '%;');
                    // uploadProcess.innerHTML = parseInt(percentComplete) + '% uploaded';
                }
            };

            xhr.onload = function() {
                if (this.status == 200) {
                    var resp = JSON.parse(this.response);

                    image = 'img/' + resp.newFileName;
                    sessionStorage.setItem('burgerLoc', image);

                    var image = document.createElement('img');
                    image.src = resp.dataUrl;
                    document.body.appendChild(image);
                };
            };

            xhr.send(fd);
            // upImage(id)
        }, false);

这是标记

<input type="file" name="afile" id="afile" accept="image/*"/>

这是PHP

$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];

function getName($str) {
    $parts = explode('.',$str);
    $imgName = str_replace(' ', '_',$parts[0]);
    return $imgName;
}
function getExtension($str) {
    $parts = explode('.',$str);
    $ext = $parts[1];
    return $ext;
}

$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);

if($ext == 'jpg' || $ext == 'jpeg' ) {
    $ext = 'jpg';
    $src = imagecreatefromjpeg($image_tmp);
} else if($ext == 'png') {
    $src = imagecreatefrompng($image_tmp);
} else {
    $src = imagecreatefromgif($image_tmp);
}

$file_content = file_get_contents($image_tmp);
$data_url = 'data:' . $image_type . ';base64,' . base64_encode($file_content);

list($width,$height) = getimagesize($image_tmp);

// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);

imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);

// rename the file
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = '../img/' . $new_file_name;

imagejpeg($img_dest,$new_file_name,100);

move_uploaded_file($image_tmp, $new_file_location);

imagedestroy($src);
imagedestroy($img_dest);

$json = json_encode(array(
    'dataUrl' => $data_url,
    'extension' => $ext,
    'id' => $_REQUEST['id'],
    'name' => $image,
    'newFileName' => $new_file_name,
    'type' => $image_type
));

echo $json;

最佳答案

我可能会尝试在您的 Linux 发行版中安装 ImageMagick 并尝试使用此功能调整图像大小

http://php.net/manual/en/imagick.resizeimage.php

我已经在我的网络服务器上复制了您的脚本...我进行了修改并想出了这个。

最重要的修改是我在文件位置使用了精确的路径,我将 tmp 文件移动到一个真实文件,加载那个真实文件,调整那个真实文件的大小,而不是尝试用 tmp 来做上传的文件。

PHP:

    <?php
    $image = $_FILES['afile']['name'];
    $image_tmp = $_FILES['afile']['tmp_name'];
    $image_type = $_FILES['afile']['type'];

    function getName($str) {
        $parts = explode('.',$str);
        $imgName = str_replace(' ', '_',$parts[0]);
        return $imgName;
    }
    function getExtension($str) {
        $parts = explode('.',$str);
        $ext = $parts[1];
        return $ext;
    }

    $image_name = stripslashes($image);
    $name = getName($image_name);
    $image_ext = getExtension($image_name);
    $ext = strtolower($image_ext);
    $outputfolder = "/var/www/html/wp-content/";
    $new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
    $new_file_location = $outputfolder.$new_file_name;
    move_uploaded_file($image_tmp, $new_file_location);

    if($ext == 'jpg' || $ext == 'jpeg' ) {
        $ext = 'jpg';
        $src = imagecreatefromjpeg($new_file_location);
    } else if($ext == 'png') {
        $src = imagecreatefrompng($new_file_location);
    } else {
        $src = imagecreatefromgif($new_file_location);
    }

    list($width,$height) = getimagesize($new_file_location);

    // width of the main image
    $new_width = 748;
    $new_height = ($height / $width) * $new_width;
    $img_dest = imagecreatetruecolor($new_width,$new_height);

    imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
    $resizedLocation = $outputfolder."resized_".$new_file_name;
    imagejpeg($img_dest,$resizedLocation,100);
    imagedestroy($src);
    imagedestroy($img_dest);


    $file_content = file_get_contents($resizedLocation);
    $data_url = 'data:image/jpeg;base64,' . base64_encode($file_content);

    $json = json_encode(array(
        'dataUrl' => $data_url,
        'extension' => $ext,
        'id' => $_REQUEST['id'],
        'name' => $image,
        'newFileName' => $new_file_name,
        'type' => $image_type
    ));

    echo $json;
    ?>

您的 HTML/JS 保持不变。

现在这对我来说完美无缺,你唯一需要确保的是 $outputfolder 可由 linux 用户写入,执行 php 脚本的网络服务器正在其下运行(通常是网络数据...)

我的网络服务器:

  • CentOS Linux 7.0.1406 版(核心版)
  • php.x86_64 5.4.16-23.el7_0.3
  • apache x86_64 2.4.6

关于javascript - 通过 JS 发送时,PHP 图片上传不调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30017556/

相关文章:

php - 如何将 JavaScript 变量传递给 PHP?

php - SOAP - PHP 可以更改 'ns1' 标记名称吗?

php - 如何将 PHP mysql_fetch_array() 转换为 NSMutableArray? PHP --> Xcode

php - 按比例调整上传图片的大小

javascript - 与 ngOnInit() 和 ngAfterContentInit() 混淆

javascript - 如何版本 MVC JavaScript 包括

java - BufferedOutputStream java :The constructor BufferedOutputStream(FileOutputStream) is undefined 错误

javascript - 图像上传和预览选项,代码不允许显示不同的图像

javascript - 数据表不能使用按列排序或在内容中搜索

php - 如何通过连接表中的 mysql 查询检索最低价格