1

我正在尝试使用 javascript 创建上传图像大小调整功能。但是,使用filereader将上传文件转换为 base64,在画布上没有图像。相反,如果我使用外部图像并将其转换为 base64,则该功能就像一个魅力。那会怎么样?问题是什么?

这是我的代码,很长。

//When changes are made to our input field
   $ ('#input-file').change (function (evt) { 
     //The selected file is recovered
     var file = evt.target.files [0];

     //And processFiles function that will resize and send the file to the server is started
     processFiles (file);
   });

   processFiles = function (file) {
     var reader = new FileReader ();

     //When the file has been completely read, the function will be executed ResizeImage
     reader.onloadend = function (evt) {
       //Reader.result represents our base64 encoded file
       ResizeImage (reader.result, file);
     };

     //Allows you to play the file
     reader.readAsDataURL (file);
   };

   ResizeImage = function (data, file) {
     var fileType = file.type,
         maxWidth = 960
         maxHeight = 960;


     //The file is loaded in a <img>
     var image = new Image ();
     image.src = data;

     //Once the image is loaded, the following operations are performed
     image.onload = function () {
       //The ImageSize function calculates the final file size keeping the proportions
       var size = ImageSize (image.width, image.height, maxWidth, maxHeight)
           ImageWidth = size.width,
           imageHeight = size.height,

           //We create a canvas element 
           //canvas = document.createElement ('canvas');
           canvas=document.getElementById('hahaha')

       canvas.width = ImageWidth;
       canvas.height = imageHeight;

       var ctx = canvas.getContext ("2d");

       //DrawImage will allow resizing the image
       //This is our image here
       var img=document.getElementById('haha')
       ctx.drawImage (img, 0, 0, ImageWidth, imageHeight);

       //Allows you to export the contents of the canvas element (our resized image) base64
       data = canvas.toDataURL(fileType);
       alert(data)

       //All the elements used for resizing is suppressed
       delete image;
       delete canvas;

       //SubmitFile (data);
     }
   };


   //Function to resize an image keeping the proportions
   ImageSize = function (width, height, maxWidth, maxHeight) {
     var newWidth = width, 
         newHeight = height;

     if (width> height) {
       if (width> maxWidth) {
         newHeight  = maxWidth / width;
         newWidth = maxWidth;
       }
     else {}
       if (height> maxHeight) {
          newWidth = maxHeight / height;
         newHeight = maxHeight;
       }
     }

     return {width: newWidth, height: newHeight};
   };
4

1 回答 1

1

您可以参考这个小提琴,http://jsfiddle.net/aliasm2k/tAum2/以获得一些想法。它可能会帮助你。这是我实现的一个小提琴,只是为了生成用户选择的图像的缩略图。它使用 FileReader API 来选择文件,然后将缩略图加载到画布上。

就个人而言,我更喜欢经典的 JS,而不是使用 jQuery,并且使用了很多事件处理程序

oFileIn.addEventListener()
oFileReader.addEventListener()
oImage.addEventListener()
于 2013-09-15T07:12:15.270 回答