Types of conversion of images - javascript

I am converting images to Base64 and sending them to websocket.
using javacript:
var reader = new FileReader();
reader.onload = (function(aImg){
return function(e){
aImg.src = e.target.result;
imageMessage = aImg.src;
};
}(image))
var ret = reader.readAsDataURL(file);
In socket server I get the string:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4RFGRXhpZgAATU0AKgAAAAgACAEyAAIAAAAUAAAIegE7AAIAAAAHAAAIjkdGAAMAAAABAAMAAEdJAAMAAAABADIAAIKYAAIAAAAhAAAIlodpAAQAAAABAAAIuJydAAEAAAAOAAARMOocAAcAAAgMAAAAbgAAAAAc6gAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA......
So as much as the image size is bigger, the string will be longer.
And the socket is crashing.
My question is how to convert the image to small and simple string.

Related

How do I get base 64 encoding of a file that use Windows-1251

I have a file uploader input, where I accept a file, convert it to base 64 string, and send the payload to a rest api.
However, when I was encoding base64 for utf-8 files, it was working fine. But if I try to get base64 strings of "window-1251" files, it is not converted to a string properly, and the api throws error instead because the base64 string is not valid content.
So my question is how do I get base64 string of a file that uses window-1251 for encoding?
var reader2 = new FileReader();
reader2.readAsDataURL(file);
reader2.onload = function (e) {
var sContentStream = e.target.result;}
Sorry, but the premise makes no sense.
FileReader.readAsDataURL will always return a valid base64 string from what you gave to it => binary data.
The fact that these bytes represent a text file, with a given encoding is simply ignored by the algorithm.
const rand_data = crypto.getRandomValues(new Uint8Array(50));
const blob = new Blob([rand_data]);
const reader = new FileReader();
reader.onload = e => {
const dataURL = reader.result
const base64 = dataURL.slice(dataURL.indexOf(',')+1);
console.log(base64);
console.log(atob(base64)); // would throw if invalid data
};
reader.readAsDataURL(blob);
So you are looking at the wrong end of the problem: The consumer may have issues with reading windows-1251 encoded text files, but that's not FileReader's fault.
Now, if you are willing to do the conversion from this encoding to UTF-8 in the browser, then that's still doable, but you's need a way to know which encoding the file you've been given is in.
const win_1251 = new Blob([Uint8Array.from([200])]); // И in windows-1251
// to prove it's not UTF-8
readUTF8Text(win_1251); // �
const reencode_reader = new FileReader();
reencode_reader.onload = e => {
const utf_8_arr = new TextDecoder('windows-1251')
.decode(new Uint8Array(reencode_reader.result));
const utf_8 = new Blob([utf_8_arr], {type: 'text/plain'})
makeDataURL(utf_8);
readUTF8Text(utf_8); // И
};
reencode_reader.readAsArrayBuffer(win_1251);
function makeDataURL(blob) {
const reader = new FileReader();
reader.onload = e => {
console.log(reader.result);
};
reader.readAsDataURL(blob);
}
function readUTF8Text(blob) {
const reader = new FileReader();
reader.onload = e => {
console.log(reader.result);
};
reader.readAsText(blob);
}

Filereader JS API not reading files properly

I have written the following code to read text from any csv or text file. However it sometimes reads successfully and stores in the variable and sometimes doesn't. Is there something missing in my code.
groupCsvData = [];
$('#add-group-upload').change(function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
groupCsvData = [text];
};
reader.readAsText(file);
)};

Convert Blob to binary string synchronously

I'm trying to put image in clipboard when user copies canvas selection:
So I thought the right way would be to convert canvas tu dataURL, dataURL to blob and blob to binary string.
Theoretically it should be possible to skip the blob, but I don't know why.
So this is what I did:
function copy(event) {
console.log("copy");
console.log(event);
//Get DataTransfer object
var items = (event.clipboardData || event.originalEvent.clipboardData);
//Canvas to blob
var blob = Blob.fromDataURL(_this.editor.selection.getSelectedImage().toDataURL("image/png"));
//File reader to convert blob to binary string
var reader = new FileReader();
//File reader is for some reason asynchronous
reader.onloadend = function () {
items.setData(reader.result, "image/png");
}
//This starts the conversion
reader.readAsBinaryString(blob);
//Prevent default copy operation
event.preventDefault();
event.cancelBubble = true;
return false;
}
div.addEventListener('copy', copy);
But when the DataTransfer object is used out of the paste event thread the setData has no longer any chance to take effect.
How can I do the conversion in the same function thread?
Here is a hacky-way to get you synchronously from a blob to its bytes. I'm not sure how well this works for any binary data.
function blobToUint8Array(b) {
var uri = URL.createObjectURL(b),
xhr = new XMLHttpRequest(),
i,
ui8;
xhr.open('GET', uri, false);
xhr.send();
URL.revokeObjectURL(uri);
ui8 = new Uint8Array(xhr.response.length);
for (i = 0; i < xhr.response.length; ++i) {
ui8[i] = xhr.response.charCodeAt(i);
}
return ui8;
}
var b = new Blob(['abc'], {type: 'application/octet-stream'});
blobToUint8Array(b); // [97, 98, 99]
You should consider keeping it async but making it two-stage, though, as you may end up locking up the browser.
Additionally, you can skip Blobs entirely by including a binary-safe Base64 decoder, and you probably don't need to go via Base64 AND Blob, just one of them.
Blob can be converted to binary string by getting Blob as dataURI and then applying atob. This, however, again [requires FileReader][3]. In my case, it's best to skip the blob alltogether:
//Canvas to binary
var data = atob(
_this.editor.selection.getSelectedImage() //Canvas
.toDataURL("image/png") //Base64 URI
.split(',')[1] //Base64 code
);

Javascript html5 how to convert binary data into string

var reader = new FileReader();
var rawData = new ArrayBuffer();
//console.log(1);
reader.onload = function(e) {
var rawData = e.target.result; //binary data
console.log(rawData);
}
I want to see explicitly the binary raw data as a text string, is that possible?, cause the only thing i see when logging is:
ArrayBuffer {}
You can try
console.log(String.fromCharCode.apply(null, new Uint16Array(rawData)));
This is what'I've needed:
reader.readAsBinaryString(file);
then the data is available raw

Using Javascript FileReader with huge files

I have a problem using the Javascript FileRead trying to read huge files.
For example, I have a text file of 200mb and everytime I read this file the code stops working.
Its possible to read the text file, but for example ONLY the first 10 lines or stop reading after 10mb?
This is my code:
var file = form.getEl().down('input[type=file]').dom.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
data = e.target.result;
form.displayedData=data;
};
})(file);
reader.readAsText(file);
The e.target.result always has the whole data of the file.
What can I do here?
Thx
This will only read the first 10 mb:
var file = form.getEl().down('input[type=file]').dom.files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
form.displayedData = data;
};
reader.readAsText(file.slice(0, 10 * 1024 * 1024));

Categories