简体   繁体   English

上传前调整图像大小

[英]Resizing image before upload

I am putting together HTML+JS code to resize picture before automatically submitting form to the server. 在将表单自动提交到服务器之前,我正在整理HTML + JS代码以调整图片大小。 I initially wrote code for automatic form submission and then added logic for image resizing. 我最初编写了自动表单提交的代码,然后添加了图像大小调整的逻辑。 Automatic form submission works but image resizing is not working. 自动表单提交工作但图像大小调整不起作用。 Please provide guidance. 请提供指导。 Thank you in advance. 先感谢您。

<!DOCTYPE html>
<html>
<head>
<title>Flask App</title>    
<meta name="viewport" content="width=device-width, initial-scale=1, user-
scalable=no">  
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 

<script type="text/javascript">
$(function(){
    //JS Code snippet 1 - Automatic form submission on file selection
    $("#file_select").change(function(){
    $("#upload_form").submit();  
    $("#upload_form_div").hide();
    $("#loading").show();

    //JS Code snippet 2 - Image Resizing
    var filesToUpload = inputs.files;

    var img = document.createElement("img");
    var reader = new FileReader();  
    reader.onload = function(e) {img.src = e.target.result}
    reader.readAsDataURL(file);

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var MAX_WIDTH = 800;
    var MAX_HEIGHT = 600;
    var width = img.width;
    var height = img.height;

    if (width > height) {
      if (width > MAX_WIDTH) {
        height *= MAX_WIDTH / width;
        width = MAX_WIDTH;
      }
    } else {
      if (height > MAX_HEIGHT) {
        width *= MAX_HEIGHT / height;
        height = MAX_HEIGHT;
      }
    }
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "upload");
    xhr.send(ctx.toDataURL());

});
});

 </script>

 </head>

 <body>
  <h1 class="logo">Upload Picture</h1>
  <div id="upload_form_div">
   <form id="upload_form" method="POST" enctype="multipart/form-data" action="upload">
    <input type="file" name="file" capture="camera" id="file_select"/>
   </form>
  </div>

  <div id="loading" style="display:none;"> 
     Uploading your picture...
  </div>

 </body>
</html>

UPDATES - (3/28/2014) -Combined code from @yuhua and 'uploader' function in JIC library . 更新 - (2014年3月28日)来自@yuhua的组合代码和JIC库中的 'uploader'功能。 Updated code is below 更新后的代码如下

When I open my webapp in chrome browser on laptop, everything works fine. 当我在笔记本电脑上的Chrome浏览器中打开我的webapp时,一切正常。 However, my resized image is not coming out as expected when I upload image from camera by opening my webapp in chrome browser on iPhone 4s. 但是,当我通过iPhone 4s上的Chrome浏览器打开我的webapp从相机上传图像时,我调整大小的图像并没有按预期出现。 Please find below original and resized image. 请在下面找到原始和调整大小的图像。 Please correct what I am doing wrong. 请纠正我做错了什么。

$("#file_select").change(function (e) {
 var fileReader = new FileReader();
 fileReader.onload = function (e) {
    var img = new Image();
    img.onload = function () {
        var MAX_WIDTH = 3264;
        var MAX_HEIGHT = 2448;
        var width = img.width;
        var height = img.height;

        if (width > height) {
            if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
            }
        } else {
            if (height > MAX_HEIGHT) {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
            }
        }

        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(this, 0, 0, width, height);

        this.src = canvas.toDataURL();
        //document.body.appendChild(this);//remove this if you don't want to show it

        var newImageData = canvas.toDataURL("image/png", 70/100);
         var result_image_obj = new Image();
         result_image_obj.src = newImageData;

          //======= Step 2 - Upload compressed image to server =========

          //Here we set the params like endpoint, var name (server side) and filename
          var server_endpoint = 'upload',
              server_var_name = 'file',
              filename = "new.jpg";

          //This is the callback that will be triggered once the upload is completed
          var callback = function(response){ console.log(response); }

          //Here goes the magic
          $("#result").load(jic.upload(result_image_obj, server_endpoint, server_var_name, filename, callback));



    }
    img.src = e.target.result;
    console.log(img);

}
fileReader.readAsDataURL(e.target.files[0]);
});

原始图像已调整大小的图像上载到服务器

I think your browser might not be supported with .mozGetAsFile() . 我认为.mozGetAsFile()可能不支持您的浏览器。 and i modified your code for an example here: 我在这里修改了你的代码示例:

$("#file_select").change(function (e) {
    var fileReader = new FileReader();
    fileReader.onload = function (e) {
        var img = new Image();
        img.onload = function () {
            var MAX_WIDTH = 100;
            var MAX_HEIGHT = 100;
            var width = img.width;
            var height = img.height;

            if (width > height) {
                if (width > MAX_WIDTH) {
                    height *= MAX_WIDTH / width;
                    width = MAX_WIDTH;
                }
            } else {
                if (height > MAX_HEIGHT) {
                    width *= MAX_HEIGHT / height;
                    height = MAX_HEIGHT;
                }
            }

            var canvas = document.createElement("canvas");
            canvas.width = width;
            canvas.height = height;
            canvas.getContext("2d").drawImage(this, 0, 0, width, height);
            this.src = canvas.toDataURL();
            document.body.appendChild(this);//remove this if you don't want to show it
        }
        img.src = e.target.result;
    }
    fileReader.readAsDataURL(e.target.files[0]);
});

this is a reference: outputting HTML5 canvas as an image, howto? 这是一个参考: 输出HTML5画布作为图像,howto?

UPDATE: 更新:

Take a look bottom of page (Browser support) 看一看页面底部(浏览器支持)

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement

You can try it with PHP rather than HTML and JavaScript. 您可以使用PHP而不是HTML和JavaScript来尝试它。 What we are doing is that we are storing the path of the resized image into the database. 我们正在做的是我们将调整大小的图像的路径存储到数据库中。

public function Resize_image($width = 0, $height = 0, $quality = 90, $filename_in = null, $filename_out = null)
{
    $this->Filename = $filename_in;
    $this->Extension = strtolower($this->Get_file_extension($this->Filename));

    $size = getimagesize($this->Filename);
    $ratio = $size[0] / $size[1];
    if ($ratio >= 1){
        $scale = $width / $size[0];
    } else {
        $scale = $height / $size[1];
    }
    // make sure its not smaller to begin with!
    if ($width >= $size[0] && $height >= $size[1]){
        $scale = 1;
    }

    // echo $fileext;
    switch ($this->Extension)
    {
        case "jpg":
            $im_in = imagecreatefromjpeg($this->Filename);
            $im_out = imagecreatetruecolor($size[0] * $scale, $size[1] * $scale);
            imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $size[0] * $scale, $size[1] * $scale, $size[0], $size[1]);
            imagejpeg($im_out, $filename_out, $quality);
        break;
        case "gif":
            $im_in = imagecreatefromgif($this->Filename);
            $im_out = imagecreatetruecolor($size[0] * $scale, $size[1] * $scale);
            imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $size[0] * $scale, $size[1] * $scale, $size[0], $size[1]);
            imagegif($im_out, $filename_out, $quality);
        break;
        case "png":
            $im_in = imagecreatefrompng($this->Filename);
            $im_out = imagecreatetruecolor($size[0] * $scale, $size[1] * $scale);
            imagealphablending($im_in, true); // setting alpha blending on
            imagesavealpha($im_in, true); // save alphablending setting (important)
            imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $size[0] * $scale, $size[1] * $scale, $size[0], $size[1]);
            imagepng($im_out, $filename_out, 9);
        break;
    }
    imagedestroy($im_out);
    imagedestroy($im_in);
}

Now you can use this function like so to resize images and copy it to the required directory. 现在您可以像这样使用此函数来调整图像大小并将其复制到所需的目录。

Resize_image($width, $height, $quality=90, $filename_in, $filename_out)

For example: 例如:

Resize_image(150, 150, 90, "Directory".$image, "Directory".$image_without_extension."_thumb.".$image_ext); //makes file_thumb.ext

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

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