Register FAQ / Rules Forum Spy Search Today's Posts Mark Forums Read
Go Back   MacRumors Forums > Special Interests > Visual Media > Web Design and Development

Reply
 
Thread Tools Search this Thread Display Modes
Old Oct 6, 2012, 06:17 AM   #1
charpi
macrumors regular
 
Join Date: Oct 2006
Resizing an image before uploading

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 Code:

<?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
charpi is offline   0 Reply With Quote
Old Oct 8, 2012, 05:36 AM   #2
SrWebDeveloper
macrumors 68000
 
SrWebDeveloper's Avatar
 
Join Date: Dec 2007
Location: 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 Code:
// 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
    
0000
    
$new_width$new_height$old_width$old_height);

// Catch the imagedata
ob_start();
imagejpeg($newNULL90);
$data ob_get_clean();

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

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

// Output data
echo $data
__________________
Jim Goldbloom
Sr. Web Developer, owner GoldTechPro, LLC
http://www.GoldTechPro.com
SrWebDeveloper is offline   0 Reply With Quote
Old Oct 8, 2012, 05:39 AM   #3
needfx
macrumors 68000
 
needfx's Avatar
 
Join Date: Aug 2010
Location: macrumors apparently
Quote:
Originally Posted by charpi View Post
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 Code:

<?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?
needfx is online now   0 Reply With Quote
Old Oct 8, 2012, 05:54 AM   #4
charlieegan3
macrumors 68020
 
charlieegan3's Avatar
 
Join Date: Feb 2012
Location: U.K
Quote:
Originally Posted by needfx View Post
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.
charlieegan3 is offline   0 Reply With Quote
Old Oct 8, 2012, 11:12 AM   #5
weex23
macrumors newbie
 
Join Date: Mar 2011
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 by weex23; Oct 8, 2012 at 11:17 AM. Reason: forgot a line of code
weex23 is offline   0 Reply With Quote
Old Oct 8, 2012, 08:46 PM   #6
charpi
Thread Starter
macrumors regular
 
Join Date: Oct 2006
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.
charpi is offline   0 Reply With Quote

Reply
MacRumors Forums > Special Interests > Visual Media > Web Design and Development

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Similar Threads
thread Thread Starter Forum Replies Last Post
Image resizing apps steveash iPhone 2 Dec 20, 2012 12:52 PM
Shrink My Pictures - Reduce Image Size Without Resizing DancingBottle iPhone and iPod touch Apps 0 Dec 4, 2012 08:09 AM
Shrink My Pictures - Reduce Image Size Without Resizing DancingBottle iPad Apps 0 Dec 4, 2012 08:05 AM
Resizing an image. SoApple Digital Photography 3 Oct 2, 2012 12:48 PM

Forum Jump

All times are GMT -5. The time now is 05:04 AM.

Mac Rumors | Mac | iPhone | iPhone Game Reviews | iPhone Apps

Mobile Version | Fixed | Fluid | Fluid HD
Copyright 2002-2013, MacRumors.com, LLC