Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an image in iPhone or Android and I want to pass that file stream or bytes string through jQuery AJAX to Web Service to store file on server.

So, in HTML5 how can I get image file (jpg, gif, etc..) bytes string so I can post that to server?

share|improve this question
    
Save the image source using jquery prop() and send it using $.ajax() –  Johan Oct 18 '12 at 8:43
    
ok image is saved in some folder & i can read but how can i convert them to bytes string –  Ankit Shah Oct 18 '12 at 8:45
add comment

1 Answer

You could copy the image to a canvas with the same size using canvas.drawImage(image, 0, 0) and then use the .toDataURL('image/TYPE') method of the canvas to retrieve the base64 representation of the image. 'TYPE' would then be either jpg, gif or png

Example: Make sure that the current page and the image are both on the same domain, subdomain and protocol otherwise you will get a security error. Also make sure that the canvas has the same width and height as the image

HTML

<img src="whatever.jpg" id="myimage" />
<canvas width="300" height="300" id="mycanvas" style="display: none;"></canvas>

Javascript

var myImage = document.getElementById('myimage');
var myCanvas = document.getElementById('mycanvas');

var ctx = myCanvas.getContext('2d');

ctx.drawImage(myImage, 0, 0);

var mydataURL=myCanvas.toDataURL('image/jpg');
share|improve this answer
    
Do you have working URL or example of that?? –  Ankit Shah Oct 18 '12 at 8:54
    
see latest EDIT –  devnull69 Oct 18 '12 at 11:26
    
Thanks you very much :) –  Ankit Shah Oct 19 '12 at 4:32
    
I have to post this image bytes in AJAX on DOT NET Web Service API. How to do this?? i tried but it giving same error "The input is not a valid Base-64 string as it contains a non-base 64 character" –  Ankit Shah Oct 19 '12 at 8:14
1  
You would have to cut off the first part of the string (which is a data URL rather than a mere base64 representation). It looks like data:image/jpg;base64,BASE64DATAHERE. If you cut off everthing up to the first comma, you should be fine –  devnull69 Oct 19 '12 at 10:02
show 2 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.