Ok I am nearing the end of a project and I ran into a small technicality. To fix it easily I need a way to take the of a html element in javascript and encode it into a base64 string?
I know that this is possible with canvas - as that is how I have it working at the moment BUT the project now requires a different approach to be taken for other technical reasons.
Any help or advice on how to extract an img src and encode it into a base64 string would be awesome.
It seems that the dataURL method only works with canvas??
The WOM(Window Object Model) comes with two methods: atob and btoa
You can call them as:
window.atob(str)
or just
btoa(str)
btoa encodes a string to Base-64
atob decodes a string in Base-64
I'm not exactly sure if I've understood it correctly, but if you'd like to encode an image from your html you could do it like in the demo below.
There I've created a canvas element that's just available in your js. Then draw your image in that "virtual" canvas and afterwards you can use toDataURL() to do the base64 encoding.
In the demo I have tested the encoding by outputting that image back to the output div.
The image in the markup I have used is base64 encoded because I have had cross-origin issues at ctx.drawImage(...) but if you use an image from the same origin that should be no problem.
You can find the same demo here at jsFiddle.
$(function() {
var $sourceImg = $('#sourceImg');
var $canvas = $('<canvas/>');
var $out = $('#output');
$canvas.prop({"width": $out.width(), "height": $out.height()});
var ctx=$canvas.get(0).getContext("2d");
//console.log($sourceImg.prop('src'));
// draw image on canvas
var img = new Image(300,300);
img.src = $sourceImg.prop('src');
ctx.drawImage(img,0,0);
// convert canvas to base64 image
var base64img = $canvas.get(0).toDataURL();
//console.log(base64img);
// test if encoding is correct
var img = new Image();
img.src = base64img;
$("#output").append(img);
});
#output {
display: block;
width: 100%;
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<!-- used base64 encoded image because of security error with cross-origin image directly from http://placehold.it/300x300 -->
<img src="data:image/png;base64,R0lGODdhLAEsAeMAAMzMzJaWlsXFxaqqqpycnKOjo76+vre3t7GxsQAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAEsAQAE/hDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru987//AoHBILBqPyKRyyWw6n9CodEqtWq/YrHbL7Xq/4LB4TC6bz+i0es1uu9/wuHxOr9vv+Lx+z+/7/4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAMKHEiwoMGDCBMqXMiwocOHECNKnEixosWLGDNq3Mixo8eP/iBDihxJsqTJkyhTqlzJsqXLlzB1CRhAIACBAgY0zKxJYIAAnTRt+ryx0yZOoDyHZija82ewAwGiSg2AAIOBmlMJ5LxwdarNrTOgeqVqFatUrWW9ov1lYKzUAxYEmM16Qa5bAjTaug0At4LdsXjjzj0LzCwCAWKjOp2AQKrPAVKrVmgc9XHkGYYRT10sgXIAy1ElU/AMmmwvvaYBeO47gbAEsxZcA4AdA7Xo1RVk06agW6ovAY0DSxDgmIJtxlLBAjjeOXkM4DYpEK9s/HLzqMqZq3b+izMAqQVGc19u/XoAsNqf544aHjn2Cek9oy8vbPpnCgV882aPX39r/hmY/tUeAPlFJdwH9g3QX1TrBTAggf5JAF4xuE2A1YGzGUjBhRVwmIFXP9nHYAgVvqbhhieaGB2KKwIjgACoPZhhiyoe6KGFKV7gVVWejdjBizF2mOOMNg554y9qeTfhggHs52AFBTa51F94mfXiB0k2KGOUTm4ZoS9eKSchgBNw+d+TTHKwGn0dhBkbmRKYOSaaZX7Zy1iszemlj9/BCSGfAaolAp5aQhnhknUCypaVXRrKJ6Jx2nlBYlHlCUJXijWa5pl7SjlMYqIRKSSNR4ragVkYhgAqixgeWWqpwchmKo6kGjlkBlHKOGiOr/JqK43CyPmnp3puymkHlPJlgrDC/vZJ57CF9gKcpcJ6tph9oVo7AbanCvojAtRGqO1w9I0LALe8iNVqjqixJl91lbp3HgeJ1Uvvrwe2K292b+3by6oSpOescLudSbCkFmAVXoGpWgAweaE1eLCivSmaS2aYBuAdadBFPJljHaeGQchwgepdwpHByKh4lYUcqnk+efayLslONfNfWfo1mIEnN9jiYBrUzOa5O9t0Ms5Z9ZyL0Apy5ZaY8D3Ngc3yWkwB01ZJ7fRYUPNSlIOW+hVUU0gJpbTP19K1wdcFhC3d2EqNDPfZMdVt991456333nz37fffgAcu+OCEF2744YgnrvjijDfu+OOQRy755JRXbvnlaZhnrvnmnHfu+eeghy766KSXbvrpqKeu+uqst+7667DHLvvstNdu++2456777rz37vvvwAcv/PDEF2/88cgnr/zyzDfv/PPQRy/99NRXb/312Gev/fbcd+/99+CHL/745Jdv/vnopz9MBAA7" id="sourceImg"/>
<div id="output">
<h2>test ouput of base64 encoded image:</h2>
</div>
</div>
Related
I'm trying to decode a custom base64 image in my web application but for some reason I'm facing some difficulties.
The server returns an image as custom base64 string:
//////////////////////////////////////////////////D/////////////////////////////////////////////////8P/////////////////////////////////////////////////w////wP////////////////////////////////////////////D////Af///////////////////////////////////////////8P///8A////////////////////////////////////////////w////wA////////////////////////////////////////////D////AB///////////////////////////////////////////8P///8AD///////////////////////////////////////////w////wAD///////////////////////////////////////////D////AAD//////////////////////////////////////////8P///8AAH//////////////////////////////////////////w////wMAH////////////////////////8AAAAAAAAAAAAAAP//D////A8AH////////////////////////wAAAAAAAAAAAAAA//8P///8D4AH////////////////////////H/////////////j//w////wPwAH///////////////////////8P////////////8P//D////A/wAH///////////////////////w/////////////w//8P///8D/wAD///////////////////////B////////////+D//w////wP/gAB//////////////////////8H////////////4P//D////A//gAA////////////8P////////wP////////////A//8P///8D//gAAP//////////+AH////////M////////////8z//w////wP//gAAA////////D/wAH///////8x////////////jP//D////A///gAAAP//////4P+AAP///////zj///////////8c//8P///8D///wAAA//////+A/wAAf///////OP///////////xz//w////wP///4AAD//////wD/AAB///////88f//////////+PP//D////A////8AAP//////AP4AAD///////z5///////////58//8P///8D/////AA//////4A/gPwP///////Pj///////////Hz//w////wP/////wD//////gP+B/gf//////8/P//////////8/P//D////A/////////////8B/wH+B///////z8f//////////j8//8P///8D/////////////wP/Af8H///////P4//////////8fz//w////wP/////////////B/8D/wf//////8/j//////////x/P//D////A/////////////8H/gP/A///////z/H/////////+P8//8P///8D/////////////wf+A/+D///////P8f/////////4/z//w////wP/////////////B/4H/4P//////8/4//////////H/P//D////A/////////////4H/gf/g///////z/z/////////8/8//8P//////////////////gf8B/+D///////P/H/////////j/z//w//////////////////+B/wH/wP//////8/+f////////+f/P//D//////////////////8H/A//A///////z/4/////////x/8//8P//////////////////wf4D/8H///////P/x////////+P/z//w///////////////////B/gP/gf//////8//H////////4//P//D//////////////////8D+B/+B///////z/+P////////H/8//8P//////////////////wHwH/wH///////P/8////////8//z//w///////////////////gMAf8A///////8//x////////j//P//D//////////////////+AAD+AD///////z//n///////+f/8//8P//////////////////8AAP4Af///////P/+P///////x//z//w///////////////////4AB/gD///////8//8////////P//P//D///////////////////wAP+Af///////z//x///////4//8//8P///////////////////gB/8D////////P//j///////H//z//w////////////////////w//w////////8//+P//////8f//P//D///////////////////////f////////z//8f//////j//8//8P////////////////////////////////P//5//////+f//z//w////////////////////////////////8///j//////x///P//D///+AAAAAAAAP///////////////////z///P//////P//8//8P///4AAAAAAAA////////////////////P//8f/////4///z//w////gAAAAAAAD///////////////////8///5//////H///P//D///+AAAAAAAAP///////////////////z///j/////8f//8//8P///8AAAAAAAA////////wAAAH///////P///H/////j///z//w////8AAAAAAAD///////AAAAAf//////8///8f////+P///P//D////4B/////////////wAAAAB///////z///4/////x///8//8P////wH////////////8AAAAAH///////P///z/////P///z//w/////gP////////////wAAAAAf//////8////H////4////P//D/////Af///////////+AAAAAB///////z///+f////n///8//8P////+A////////////wAAAAAH///////P///4////8f///z//w/////4D////////////AP///////////8////x////j////P//D/////wH///////////8B////////////z////H///+P///8//8P/////gf///////////wP////////////P///+P///x////z//w//////A///////////+B////////////8////4////P////P//D/////8D///////////4H////////////z////x///4////8//8P/////4H///////////gf////////////P////n///n////z//w//////gf///////////B////////////8////+P//8f////P//D//////////////////8H////////////z////8///z////8//8P//////////////////wf////////////P////x//+P////z//w///////////////////B////////////8/////j//x/////P//D//////////////////+D////////////z////+P//H////8//8P//////////////////4P////////////P////8f/4/////z//w///////////////////wf///////////8/////5//n/////P//D///////////////////g////////////z/////j/8f////8//8P///////////////////Af///////////P/////P/z/////z//w///////////////////+AAAAAf//////8/////8f+P/////P//D///////////////////4AAAAB///////z/////5/5/////8//8P//////////////////+AAAAAH///////P/////j/H/////z//w///////////////////wAAAAAf//////8//////H4//////P//D//////////////////+AAAAAB///////z/////8fj/////8//8P//////////////////4AAAAAH///////P/////48f/////z//w///////////////////AAf//////////8//////zz//////P//D//////////////////8A////////////z//////GP/////8//8P//////////////////wP////////////P/////+Z//////z//w///////////////////A////////////8//////4H//////P//D//////////////////4H////////////z//////w//////8//8P//////////////////gf////////////P//////D//////z//w//////////////////+B////////////8//////8P//////P//D//////////////////8H////////////z//////w//////8//8P//////////////////wf////////////P/////+B//////z//w///////////////////B////////////8//////5n//////P//D//////////////////8D////////////z//////GP/////8//8P//////////////////4P////////////P/////88//////z//w///////////////////gf///////////8//////jx//////P//D///////////////////A////////////z/////8fj/////8//8P//////////////////+B////////////P/////x+P/////z//w///////////////////8A///////////8/////+P8f/////P//D///////////////////4AAAAB///////z/////5/5/////8//8P//////////////////wAAAAAH///////P/////H/j/////z//w///////////////////AAAAAAf//////8/////8//P/////P//D//////////////////8AAAAAB///////z/////j/8f////8//8P//////////////////wAAAAAH///////P////+f/5/////z//w///////////////////AAAAAAf//////8/////x//j/////P//D////////////////////////////////z////+P//H////8//8P////////////////////////////////P////4//8f////z//w////////////////////////////////8/////H//4/////P//D////////////////////////////////z////8///z////8//8P////////////////////////////////P////j///H////z//w////////////////////////////////8////+f//+f////P//D////////////////////////////////z////x///4////8//8P////////////////////////////////P////P///z////z//w/////////////////////gP3////////8////4////H////P//D////////////////////gA/H////////z////H///+P///8//8P///////////////////4AD8H////////P///8f///4////z//w////////////////////AAPwH///////8////j////x////P//D///////////////////wAA+AP///////z///+f////n///8//8P///////////////////AAD4A////////P///x////+P///z//w///////////////////4AAPgB///////8////P////8////P//D///////////////////APg/gD///////z///4/////x///8//8P//////////////////4B+D/gP///////P///H/////j///z//w///////////////////gf4P/Af//////8///8f////+P///P//D//////////////////8D/g/+B///////z///j/////8f//8//8P//////////////////wP+D/8H///////P//+f/////x///z//w///////////////////B/4P/wf//////8///x//////j///P//D//////////////////8H/g//A///////z///P//////P//8//8P//////////////////wf+D/+D///////P//4//////8f//z//w//////////////////+B/4P/4P//////8///n//////5///P//D//////////////////4H/g//g///////z//8f//////j//8//8P//////////////////gf+D/+D///////P//j///////H//z//w///////////////////B/4P/wP//////8//+P//////8f//P//D//////////////////8H/g//A///////z//x///////4//8//8P//////////////////wf+D/8H///////P//P///////z//z//w///////////////////A/4P/gf//////8//4////////H//P//D//////////////////8D/g/+B///////z//n///////+f/8//8P//////////////////4H+D/wH///////P/8f///////4//z//w///////////////////gP4P+A///////8//z////////z//P//D///////////////////APg/gD///////z/+P////////H/8//8P//////////////////8AOD4Af///////P/x////////+P/z//w///////////////////4AAAAD///////8//H////////4//P//D///////////////////wAAAAf///////z/4/////////x/8//8P///////////4///////gAAAD////////P/n/////////n/z//w///////////+D///////gAAAf///////8/8f////////+P/P//D///////////AP///////AAAH////////z/z/////////8/8//8P//////////wA////////AAB/////////P+P/////////x/z//w//////////4AD////////4B/////////8/x//////////j/P//D/////////+AAP///////////////////z/H/////////+P8//8P/////////gAA////////////////////P4//////////8fz//w/////////wAAH///////////////////8/j//////////x/P//D////////8AAD////////////h///////z8f//////////j8//8P///////+AAA///////wf///4H///////Pz///////////Pz//w////////gAAf///////B////wf//////8+P//////////8fP//D///////wAAP///////8H////B///////z5///////////58//8P//////8AAD////////wf///8H///////PH///////////jz//w//////+AAAf////////B////gf//////84////////////HP//D//////gAAB////////8H///8B///////zj///////////8c//8P/////4AAAH//////wAAAAAAAH///////Mf///////////4z//w/////8AAHgf//////AAAAAAAAf//////8z////////////zP//D/////AAB+B//////+AAAAAAAB///////wP////////////A//8P////gAA/4H//////4AAAAAAAP///////B////////////+D//w////4AAf/gf//////wAAAAAAB///////8H////////////4P//D///+AAH/+B///////gAAAAAAP///////w/////////////w//8P///4AD//4H////////wf////////////D/////////////D//w////gB///gf////////B////////////8f////////////+P//D///+A///+B////////8H////////////wAAAAAAAAAAAAAA//8P///4B///4H////////wf////////////AAAAAAAAAAAAAAD//w////gAf//gf////////B//////////////////////////////D///+AAP/+B///////////////////////////////////////8P///8AAH/4H///////////////////////////////////////w////8AAH/gf///////////////////////////////////////D////+AAD+B///////////////////////////////////////8P////+AAB4H////////////gP/////////////////////////w//////AABgf/////////z/4AP/////////////////////////D//////gAAB/////////8P/AAf////////////////////////8P//////gAAH/////////A/4AA/////////////////////////w///////wAAP////////4D/AAB/////////////////////////D///////wAAP////////AP8AAD////////////////////////8P///////4AAH///////4A/gHAP////////////////////////w////////8AAD///////gD+A/A/////////////////////////D////////8AAB//////+B/wH+B////////////////////////8P////////+AAB//////wP/Af8H////////////////////////w/////////+AAD//////A/8D/wf////////////////////////D//////////AAP/////8H/wP/A////////////////////////8P//////////gA//////wf+A/+D////////////////////////w///////////gD//////B/4D/4P////////////////////////D///////////wP/////4H/gf/g////////////////////////8P///////////w//////gf8B/+D////////////////////////w////////////7/////+B/wH/4P////////////////////////D//////////////////8H/Af/A////////////////////////8P//////////////////wf8D/8D////////////////////////w///////////////////B/gP/wf////////////////////////D/////////+////////8H+A/+B////////////////////////8P////////8AH///////wPwH/wH////////////////////////w//////D//gAH///////geAf+A/////////////////////////D/////gP/4AAP//////+AAB/gD////////////////////////8P////4A//AAAf//////8AAP4Af////////////////////////w/////AD/4AAA///////wAB/gB/////////////////////////D////4AP/gAAB///////gAH+AP////////////////////////8P////AA/8APgD///////AB/8B/////////////////////////w////8AD/wD/gP///////AP/wf/////////////////////////D////gD/+Af/Af//////////H/////////////////////////8P///8A//4D/8B/////////////////////////////////////w////wH//AP/4D/////////////////////////////////////D////A//8B//wP////////////////////////////////////8P///4D//wH//A//////3//////////////////////////////w////gf/+Af/8D//////D//////////////////////////////D///+B//4D//wH/////8B/////////////////////////////8P///4H//gP//gf/////wB/////////////////////////////w////gf/+A//+B//////AA/////////////////////////////D///8D//wH//4H/////8AAf///////////////////////////8P///wP//Af//gf/////4AAf///////////////////////////w////A//8B//+B//////4AAP////////////////wP/////////D///8D//wH//4H//////8AAH////////////////Af////////8P///wP/+A///gf//////+AAH///////////////8A/////////w////A//4D//8B////////AAD///////////////wA/////////D///+B//gP//wP////////AAB///////////////AB////////8P///4H/+A///A/////////gAB//////////////8AD////////w////gf/wH//8D/////////wAA//////////////wAD////////D///+B//Af//gP/////////4AAf/////////////AAD///////8P///4D/8B//+A//////////8AB/////////////8AAH///////w////wP/gP//wH//////////+AH/////////////wMAH///////D////Af8A//+Af//////////wAf/////////////A8AH//////8P///+AfgH//wD//////////wAB/////////////8D4AH//////w////4AAAf/+AP/////////4AAH/////////////wPwAH//////D////wAAD//gB/////////+AAH//////////////A/wAH/////8P////gAAP/gAH/////////AAB//////////////8D/wAD/////w/////AAB/+AA/////////gAA///////////////wP/gAB/////D////+AAf/4AH////////wAAf///////////////A//gAA////8P////+AD//gB////////4AAH///////////////8D//gAAP///w/////+B//+AP///////+AAD////////////////wP//gAAA///D/////////8D////////AAB/////////////////A///gAAAP/8P/////////x////////wAAf////////////////8D///wAAA//w///////////////////AAP/////////////////wP///4AAD//D//////////////////8AD//////////////////A////8AAP/8P//////////////////wB//////////////////8D/////AA//w///////////////////A///////////////////wP/////wD//D//////////////////8P///////////////////A/////////8P//////////////////3///////////////////8D/////////w///////////////////////////////////////wP/////////D///////////////////////////////////////A/////////8P//////////////////////////////////////8D/////////w////gAAAAAAAD//////////////////////////wP/////////D///+AAAAAAAAP//////////////////////////A/////////8P///4AAAAAAAA/////////wB//////////////////////////w////gAAAAAAAD/////8f/8AB//////////////////////////D///+AAAAAAAAP////+B//AAB/////////////////////////8P///4AAAAAAAA/////gH/4AAD/////////////////////////w///////8D////////4Af/gAAH/////////////////////////D///////wP////////AB/8AAAP////////////////////////8P///////A////////4AH/gB8Af////////////////////////w///////8D////////gAf+Af4B/////////////////////////D///////wP///////8Af/wD/wD////////////////////////8P///////A////////wD//Af/gP////////////////////////w///////8D///////+A//4B//Af////////////////////////D///////wP///////4H//gP/8B////////////////////////8P///////A////////Af/+A//4H////////////////////////w///////8D///////8D//4D//gf////////////////////////D///////wP///////wP//Af/+A////////////////////////8P///////A////////A//8B//8D////////////////////////w///////8D///////8D//wH//wP////////////////////////D///////wP///////gf//A///A/////////////+AAAAAAAAP/8P///////A///////+B//4D//8D/////////////4AAAAAAAA//w///////8D///////4H//gP//wP/////////////gAAAAAAAD//D///////wP///////gf/+A///A/////////////+AAAAAAAAP/8P///////A///////+B//wH//8D/////////////8AAAAAAAA//w///////8D///////4H//Af//gP/////////////8AAAAAAAD//D///////wP///////wP/8B//+B//////////////4B////////8P///////A////////A//wH//4H//////////////wH////////w///////8D///////8D/+A///gf//////////////gP////////D///////wP///////wP/4D//8B///////////////Af///////8P///////A////////Af/gP//wH//////////////+A////////w///////8D///////+B/8B//+A///////////////4D////////D///////wP///////4D/gH//4D///////////////wH///////8P///////A////////wH8Af//AP///////////////gf///////w////gAAAAAAAD////ADAD//wB////////////////A////////D///+AAAAAAAAP///+AAAf/8AP///////////////8D///////8P///4AAAAAAAA////8AAB/+AA////////////////4H///////w////gAAAAAAAD////wAAP/wAH////////////////gf///////D///+AAAAAAAAP////wAB//AA/////////////////////////8P///4AAAAAAAA/////gAf/8AH/////////////////////////w////gAAAAAAAD/////wH//wB//////////////////////////D//////////////////////gf/////////////////////////8P/////////////////////+P//////////////////////////w//////////////////////////////////////////////////D/////////////////////////////////////////////////8P/////////////////////////////////////////////////w//////////////////////////////////////////////////D/////////////////////////////////////////////////8P/////////////////////////////////////////////////w//////////////////////////////////////////////////D/////////////////////////////////////////////////8P/////////////////////////////////////////////////w//////////////////////////////////////////////////D/////////////////////////////////////////////////8P/////////////////////////////////////////////////w//////////////////////////////////////////////////D/////////////////////////////////////////////////8P/////////////////////////////////////////////////w
I do also get information about width, height, bytesize & and format. The format in this case is "Mono 8 bit".
Is there anyway that this string can be decoded to the image?
Edit #1
Here is a simple code. Iam just trying to append it to the src of the element. Like this, which of course wont work:
const imgData = "base64 string from above";
const image = document.getElementById('testImage');
image.src = "data:image/jpeg;charset=utf-8;base64, + " imgData;
I want to resize image at client side using JavaScript. I found 2 solutions, one is using .toDataURL() function and the other is using .toBlob() function. Both solutions are worked. Well, I just curious what is the difference between those two functions? which one is better? or when should I use .toDataURL() function or .toBlob() function?
Here is the code I used to output those two function, and I got very slightly different in image size (bytes) and image color (I'm not sure about this one). Is something wrong with the code?
<html>
<head>
<title>Php code compress the image</title>
</head>
<body>
<input id="file" type="file" onchange="fileInfo();"><br>
<div>
<h3>Original Image</h3>
<img id="source_image"/>
<button onclick="resizeImage()">Resize Image</button>
<button onclick="compressImage()">Compress Image</button>
<h1 id="source_image_size"></h1>
</div>
<div>
<h3>Resized Image</h3>
<h1> image from dataURL function </h1>
<img id="result_resize_image_dataURL"/>
<h1> image from toBlob function </h1>
<img id="result_resize_image_toBlob"/>
</div>
<div>
<fieldset>
<legend>Console output</legend>
<div id='console_out'></div>
</fieldset>
</div>
<script>
//Console logging (html)
if (!window.console)
console = {};
var console_out = document.getElementById('console_out');
var output_format = "jpg";
console.log = function(message) {
console_out.innerHTML += message + '<br />';
console_out.scrollTop = console_out.scrollHeight;
}
var encodeButton = document.getElementById('jpeg_encode_button');
var encodeQuality = document.getElementById('jpeg_encode_quality');
function fileInfo(){
var preview = document.getElementById('source_image');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function(e) {
preview.src = e.target.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
function resizeImage() {
var loadedData = document.getElementById('source_image');
var result_image = document.getElementById('result_resize_image_dataURL');
var cvs = document.createElement('canvas'),ctx;
cvs.width = Math.round(loadedData.width/4);
cvs.height = Math.round(loadedData.height/4);
var ctx = cvs.getContext("2d").drawImage(loadedData, 0, 0, cvs.width, cvs.height);
cvs.toBlob(function(blob) {
var newImg = document.getElementById('result_resize_image_toBlob'),
url = URL.createObjectURL(blob);
newImg.onload = function() {
// no longer need to read the blob so it's revoked
URL.revokeObjectURL(url);
};
newImg.src = url;
console.log(blob.size/1024);
}, 'image/jpeg', 0.92);
var newImageData = cvs.toDataURL('image/jpeg', 0.92);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
result_image.src = result_image_obj.src;
var head = 'data:image/png;base64,';
var imgFileSize = ((newImageData.length - head.length)*3/4)/1024;
console.log(imgFileSize);
}
Edited:
Based on Result of html5 Canvas getImageData or toDataURL - Which takes up more memory?, its said that
"DataURL (BASE64) is imageData compressed to JPG or PNG, then converted to string, and this string is larger by 37% (info) than BLOB."
What is the string mean? is it same as size in bytes? using the code I provided above, the size difference is less than 1Kb (less than 1%). is .toBlob() always better than .toDataURL() function? or there is a specific condition where it would be better to use .toDataURL() function?
Definitely go with toBlob().
toDataURL is really just an early error in the specs, and had it been defined a few months later, it certainly wouldn't be here anymore, since we can do the same but better using toBlob.
toDataURL() is synchronous and will block your UI while doing the different operations
move the bitmap from GPU to CPU
conversion to the image format
conversion to base64 string
toBlob() on the other hand will only do the first bullet synchronously, but will do the conversion to image format in a non blocking manner. Also, it will simply not do the third bullet.
So in raw operations, this means toBlob() does less, in a better way.
toDataURL result takes way more memory than toBlob's.
The data-URL returned by toDataURL is an USVString, which contains the full binary data compressed in base64.
As the quote in your question said, base64 encoding in itself means that the binary data will now be ~37% bigger. But here it's not only encoded to base64, it is stored using UTF-16 encoding, which means that every ascii character will take twice the memory needed by raw ascii text, and we jump to a 174% bigger file than its original binary data...
And it's not over... Every time you'll use this string somewhere, e.g as the src of a DOM element*, or when sending it through a network request, this string can get reassigned in memory once again.
*Though modern browsers seem to have mechanism to handle this exact case
You (almost) never need a data-url.
Everything you can do with a data-url, you can do the same better with a Blob and a Blob-URI.
To display, or locally link to the binary data (e.g for user to download it), use a Blob-URI, using the URL.createObjectURL() method.
It is just a pointer to the binary data held in memory that the Blob itself points to. This means you can duplicate the blob-URI as many times as you wish, it will always be a ~100 chars UTF-16 string, and the binary data will not move.
If you wish to send the binary data to a server, send it as binary directly, or through a multipart/formdata request.
If you wish to save it locally, then use IndexedDB, which is able to save binary files. Storing binary files in LocalStorage is a very bad idea as the Storage object has to be loaded at every page-load.
The only case you may need data-urls is if you wish to create standalone documents that need to embed binary data, accessible after the current document is dead. But even then, to create a data-url version of the image from your canvas, use a FileReader to which you'd pass the Blob returned by canvas.toBlob(). That would make for a complete asynchronous conversion, avoiding your UI to be blocked for no good reasons.
I keep facing a problem converting XHR request response properly. I've read couple of solutions on Stackoverflow and on some other platforms but couldn't success to convert string to dataURL.
I've tried to convert string to through atob() and btoa() methods mention on MDN and this Stackoverflow post.
+ I've keep dive much to find a solution within lost of different methods but non of them took me aim.
How can I convert this response below to a dataURL properly to be able set the URL as image src?
XHR Request Response:
"�PNG
IHDR�� m"H3PLTE���������������������������������������������������?�U�iIDATx�흋�� Eۈ�Z����R�[���BB�]�_�Y�� x��a�a�a�a�a�a�a�a��-��nFI]]�}_x�}�����$ʆ�h�s�_4M_w�WI��*��.o���"��~۔�C^uڟ�P5W�'�[��(��}�=)���U�����Z�J#U��G�'�8G�ۓH�>��E���G�>݁K�ތ4l��C��
v�xu���?�*R��^������ł�B[�YkkY����=�
l|H�s7Yp"���+6zV�cvSj+�
�}�c�c݄Pކ
~�W�N֨(�3����0[QƄ�Q�)o�_R,�]J����G�b��?��M 9� w*h��!=�%"�4������˔*a��
���6��w'��>��el3�e�l����c�ݍ(U.p�Q2�э����#��BɺB�h�4Sh��I�
�s��B���P735���(L�KU_�����s��v�]~�������6�+
/��iD��� �����uԏf�ﳽ�}nA�1_7��t�
+m�2W���P:�8�N�.Ԉ}�KQ�`�G0�P�Y�}�=A|�$� ��Xǭ�)w���>����m�J�R�֖��~}�n�#�G��7�ͽ���d������58C��i�6|�&�ۄ?pIl:P�l *FE�
q��wj��v��6�.�BQ�߁�����GBm�{�(�
�!f�k�Df*?}�+�N��"u��V,N��.eҚj��r�t��А�r��>)��*a��J����4�U���L��Z�/�ҵ���e=�;Qp����=x�[5=N��:8O}��k�?�Rr"�ma��tڱQ�I���R���=ܣU�MI�3Y�6\�~�v�.yJ�)��q�&���/�_�R�A-����{Ҡ�$��RNx%�}'�D�Tm�d9��}�n��~�kz��Ӝ���K� b��] L|�iqo3�O��p��l�� 'd�$�D�!:e��F=����'�"7g�F=b��7+Qܤ֩n�_"��c�����w$~`�V�"��I�{�&R̰G�O�|��%� ��/�L���>� �wb�S����- �3O����*J��7�͈�
�m�JL�Fdҗ��0��>���0��<����0�I!�33,y
d>3Ò�<y��)�'�pxS�E����;�����)�2�p��Dt��P�*�����Y�.�܈�
��D�5�Y�Ld����l��cb�lQ�|4�DED�͒�n
^3��&F!|��D��?�'��q
G�jN�h�\� 2ODVu�d���'���LLs_�ۏ�>CV� �gQ�{���e�
���2��*�Q�>|y��fg�M9a��E�IEND�B`�"
UPDATE:
I've succeed to render image through this post #
https://stackoverflow.com/a/8022521/7163711
Your XHR data is a png file, as expected. In order to show you how to embed it properly, I've taken the liberty of generating a "better" PNG - a 10x10 yellow square. it is base64-encoded in b64data on the first line of the snippet. The second line sets yourData as what you would have gotten from an XHR.
var b64data = "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFklEQVR42mP8/5/hDAMRgHFUIX0VAgBfZRvvtreybgAAAABJRU5ErkJggg==";
// Assuming your data is a raw PNG
var yourData = atob(b64data);
// We convert...
var btoa_data = btoa(yourData);
var elem = document.createElement("img");
elem.src = "data:image/png;base64,"+btoa_data;
document.getElementById("app").append(elem);
console.log(atob(b64data));
<div id="app"></div>
As you can see, btoa() works in order to base64-encode data; the only thing you need to do after this is to indicate in the src part of your img tag that:
It is a PNG (if it isn't, or if you are not sure if it will be, you'll need to check the first few bytes of your reply)
It is base64-encoded
how to convert image url to base64 encoded data url without using html5 canvas object.
canvas.todataURL()
I am gettting base64 data using canvas.todataURL, but it fails to read remote url's, so I want to convert my image url to dataurl with out using canvas.todataURL() and use it in my application.
HOw can I to do this.
You can use this code-
HTML-
<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />
javascript-
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());
</script>
found it here-
How to get base64 encoded data from html image
You can't do it purely in javascript without using canvas.toDataUrl(). You would have to do something server-side. Basically create a simple service which takes an url to an image as parameter and then returns that image as a base64 string.
I have created a custom product configurator and i am using html2canvas to generate a base64 encoded string of a canvas element.
If you go to: http://faithpointdallas.com/ecom/page/customStole you can see that when you click "add to cart" at the bottom, it uses the html2canvas script to alert a generated base64 encoded string.
My question is: How can i take that base64 encoded string and turn it into a regular image tag. Like <img src="myconvertedbase64string.PNG" />
Here is the code that is generating the string:
$('#addToCart').click(function(event) {
event.preventDefault();
var target = $('.customstole');
html2canvas(target, {
onrendered: function(canvas) {
var data = canvas.toDataURL();
alert(data);
// data is the Base64-encoded image
}
});
});
This might help - it uses jQuery to post the base64 encoded URL to the server and then saves it to a file with some PHP:
http://www.rgraph.net/docs/integration-with-server-side-scripting.html#image
Also, did you know that you can use the data: url returned by toDataUrl() directly as the tag src?