繁体   English   中英

使用Javascript将图像转换为灰度并降低其分辨率

[英]Convert image to grayscale and reduce its resolution with Javascript

我有以下代码,允许用户拍摄照片,然后将其上传到服务器 (最终将进行进一步的图像处理)。

 <form action="/submitphoto" method="post"> <input type="file" capture="camera" accept="image/*" id="cameraInput" name="photo" onchange="this.form.submit()" /> </form> 

有用。 但是很多时候(尤其是如今使用高像素手机摄像头):

  • 图像文件将很大(因此上传时间很长!),并且对我的应用程序来说不必要的分辨率过高,例如4000x6000像素

  • 图像将是彩色的,而我只需要灰度

当然我可以做JPG尺寸减小(例如4000x6000像素到800x1200像素)+ color =>服务器上的灰度处理,但是过高的上载时间/服务器处理时间/带宽将被浪费

问题:在Java中提交form之前,如何降低使用<input type="file" capture="camera" ...>拍摄的JPG图像的分辨率并将其转换为灰度?

在下面的示例中,我使用MarvinJ调整大小并将图像转换为灰度,然后再上传到服务器。 这两个操作在客户端的javascript中执行,如下所示:

 Marvin.scale(image.clone(), image, 200);
 Marvin.grayScale(image.clone(), image);

我还包括一个上传按钮的实现和一种将图像发布到服务器的方法。

您可以尝试该代码段。 希望对您有帮助。

 /*********************************************** * GLOBAL VARS **********************************************/ var image = new MarvinImage(); /*********************************************** * FILE CHOOSER AND UPLOAD **********************************************/ $('#fileUpload').change(function (event) { form = new FormData(); form.append('name', event.target.files[0].name); reader = new FileReader(); reader.readAsDataURL(event.target.files[0]); reader.onload = function(){ image.load(reader.result, imageLoaded); }; }); function resizeAndSendToServer(){ $("#divServerResponse").html("uploading..."); $.ajax({ method: 'POST', url: 'https://www.marvinj.org/backoffice/imageUpload.php', data: form, enctype: 'multipart/form-data', contentType: false, processData: false, success: function (resp) { $("#divServerResponse").html("SERVER RESPONSE (NEW IMAGE):<br/><img src='"+resp+"' style='max-width:400px'></img>"); }, error: function (data) { console.log("error:"+error); console.log(data); }, }); }; /*********************************************** * IMAGE MANIPULATION **********************************************/ function imageLoaded(){ Marvin.scale(image.clone(), image, 200); Marvin.grayScale(image.clone(), image); form.append("blob", image.toBlob()); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script> <form id="form" action='/backoffice/imageUpload.php' style='margin:auto;' method='post' enctype='multipart/form-data'> <input type='file' id='fileUpload' class='upload' name='userfile'/> </form><br/> <button type="button" onclick="resizeAndSendToServer()">Resize and Send to Server</button><br/><br/> <div id="divServerResponse"> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM