{"id":8359,"date":"2016-07-24T11:11:14","date_gmt":"2016-07-24T10:11:14","guid":{"rendered":"http:\/\/www.wjst.de\/blog\/?p=8359"},"modified":"2019-04-07T07:35:36","modified_gmt":"2019-04-07T06:35:36","slug":"resize-image-before-upload","status":"publish","type":"post","link":"https:\/\/www.wjst.de\/blog\/sciencesurf\/2016\/07\/resize-image-before-upload\/","title":{"rendered":"Resize and preserve image orientation before upload"},"content":{"rendered":"<p>I need to\u00a0downscale images on mobile phones to save bandwidth. Here is my code based on <a href=\"http:\/\/based on http:\/\/www.codeforest.net\/html5-image-upload-resize-and-crop\">http:\/\/www.codeforest.net\/html5-image-upload-resize-and-crop<\/a>. No need for any complicated plugins. Take care of some security holes&#8230;<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;html&gt;\r\n&lt;head&gt;\r\n&lt;script src=&quot;jquery-1.11.1.min.js&quot;&gt;&lt;\/script&gt;\r\n&lt;?php if ($_POST) {\r\n  $img = $_POST&#x5B;'image'];\r\n  $img = str_replace('data:image\/jpeg;base64,', '', $img);\r\n  $img = str_replace(' ', '+', $img);\r\n  $data = base64_decode($img);\r\n  $file = 'cache\/' . uniqid() . '.jpg';\r\n  file_put_contents($file, $data);\r\n}\r\n?&gt;\r\n&lt;\/head&gt;\r\n\r\n&lt;body&gt;\r\n&lt;form&gt;\r\n&lt;input type=&quot;text&quot; value=&quot;&quot; name=&quot;text&quot; id=&quot;text&quot;\/&gt;\r\n&lt;input type=&quot;file&quot; name=&quot;filesToUpload&#x5B;]&quot; id=&quot;filesToUpload&quot; multiple=&quot;multiple&quot; \/&gt;\r\n&lt;input type=&quot;button&quot; id=&quot;button&quot; value=&quot;submit&quot;&gt;\r\n&lt;\/form&gt;\r\n\r\n&lt;script&gt;\r\n$('#button').click(function(){\r\n\r\n if (window.File &amp;&amp; window.FileReader &amp;&amp; window.FileList &amp;&amp; window.Blob) {\r\n   var files = document.getElementById('filesToUpload').files;\r\n   for(var i = 0; i &lt; files.length; i++) {\r\n     resizeAndUpload(files&#x5B;i]);\r\n   }\r\n }\r\n else {\r\n   alert('not supported');\r\n }\r\n});\r\n\r\nfunction resizeAndUpload(file) {\r\n  var reader = new FileReader();\r\n  reader.onloadend = function() {\r\n    var tempImg = new Image();\r\n    tempImg.src = reader.result;\r\n    tempImg.onload = function() {\r\n      var max_width = 500;\r\n      var max_height = 500;\r\n      var tempW = tempImg.width;\r\n      var tempH = tempImg.height;\r\n      if (tempW &gt; tempH) {\r\n        if (tempW &gt; max_width) {\r\n          tempH *= max_width \/ tempW;\r\n          tempW = max_width;\r\n        }\r\n      }\r\n      else {\r\n      if (tempH &gt; max_height) {\r\n        tempW *= max_height \/ tempH;\r\n        tempH = max_height;\r\n      }\r\n   }\r\n   var canvas = document.createElement('canvas');\r\n   canvas.width = tempW;\r\n   canvas.height = tempH;\r\n   var ctx = canvas.getContext(&quot;2d&quot;);\r\n   ctx.drawImage(this, 0, 0, tempW, tempH);\r\n   var dataURL = canvas.toDataURL(&quot;image\/jpeg&quot;);\r\n   var xhr = new XMLHttpRequest();\r\n   xhr.onreadystatechange = function() {\r\n     if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) {\r\n       location.reload();\r\n     }\r\n   };\r\n   xhr.open('POST', 'index.php', true);\r\n   xhr.setRequestHeader(&quot;Content-type&quot;,&quot;application\/x-www-form-urlencoded&quot;);\r\n   var input = document.getElementById(&quot;text&quot;);\r\n   var inputData = encodeURIComponent(input.value);\r\n   var data = 'text=' + inputData + '&amp;image=' + dataURL;\r\n   xhr.send(data);\r\n   }\r\n }\r\n}\r\n&lt;\/script&gt;\r\n\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>The big issue when running that with multiple phones is image orientation.<br \/>\nTo save computing power many mobiles are just save their sensor data without caring about too much about orientation as long as orientation is written in the exif tag.<br \/>\nHere are the 8 possible orientations<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\nORIENTATION\r\n\tTOP\tLEFT    \r\n1\ttop\tleft\r\n2\ttop\tright\r\n3\tbottom\tright\r\n4\tbottom\tleft\r\n5\tleft\ttop\r\n6\tright\ttop\r\n7\tright\tbottom\r\n8\tleft\tbottom\r\n<\/pre>\n<p>I therefore added canvas rotation \/ flipping after getting image orientation from <a href=\"https:\/\/github.com\/blueimp\/JavaScript-Load-Image\">https:\/\/github.com\/blueimp\/JavaScript-Load-Image<\/a>. The revised function now looks like<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\nfunction resizeAndUpload(file) {\r\n  var reader = new FileReader();\r\n  reader.onloadend = function() {\r\n    var can = document.createElement('canvas'); \r\n    var ctx = can.getContext(&quot;2d&quot;);\r\n    var thisImage = new Image();\r\n    thisImage.src = reader.result;\r\n    thisImage.onload = function() {    \r\n      var max_width = 1500;\r\n      var max_height = 1500;\r\n      var tempW = thisImage.width;\r\n      var tempH = thisImage.height;\r\n      if (tempW &gt; tempH) {\r\n        if (tempW &gt; max_width) {\r\n          tempH *= max_width \/ tempW;\r\n          tempW = max_width;\r\n        }\r\n      }\r\n      else {\r\n        if (tempH &gt; max_height) {\r\n          tempW *= max_height \/ tempH;\r\n          tempH = max_height;\r\n        }\r\n      }\r\n      can.width  = tempW;\r\n      can.height = tempH;\r\n      ctx.save();\r\n      var width  = can.width;  var styleWidth  = can.style.width;\r\n      var height = can.height; var styleHeight = can.style.height;\r\n      if (orientation&gt;1) {\r\n        if (orientation &gt; 4) {\r\n          can.width  = height; can.style.width  = styleHeight;\r\n          can.height = width;  can.style.height = styleWidth;\r\n        }\r\n        switch (orientation) {\r\n          case 2: ctx.translate(width, 0);     ctx.scale(-1,1); break;\r\n          case 3: ctx.translate(width,height); ctx.rotate(Math.PI); break;\r\n          case 4: ctx.translate(0,height);     ctx.scale(1,-1); break;\r\n          case 5: ctx.rotate(0.5 * Math.PI);   ctx.scale(1,-1); break;\r\n          case 6: ctx.rotate(0.5 * Math.PI);   ctx.translate(0,-height); break;\r\n          case 7: ctx.rotate(0.5 * Math.PI);   ctx.translate(width,-height); ctx.scale(-1,1); break;\r\n          case 8: ctx.rotate(-0.5 * Math.PI);  ctx.translate(-width,0); break;\r\n        }\r\n      }\r\n      ctx.drawImage(thisImage,0,0,tempW,tempH);\r\n      ctx.restore();\r\n    }\r\n    var dataURL = canvas.toDataURL(&quot;image\/jpeg&quot;);\r\n    var xhr = new XMLHttpRequest();\r\n    xhr.onreadystatechange = function() {\r\n      if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) {\r\n        location.reload();\r\n      }\r\n    };\r\n    xhr.open('POST', 'index.php', true);\r\n    xhr.setRequestHeader(&quot;Content-type&quot;,&quot;application\/x-www-form-urlencoded&quot;);\r\n    var input = document.getElementById(&quot;text&quot;);\r\n    var inputData = encodeURIComponent(input.value);\r\n    var data = 'text=' + inputData + '&amp;image=' + dataURL;\r\n    xhr.send(data);\r\n  }\r\n}\r\n<\/pre>\n\n<p>&nbsp;<\/p>\n<div class=\"bottom-note\">\n  <span class=\"mod1\">CC-BY-NC Science Surf , accessed 06.04.2026<\/span>\n <\/div>","protected":false},"excerpt":{"rendered":"<p>I need to\u00a0downscale images on mobile phones to save bandwidth. Here is my code based on http:\/\/www.codeforest.net\/html5-image-upload-resize-and-crop. No need for any complicated plugins. Take care of some security holes&#8230; &lt;html&gt; &lt;head&gt; &lt;script src=&quot;jquery-1.11.1.min.js&quot;&gt;&lt;\/script&gt; &lt;?php if ($_POST) { $img = $_POST&#x5B;&#8217;image&#8217;]; $img = str_replace(&#8216;data:image\/jpeg;base64,&#8217;, &#8221;, $img); $img = str_replace(&#8216; &#8216;, &#8216;+&#8217;, $img); $data = base64_decode($img); $file &hellip; <a href=\"https:\/\/www.wjst.de\/blog\/sciencesurf\/2016\/07\/resize-image-before-upload\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Resize and preserve image orientation before upload<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-8359","post","type-post","status-publish","format-standard","hentry","category-computer-software"],"_links":{"self":[{"href":"https:\/\/www.wjst.de\/blog\/wp-json\/wp\/v2\/posts\/8359","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wjst.de\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wjst.de\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wjst.de\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wjst.de\/blog\/wp-json\/wp\/v2\/comments?post=8359"}],"version-history":[{"count":11,"href":"https:\/\/www.wjst.de\/blog\/wp-json\/wp\/v2\/posts\/8359\/revisions"}],"predecessor-version":[{"id":12350,"href":"https:\/\/www.wjst.de\/blog\/wp-json\/wp\/v2\/posts\/8359\/revisions\/12350"}],"wp:attachment":[{"href":"https:\/\/www.wjst.de\/blog\/wp-json\/wp\/v2\/media?parent=8359"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wjst.de\/blog\/wp-json\/wp\/v2\/categories?post=8359"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wjst.de\/blog\/wp-json\/wp\/v2\/tags?post=8359"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}