How do I fix orientation (upload image) before saving in folder (Javascript)?

时间秒杀一切 提交于 2019-12-28 04:33:10

问题


I try this reference : https://github.com/blueimp/JavaScript-Load-Image

I try like this : https://jsfiddle.net/oscar11/gazo3jc8/

My code javascript like this :

$(function () {
  var result = $('#result')
  var currentFile

  function updateResults (img, data) {
    var content
    if (!(img.src || img instanceof HTMLCanvasElement)) {
      content = $('<span>Loading image file failed</span>')
    } else {
      content = $('<a target="_blank">').append(img)
        .attr('download', currentFile.name)
        .attr('href', img.src || img.toDataURL())

      var form = new FormData();
      form.append('file', currentFile);

       $.ajax({
                    url:'response_upload.php',
                    type:'POST',
                    data:form,
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        console.log(response);
                    },
                    error: function () {
                        console.log(error)
                    },
                });
    }
    result.children().replaceWith(content)
  }

  function displayImage (file, options) {
    currentFile = file
    if (!loadImage(
        file,
        updateResults,
        options
      )) {
      result.children().replaceWith(
        $('<span>' +
          'Your browser does not support the URL or FileReader API.' +
          '</span>')
      )
    }
  }

  function dropChangeHandler (e) {
    e.preventDefault()
    e = e.originalEvent
    var target = e.dataTransfer || e.target
    var file = target && target.files && target.files[0]
    var options = {
      maxWidth: result.width(),
      canvas: true,
      pixelRatio: window.devicePixelRatio,
      downsamplingRatio: 0.5,
      orientation: true
    }
    if (!file) {
      return
    }
    displayImage(file, options)
  }

  // Hide URL/FileReader API requirement message in capable browsers:
  if (window.createObjectURL || window.URL || window.webkitURL ||
      window.FileReader) {
    result.children().hide()
  }

  $('#file-input').on('change', dropChangeHandler)
})

If I uploaded the image, the image saved in the folder still does not use the image that is in its orientation set. I want when I upload a picture, the image stored in the folder is the image that has been set its orientation

It seems that the currentFile sent via ajax is the unmodified currentfFile. How do I get the modified currentFile?


回答1:


After some researching little bit I found the solution thanks to this great plugin https://github.com/blueimp/JavaScript-Canvas-to-Blob . ( canvas-to-blob.js )

This plugin will convert your canvas to a Blob directly server would see it as if it were an actual file and will get the new(modified) file in you $_FILES array. All you need is call toBlob on the canvas object (img). After that you would get your blob which you then can send in FormData. Below is your updated updateResults() function

function updateResults (img, data) {
  var content
  if (!(img.src || img instanceof HTMLCanvasElement)) {
    content = $('<span>Loading image file failed</span>')
  } 
  else 
  {
       content = $('<a target="_blank">').append(img)
      .attr('download', currentFile.name)
      .attr('href', img.src || img.toDataURL())

      img.toBlob(
           function (blob) {
               var form = new FormData();
               form.append('file', blob, currentFile.name);

               $.ajax({
                  url:'response_upload.php',
                  type:'POST',
                  data:form,
                  processData: false,
                  contentType: false,
                  success: function (response) {
                    console.log(response);
                  },
                  error: function () {
                    console.log(error)
                  },
               });

           },'image/jpeg'   
      );
      result.children().replaceWith(content);
  }
}



回答2:


You want to change some things about image (dimensions, roataion etc) and upload it on to the server but the problem here is that ImageLoad plugin will give the modified image as an canvas means it won't modify the original file selected in <input type="file" id="file-input">. Since you are sending the file input object in form.append('file', currentFile); your modified file wont get sent but just the original

How to fix?

This is particularity hard you (or plugin) cannot modify anything on <input type="file" id="file-input"> due to browser restrictions neither you can send canvas directly to the server so the only way (used and works great) is to send the data URI of the image as a regular text and then decode it on the server, write it to a file.You might also want to send the original file name since a data URI is pure content and doesn't hold file name

Change

  form.append('file', currentFile);

To

  form.append('file', img.toDataURL() );        // data:image/png;base64,iVBO ...
  form.append('file_name',  currentFile.name ); // filename 

PHP

  $img_data=substr( $_POST['file'] , strpos( $_POST['file'] , "," )+1); 
  //removes preamble ( like data:image/png;base64,)
  $img_name=$_POST['file_name'];

  $decodedData=base64_decode($img_data);

  $fp = fopen( $img_name , 'wb' );
  fwrite($fp, $decodedData);
  fclose($fp );

Good luck!



来源:https://stackoverflow.com/questions/45650465/how-do-i-fix-orientation-upload-image-before-saving-in-folder-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!