Resizing an image before uploading

charpi

macrumors regular
Original poster
Sep 30, 2006
203
10
Hello, this issue is frustrating the hell out of me :(

I can't seem to resize my file before uploading it.

Relevant code

Code:
function submitFile(){
  var file = resize(document.getElementById('askForm').files[0]);
  console.log(file);
  var formData = new FormData();
  formData.append('file',file);
  var xhr = new XMLHttpRequest();
  xhr.open('POST',"../server/upload.php",true);
  xhr.onload = function(e){
    alert(this.response);
    addImage(this.response); // this leads to another function that is working already
  };
  xhr.send(formData);
}

function resize(MYFILE){
    var file = MYFILE;
    var c = document.createElement('canvas');
    var ctx = c.getContext('2d'),
    reader = new FileReader;

    reader.onload = function(event) {
      var img = new Image;
      img.src = event.target.result;

      var MAX_WIDTH = 800;
      var MAX_HEIGHT = 600;
      var width = img.width;
      var height = img.height;

      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }
      c.width = width;
      c.height = height;
      ctx.drawImage(img, 0, 0, width, height);

    };

    reader.readAsDataURL(file);
    var dataurl = c.toDataURI("image/png");
    return dataurl;
  }
Problem is I am getting (I think) the correct dataurl file (I did a console.log and had this longish string), but I can't convert it to ajax readable format.

If I just had (without the resize function)

Code:
function submitFile(){
  var file = document.getElementById('askForm').files[0];
  console.log(file);
  var formData = new FormData();
  formData.append('file',file);
  var xhr = new XMLHttpRequest();
  xhr.open('POST',"../server/upload.php",true);
  xhr.onload = function(e){
    alert(this.response);
    addImage(this.response);
  };
  xhr.send(formData);
}
Everything works well, just that the image is not resized!

PHP Code:
PHP:
<?php
$name = time();
if ($_FILES["file"]["error"] > 0)
{
	echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{

    if (file_exists("../images/questions/" . $name))
    {
    	echo $_FILES["file"]["name"] . " already exists. ";
    }
    else
    {
    	move_uploaded_file($_FILES["file"]["tmp_name"],"../images/questions/" . $name);
    	echo $name;
    }
}
?>
So basically I need to resize the image before uploading. Solution preferably not to much changes. Is there just some "var newFile = resize(oldFile, 800,600) function I could use without changing the format of the file?

Thank you :)
 

SrWebDeveloper

macrumors 68000
Dec 7, 2007
1,872
2
Alexandria, VA, USA
Maybe this:

Code:
c.width = width;
      c.height = height;
      ctx.drawImage(img, 0, 0, width, height);
Should be this:

Code:
c.width = width;
      c.height = height;
      ctx.drawImage(img, 0, 0, c.width, c.height);
And of course the JS creates a .PNG based on your source. Beyond that, we'd need to see your console.log to see what's going on.

As you also mentioned PHP resizing and doing it server side like that is my preferred method. Here is how I might handle it noting this supports various image formats and proportionate scaling:

PHP:
// Create image from file
switch(strtolower($_FILES['image']['type']))
{
    case 'image/jpeg':
        $image = imagecreatefromjpeg($_FILES['image']['tmp_name']);
        break;
    case 'image/png':
        $image = imagecreatefrompng($_FILES['image']['tmp_name']);
        break;
    case 'image/gif':
        $image = imagecreatefromgif($_FILES['image']['tmp_name']);
        break;
    default:
        exit('Unsupported type: '.$_FILES['image']['type']);
}
// Target dimensions
$max_width = 800;
$max_height = 600;

// Get current dimensions
$old_width  = imagesx($image);
$old_height = imagesy($image);

// Calculate the scaling we need to do to fit the image inside our frame
$scale      = min($max_width/$old_width, $max_height/$old_height);

// Get the new dimensions
$new_width  = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);

// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);

// Resize old image into new
imagecopyresampled($new, $image, 
    0, 0, 0, 0, 
    $new_width, $new_height, $old_width, $old_height);

// Catch the imagedata
ob_start();
imagejpeg($new, NULL, 90);
$data = ob_get_clean();

// Destroy resources
imagedestroy($image);
imagedestroy($new);

// Set new content-type and status code
header("Content-type: image/jpeg", true, 200);

// Output data
echo $data;
 

needfx

Suspended
Aug 10, 2010
3,931
4,241
macrumors apparently
Hello, this issue is frustrating the hell out of me :(

I can't seem to resize my file before uploading it.

Relevant code

Code:
function submitFile(){
  var file = resize(document.getElementById('askForm').files[0]);
  console.log(file);
  var formData = new FormData();
  formData.append('file',file);
  var xhr = new XMLHttpRequest();
  xhr.open('POST',"../server/upload.php",true);
  xhr.onload = function(e){
    alert(this.response);
    addImage(this.response); // this leads to another function that is working already
  };
  xhr.send(formData);
}

function resize(MYFILE){
    var file = MYFILE;
    var c = document.createElement('canvas');
    var ctx = c.getContext('2d'),
    reader = new FileReader;

    reader.onload = function(event) {
      var img = new Image;
      img.src = event.target.result;

      var MAX_WIDTH = 800;
      var MAX_HEIGHT = 600;
      var width = img.width;
      var height = img.height;

      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }
      c.width = width;
      c.height = height;
      ctx.drawImage(img, 0, 0, width, height);

    };

    reader.readAsDataURL(file);
    var dataurl = c.toDataURI("image/png");
    return dataurl;
  }
Problem is I am getting (I think) the correct dataurl file (I did a console.log and had this longish string), but I can't convert it to ajax readable format.

If I just had (without the resize function)

Code:
function submitFile(){
  var file = document.getElementById('askForm').files[0];
  console.log(file);
  var formData = new FormData();
  formData.append('file',file);
  var xhr = new XMLHttpRequest();
  xhr.open('POST',"../server/upload.php",true);
  xhr.onload = function(e){
    alert(this.response);
    addImage(this.response);
  };
  xhr.send(formData);
}
Everything works well, just that the image is not resized!

PHP Code:
PHP:
<?php
$name = time();
if ($_FILES["file"]["error"] > 0)
{
	echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{

    if (file_exists("../images/questions/" . $name))
    {
    	echo $_FILES["file"]["name"] . " already exists. ";
    }
    else
    {
    	move_uploaded_file($_FILES["file"]["tmp_name"],"../images/questions/" . $name);
    	echo $name;
    }
}
?>
So basically I need to resize the image before uploading. Solution preferably not to much changes. Is there just some "var newFile = resize(oldFile, 800,600) function I could use without changing the format of the file?

Thank you :)
have you tried actually re-sizing the physical image in photoshop (image--> image size), save it & re-upload it?
 

charlieegan3

macrumors 68020
Feb 16, 2012
2,394
14
U.K
have you tried actually re-sizing the physical image in photoshop (image--> image size), save it & re-upload it?
You can do that in preview too, then you can apple script it.

I think he might be looking for code to do it though.
 

weex23

macrumors newbie
Mar 22, 2011
7
0
what i did

i hope i didnt miss it but i don't see you using windows.File or windows.FileReader to do this. i wrote code that takes an image file selected by the user, resamples it then uploads to a php script using windows.File and windows.FileReader and also the canvas element. it sends the new image in base64 using ajax then a php script writes it as a jpeg onto the server side storage.

you have to use these to do what you are doing i believe. they are html5 elements.

at the time safari didn't support the File object but testing it now looks like safari 6 does finally.

i used a tutorial online but it took a bit of trial and error myself since i am just a hobbyist and no professional programmer.

hope this helps.

----------

Problem is I am getting (I think) the correct dataurl file (I did a console.log and had this longish string), but I can't convert it to ajax readable format.


encoded_data = encodeURIComponent(STRING);
sendrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

and it looks like you are using those html5 elements. my bad.
 
Last edited:

charpi

macrumors regular
Original poster
Sep 30, 2006
203
10
Hi guys, after not seeing any reply for after a day I thought no one was going to reply. Glad people helped.

I'm sort of at work now so I'll try out the suggestions when I get home. As for why I don't resize the images first, the web app is supposed to allow users to upload their own images to server, and for convenience, I don't want to trouble the users to resize before uploading :) I'll do it for them.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.