HTML5 Pre-resize images before uploading

前端 未结 10 2522
野的像风
野的像风 2020-11-22 15:53

Here\'s a noodle scratcher.

Bearing in mind we have HTML5 local storage and xhr v2 and what not. I was wondering if anyone could find a work

10条回答
  •  猫巷女王i
    2020-11-22 16:16

    Modification to the answer by Justin that works for me:

    1. Added img.onload
    2. Expand the POST request with a real example
    
    function handleFiles()
    {
        var dataurl = null;
        var filesToUpload = document.getElementById('photo').files;
        var file = filesToUpload[0];
    
        // Create an image
        var img = document.createElement("img");
        // Create a file reader
        var reader = new FileReader();
        // Set the image once loaded into file reader
        reader.onload = function(e)
        {
            img.src = e.target.result;
    
            img.onload = function () {
                var canvas = document.createElement("canvas");
                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);
    
                dataurl = canvas.toDataURL("image/jpeg");
    
                // Post the data
                var fd = new FormData();
                fd.append("name", "some_filename.jpg");
                fd.append("image", dataurl);
                fd.append("info", "lah_de_dah");
                $.ajax({
                    url: '/ajax_photo',
                    data: fd,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    success: function(data){
                        $('#form_photo')[0].reset();
                        location.reload();
                    }
                });
            } // img.onload
        }
        // Load files into file reader
        reader.readAsDataURL(file);
    }
    

提交回复
热议问题