上传Javascript中的图像大小缩小器

Upload Image size reducer in Javascript

本文关键字:缩小 图像 Javascript 上传      更新时间:2023-09-26

在将图像上传到服务器之前,JavaScript中是否有任何内置函数可以减小图像大小?我有下面的代码,它上传图像并显示进度。我将把它用于网络应用程序,用户可以点击手机摄像头上的照片。由于移动相机的图像太大,我需要一个功能,可以将图像缩小到大约100x150像素。Javascript代码:

var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('stuimagebyajax',true); /*Flag to check in php so that we know file was uploaded through ajax*/ 
for(var i=0;i<=fileInput.files.length;++i)
    {
    data.append('file[]',fileInput.files[i]);
    }
var request = new XMLHttpRequest();
request.upload.addEventListener('progress',function(event){
    if(event.lengthComputable)
        {
        var percent = Math.round((event.loaded/event.total)*100);
        var progress =  document.getElementById('upload_progress'); 
        var bar = document.getElementById('uploadprogressbar');
        while(progress.hasChildNodes())
            {
            progress.removeChild(progress.firstChild);
            }
        progress.appendChild(document.createTextNode(percent + ' %'));
        bar.value = percent;
        }
    });
/*Load event is fired once the process is cimplete*/    
request.upload.addEventListener('load',function(event){
    document.getElementById('upload_progress').style.display = 'none';
    });
request.upload.addEventListener('error',function(event){
    document.getElementById('upload_progress').innerHTML = "Error uploading file!! Please Try Again.";
    });
request.addEventListener('readystatechange',function(event){
    if(this.readyState==4 && this.status==200)
        {
        console.log('Desired ready state reached');
        var links = document.getElementById('uploaded');
        var uploaded = eval(this.response);
        var div,i;
        for(var i=0;i<uploaded.length;++i)
            {
            console.log(i);
            div=document.createElement('div');
            a=document.createElement('a');
            a.setAttribute('href','stuuplds/'+uploaded[i]);
            a.appendChild(document.createTextNode(uploaded[i]));
            console.log('a is '+a);
            div.appendChild(a);
            links.appendChild(div);
            console.log('div is '+div);
            console.log('links is '+links);
            }
        console.log(this.response);
        }
    else
        {
        console.log('Server replied with HTTP status ' + this.status);
        }
    });
request.open("POST",'uploadprogressbartest.php');
request.setRequestHeader('Cache-Control','no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
console.log(fileInput.files.length);
}
window.addEventListener('load',function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click',handleUpload);
});

这是服务器上的php代码:

<?php
/*print_r($_FILES);*/
if(!empty($_FILES['file'])) /*Here 'file' is the name of array in input     type*/
 {
foreach($_FILES['file']['name'] as $key =>$name)
    {
    if($_FILES['file']['error'][$key]==0 && move_uploaded_file($_FILES['file']['tmp_name'][$key],"stuuplds/{$name}"))
        {
            $uploaded[]=$name;
        }
    }
}
if(!empty($_POST['stuimagebyajax']))
{
die(json_encode($uploaded));
}
/*print_r($uploaded);*/
?>
<!DOCTYPE html PUBLIC>
<html>
<head>
    <script type="text/javascript" src="upload.js"></script>
    <style type="text/css">
        #upload_progress {display:none;}
    </style>
    <title>File Upload</title>
</head>
<body>
    <div id="uploaded">
        <?php
        if(!empty($uploaded))
            {
            foreach($uploaded as $name)
                {
                    echo '<div><a href="stuuplds/' . $name . '">' . $name . '</a></div>';
                }
            }
        ?>

    </div>
    <div id="upload_progress"></div>
    <div>
    <form action="" method="post" enctype="multipart/form-data">
        <div>
            <input type="file" name="file[]" id="file" multiple="multiple" />
            <input type="submit" id="submit" value="Upload" />
            <progress id="uploadprogressbar" value="0" max="100"></progress>
        </div>
    </form>
    </div>
</body>

这可以有效地将文件上传到服务器上的文件夹"stuuplds",同时在上传时显示进度。现在唯一的问题是如何在上传之前将图像大小(大致)减小到100x150像素。有人能帮忙吗。

例如,用中端智能手机相机拍摄的典型图像的分辨率为4160x3120像素。但我只需要100x150像素的图像。所以我不需要任何类型的压缩算法/函数。我想要的是一个javascript函数,它可以从智能手机摄像头上拍摄一张大图像(比如4160x3120像素),并将其缩小到100x150像素,这样图像在光盘上的整体尺寸就会显著减小。

您可以利用HTML5画布在上传到服务器之前调整图像大小。

正确答案记录在这里

HTML5在上传之前预先调整图像大小