上传前使用HTML5调整图片大小

我发现了一些不同的帖子,甚至关于stackoverflow的问题都回答了这个问题。我基本上正在实现与此职位相同的事情。


所以这是我的问题。上传照片时,我还需要提交剩余的表格。这是我的html:


<form id="uploadImageForm" enctype="multipart/form-data">

  <input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />

  <input id="name" value="#{name}" />

  ... a few more inputs ... 

</form>

以前,我不需要调整图像大小,因此我的JavaScript看起来像这样:


window.uploadPhotos = function(url){

    var data = new FormData($("form[id*='uploadImageForm']")[0]);


    $.ajax({

        url: url,

        data: data,

        cache: false,

        contentType: false,

        processData: false,

        type: 'POST',

        success: function(data){

            ... handle error...

            }

        }

    });

};

所有这些都很好用...现在我需要调整图像的大小...如何替换表单中的图像,以便发布调整大小的图像而不是上传的图像?


window.uploadPhotos = function(url){


    var resizedImage;


    // Read in file

    var file = event.target.files[0];


    // Ensure it's an image

    if(file.type.match(/image.*/)) {

        console.log('An image has been loaded');


        // Load the image

        var reader = new FileReader();

        reader.onload = function (readerEvent) {

            var image = new Image();

            image.onload = function (imageEvent) {


                // Resize the image

                var canvas = document.createElement('canvas'),

                    max_size = 1200,

                    width = image.width,

                    height = image.height;

                if (width > height) {

                    if (width > max_size) {

                        height *= max_size / width;

                        width = max_size;

                    }

                } else {

                    if (height > max_size) {

                        width *= max_size / height;

                        height = max_size;

                    }

                }

                canvas.width = width;

                canvas.height = height;

            }

        }

    }




我曾考虑过将文件输入移出表单,并在表单中有一个隐藏的输入,我将的值设置为调整大小后的图像的值...但是我想知道是否可以替换掉那个已经是表格了。


神不在的星期二
浏览 613回答 3
3回答

慕尼黑8549860

这就是我最终要做的,并且效果很好。首先,我将文件输入移到了表单之外,以便不提交:<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" /><form id="uploadImageForm" enctype="multipart/form-data">&nbsp; &nbsp; <input id="name" value="#{name}" />&nbsp; &nbsp; ... a few more inputs ...&nbsp;</form>然后,我将uploadPhotos功能更改为仅处理调整大小:window.uploadPhotos = function(url){&nbsp; &nbsp; // Read in file&nbsp; &nbsp; var file = event.target.files[0];&nbsp; &nbsp; // Ensure it's an image&nbsp; &nbsp; if(file.type.match(/image.*/)) {&nbsp; &nbsp; &nbsp; &nbsp; console.log('An image has been loaded');&nbsp; &nbsp; &nbsp; &nbsp; // Load the image&nbsp; &nbsp; &nbsp; &nbsp; var reader = new FileReader();&nbsp; &nbsp; &nbsp; &nbsp; reader.onload = function (readerEvent) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var image = new Image();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; image.onload = function (imageEvent) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Resize the image&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var canvas = document.createElement('canvas'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max_size = 544,// TODO : pull max size from a site config&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width = image.width,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; height = image.height;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (width > height) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (width > max_size) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; height *= max_size / width;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width = max_size;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (height > max_size) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width *= max_size / height;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; height = max_size;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; canvas.width = width;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; canvas.height = height;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; canvas.getContext('2d').drawImage(image, 0, 0, width, height);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var dataUrl = canvas.toDataURL('image/jpeg');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var resizedImage = dataURLToBlob(dataUrl);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.event.trigger({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "imageResized",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; blob: resizedImage,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: dataUrl&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; image.src = readerEvent.target.result;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; reader.readAsDataURL(file);&nbsp; &nbsp; }};如您所见,我正在使用canvas.toDataURL('image/jpeg');将已调整大小的图像更改为dataUrl adn,然后调用该函数dataURLToBlob(dataUrl);将dataUrl转换为Blob,然后可以将其附加到表单。创建Blob后,我会触发一个自定义事件。这是创建Blob的函数:/* Utility function to convert a canvas to a BLOB */var dataURLToBlob = function(dataURL) {&nbsp; &nbsp; var BASE64_MARKER = ';base64,';&nbsp; &nbsp; if (dataURL.indexOf(BASE64_MARKER) == -1) {&nbsp; &nbsp; &nbsp; &nbsp; var parts = dataURL.split(',');&nbsp; &nbsp; &nbsp; &nbsp; var contentType = parts[0].split(':')[1];&nbsp; &nbsp; &nbsp; &nbsp; var raw = parts[1];&nbsp; &nbsp; &nbsp; &nbsp; return new Blob([raw], {type: contentType});&nbsp; &nbsp; }&nbsp; &nbsp; var parts = dataURL.split(BASE64_MARKER);&nbsp; &nbsp; var contentType = parts[0].split(':')[1];&nbsp; &nbsp; var raw = window.atob(parts[1]);&nbsp; &nbsp; var rawLength = raw.length;&nbsp; &nbsp; var uInt8Array = new Uint8Array(rawLength);&nbsp; &nbsp; for (var i = 0; i < rawLength; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; uInt8Array[i] = raw.charCodeAt(i);&nbsp; &nbsp; }&nbsp; &nbsp; return new Blob([uInt8Array], {type: contentType});}/* End Utility function to convert a canvas to a BLOB&nbsp; &nbsp; &nbsp; */最后,这是我的事件处理程序,该事件处理程序从自定义事件中获取Blob,然后追加表单然后提交。/* Handle image resized events */$(document).on("imageResized", function (event) {&nbsp; &nbsp; var data = new FormData($("form[id*='uploadImageForm']")[0]);&nbsp; &nbsp; if (event.blob && event.url) {&nbsp; &nbsp; &nbsp; &nbsp; data.append('image_data', event.blob);&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: event.url,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: data,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cache: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contentType: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; processData: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function(data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//handle errors...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP