Skip to content

Instantly share code, notes, and snippets.

@graylikeme
Created March 13, 2011 03:55
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save graylikeme/867848 to your computer and use it in GitHub Desktop.
Save graylikeme/867848 to your computer and use it in GitHub Desktop.
fetch images with xhr
<!DOCTYPE html>
<html>
<head>
<title>Kitten!</title>
<meta charset="utf-8" />
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/images/kitten.jpg', true);
xhr.onload = function(){
var img = new Image();
var response = xhr.responseText;
var binary = ""
for(i=0;i<response.length;i++){
binary += String.fromCharCode(response.charCodeAt(i) & 0xff);
}
img.src = 'data:image/jpeg;base64,' + btoa(binary);
var canvas = document.getElementById('showImage');
var context = canvas.getContext('2d');
context.drawImage(img,0,0);
var snapshot = canvas.toDataURL("image/png");
var twinImage = document.getElementById('twinImg');
twinImage.src = snapshot;
}
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.send();
</script>
</head>
<body>
<canvas id="showImage" width="200" height="200"></canvas>
<img src="#" id="twinImg" />
</body>
</html>
@Eugenexz
Copy link

Thank you!

@patricknelson
Copy link

patricknelson commented Mar 26, 2021

This was a big help in understanding why btoa() kept freaking out with:

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

The best solution was this part from your example code:

for(i=0;i<response.length;i++){
	binary += String.fromCharCode(response.charCodeAt(i) & 0xff);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment