blob to base64 converstion javascript - javascript

I am trying to parse blob object into base64 string in javascript. Please help. my code is
var reader = new FileReader();
reader.addEventListener("loadend", function () {
// reader.result contains the contents of blob as a typed array
var buffer = reader.result;
var view = new Uint8Array(buffer);
var binary = String.fromCharCode.apply(window, view);
var base64 = btoa(binary);
cb(base64);
console.log(base64);
});
reader.readAsArrayBuffer(data.blob);

You may try this-
var blob = //your blob data;
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
console.log(base64data);
return;
}
Refer- Convert blob to base64

Related

A image converted with canvas fails to be read by python PIL _io.BytesIO

Python PIL rejects to read an image you have resized with Javascript canvas
I resize an image on the client-side with Javascript:
var reader = new FileReader();
reader.onload = function (e) {
el('image-picked').src = e.target.result;
el('image-picked').className = '';
var image = new Image();
//compress Image
image.onload=function(){
el("image-picked").src=image.src;
var canvas=document.createElement("canvas");
var context=canvas.getContext("2d");
new_size = get_sizes(image.width,image.height,max_side_px)
[canvas.width,canvas.height] = new_size;
context.drawImage(image,
0,
0,
image.width,
image.height,
0,
0,
canvas.width,
canvas.height
);
console.log("Converted");
//el('image-picked').className = 'no-display'
//el('image-picked').src=""
el('upload-Preview').className = ''
el('upload-Preview').src = canvas.toDataURL("image/png", quality);
The result seems ok, less size, seemingly ok:
There are only minor differences on the files with identify:
(base) ➜ Desktop file before.png after.png
before.png: PNG image data, 4048 x 3036, 8-bit/color RGB, non-interlaced
after.png: PNG image data, 500 x 375, 8-bit/color RGBA, non-interlaced
Then I send the file via POST:
var xhr = new XMLHttpRequest();
var loc = window.location
xhr.open('POST', `${loc.protocol}//${loc.hostname}:${loc.port}/analyze`, true);
xhr.onerror = function() {alert (xhr.responseText);}
xhr.onload = function(e) {
if (this.readyState === 4) {
var response = JSON.parse(e.target.responseText);
el('result-label').innerHTML = `Result = ${response['result']}`;
}
}
var fileData = new FormData();
var file = new File([el('upload-Preview').src],
"image.png", { type: "image/png",
lastModified : new Date()});
fileData.append('file', uploadFiles[0]);
xhr.send(fileData);
And then I read on the server with python open_image(BytesIO(img_bytes)) :
#app.route('/analyze', methods=['POST'])
async def analyze(request):
data = await request.form()
img_bytes = await (data['file'].read())
img = open_image(BytesIO(img_bytes))
The above works without problems with any normal image, but it fails with any image that is the result of the resize with js, and the error is
File "/Users/brunosan/anaconda3/envs/fastai/lib/python3.7/site-packages/PIL/Image.py", line 2705, in open
% (filename if filename else fp))
OSError: cannot identify image file <_io.BytesIO object at 0x124ce6360>```
I've tried canvas.toDataURL("image/jpeg", quality) on the JS side, and reading directly with PIL (not fastai, which calls PIL). It's the same error :frowning_face:
Found the answer here.
I was injecting the image as a a DataURL, when the POST expected a binary. I could see the difference using the "Network" tab:
To convert a DataURL into the binary we need to make a Blob, and then put it into a File:
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
blob=dataURItoBlob(el('upload-Preview').src)
var file = new File([blob],
"image.png", { type: "image/png",
lastModified : new Date()});
var fileData = new FormData();
fileData.append('file', file);

How to perform sha256 hash using sjcl.hash.sha256.hash on a file content?

I am trying to perform SHA256 hash on a file content using javascript.
I get the file using the following function
var fileReader = new FileReader();
var fileByteArray = [];
fileReader.onload = function(evt) {
if (evt.target.readyState == FileReader.DONE) {
var arrayBuffer = evt.target.result,
array = new Uint8Array(arrayBuffer);
fileHash = generateHashOfFileContent(array);
console.log('fileHash1: ' + fileHash);
}
}
fileReader.readAsArrayBuffer(this.files[0]);
And the hash function is
function generateHashOfFileContent(fileData){
var bitArray = sjcl.hash.sha256.hash(fileData);
var digest_sha256 = sjcl.codec.hex.fromBits(bitArray);
console.log("Sha256 "+digest_sha256);
return digest_sha256;
}
But it produce wrong hash data when I select a binary file
I can only produce actual hash using a text file and change the fileReader.readAsArrayBuffer(this.files[0]); -------> fileReader.readAsText(this.files[0]);
Can someone help me to figure out the problem
You should convert your TypedArray to bitArray:
var fileReader = new FileReader();
var fileByteArray = [];
fileReader.onload = function(evt) {
if (evt.target.readyState == FileReader.DONE) {
var arrayBuffer = evt.target.result,
array = new Uint8Array(arrayBuffer);
let bitArray = sjcl.codec.bytes.toBits(array)
fileHash = generateHashOfFileContent(bitArray);
console.log('fileHash1: ' + fileHash);
}
}
fileReader.readAsArrayBuffer(this.files[0]);
See https://github.com/bitwiseshiftleft/sjcl/wiki/Codecs

How to return something in a function .onload added

I'm trying to import an excel file using SheetJS js-xlsx and I don't know how to return the variable workbook. Thanks!
var rABS = true; // true: readAsBinaryString ; false: readAsArrayBuffer
function handleFile(e) {
var files = e.target.files, f = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
if(!rABS) data = new Uint8Array(data);
var workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});
/* DO SOMETHING WITH workbook HERE */
};
if(rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
}
input_dom_element.addEventListener('change', handleFile, false);

How to save a text to file and read it again but save as binary in javascript

I'm building a file saver from a string using FileSaver.js from a SO question
let byteChars = atob("my string");
let byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++) {
byteNumbers[i] = byteChars.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
var data:Blob = new Blob([byteArray], {type: "application/octet-stream"});
var filename:string = filename + '.myext';
saveAs(data, filename, true);
Then I have to read it back to "my string" using Javascript's FileReader:
let fr = new FileReader();
fr.onload = (e:FileReaderEvent) => {
let result:any = e.target.result;
//I don't know what I have to do with this type of data to get "my string" back
};
fr.readAsBinaryString(file);
Edit, Updated
write file
let byteChars = atob("my string");
let byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++) {
byteNumbers[i] = byteChars.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
var data = new Blob([byteArray], {type: "application/octet-stream"});
saveAs(data, "myfile.abc");
read file
<input type="file">
<script>
var reader = new FileReader();
reader.addEventListener("load", function(e) {
document.body.innerHTML += "<br>" + btoa(e.target.result);
});
document.querySelector("input[type=file]")
.addEventListener("change", function(e) {
reader.readAsBinaryString(e.target.files[0])
})
</script>
plnkr http://plnkr.co/edit/0KVhXnd0JpysplDLcAlC?p=preview
You can use TextEncoder(), TextDecoder() or FileReader(), .readAsBinaryString()
var str = "my string";
var encoder = new TextEncoder();
var encodedBytes = encoder.encode(str);
// do file save stuff
var decoder = new TextDecoder();
var decodedBytes = decoder.decode(encodedBytes);
console.log(encodedBytes, decodedBytes);
// alternatively, using `FileReader()`
var reader = new FileReader();
reader.onload = function() {
console.log("FileReader result:", reader.result)
}
reader.readAsBinaryString(new Blob([encodedBytes]))

Unable to display binary to image

I am trying to get an image from a URL by using Ajax and want to convert this into data URL.
so far I have done following things("ALL DOES NOT WORK :(")
sforce.connection.remoteFunction({
url : newURL,
mimeType: 'text/plain',
requestHeaders: {"responseType": "arraybuffer"},
onSuccess:function(response){
console.log(newURL);
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById(imageID);
output.src = dataURL;
};
var blob = new Blob([response], {type: "image/png"});
console.log(blob);
reader.readAsDataURL(blob);
}
This above code return data url but that does not display any image(corrupted).
I have done below thing also :
First converted response binary string into array like below
var bytes = new Uint8Array(response.length);
for (var i=0; i<response.length; i++)
bytes[i] = response.charCodeAt(i);
Now I converted above array into base64 like below
function Uint8ToString(u8a){
var CHUNK_SZ = 0x8000;
var c = [];
for (var i=0; i < u8a.length; i+=CHUNK_SZ) {
c.push(String.fromCharCode.apply(null, u8a.subarray(i, i+CHUNK_SZ)));
}
return c.join("");
}
// Usage
var u8 = bytes;
var b64encoded = btoa(Uint8ToString(u8));
make data URI with above base64 like below
var dataurl = 'data:image/png;base64,'+b64encoded;
But nothing is working.
Below is the end point url to get image from
http://featherfiles.aviary.com/2014-10-24/f93707f9c1472f8a/7892b73db1d947adb7bc536d5d03e5c0.png
Please help me as I am not able to understand how to solve this :(
Are you able to get the blob of image correctly? i.e. it's size is that of the image right?
If yes , then you might be just missing this line (the creation of blobUrl from blob)
var blob = new Blob([response], {type: "image/png"});
var blobUrl= URL.createObjectURL(blob); //create blobUrl from blob
console.log(blob);
console.log(blobUrl)
reader.readAsDataURL(blobUrl);

Categories