通过JS

时间:2015-05-03 18:14:01

标签: 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;

1 个答案:

答案 0 :(得分:2)

我可能会尝试在您的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脚本的webeserver正在运行(通常是web-data ...)

我的网络服务器:

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