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

2

2

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?

Lessee answered 12/8, 2017 at 12:48 Comment(2)
Hi bro I found you a solution see my second answer.Vibrations
@Novice, Okay bro. Thanks a lotLessee
V
2

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);
  }
}
Vibrations answered 15/8, 2017 at 17:37 Comment(5)
I had try it. And seems it works. I want to ask. So it's a collaboration between 2 plugins? JavaScript-Load-Image plugin and JavaScript-Canvas-to-BlobLessee
The visible code seems it can only upload jpeg images. Whether gif, png, jpg can also uploaded?Lessee
Ye they work in collabration . For png image types replace "image/jpeg" to "image/png" .You can get image type dynamically if you use currentFile.type thereVibrations
Okay. Thanks a lot. Your answer really helped meLessee
what is the content of the response_upload.php ?Stacistacia
V
0

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!

Vibrations answered 13/8, 2017 at 8:29 Comment(10)
In php I add this : echo '<pre>';print_r($_POST['file']);echo '</pre>';die(); to check the result. But it was too long and did not show anythingLessee
If I try this : echo '<pre>';print_r($_FILES);echo '</pre>';die();, the result empty array like this : <pre>Array ( ) </pre>Lessee
yes $_POST['file'] will not show the image but instead its encoded form so you have to decode it using base64_decode, don't use $_FILES it is supposed to be empty you may add and extra form.append('file', currentFile); but that would give only the original file. So you have to use $_POST['file'] and decode itVibrations
Okay. I have followed your way. Then how can I get the data file to be stored in the folder? I tried echo '<pre>';print_r($fp);echo '</pre>';, the result : <pre>Resource id #3</pre>. It is not a data fileLessee
I want the result like this : Array ( [file] => Array ( [name] => chelsea.jpeg [type] => image/jpeg [tmp_name] => C:\xampp\tmp\php1E31.tmp [error] => 0 [size] => 1244449 ) ) If the result is like that, it can be stored in the folderLessee
Do you have a solution?Lessee
Ohh means you want file in $_FILES . I have not done that but i think that may be possible will check for that and let you knowVibrations
Essentially I want it before it is stored in a folder, the image has fixed orientation. No problem using any way. It is possible to fix orientation in the handle of server sideLessee
Found it see my 2nd answerVibrations
Okay. Thanks a lotLessee

© 2022 - 2024 — McMap. All rights reserved.