FileReader Image to Base64 Corrupted Conversion - javascript

I am trying to convert an Image from my local files to Base64 by JavaSctipt.
For example please look at THIS website.
When I browse a picture on the input beneath Local File* heading (input having id #form-base64-converter-encode-image-file) and then run this code in the console of the browser -
function getBase64(file) {
var reader = new window.FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
alert(reader.result);
};
reader.onerror = function (error) {
alert('Error: ', error);
};
}
var file = window.document.querySelector('#form-base64-converter-encode-image-file').files[0];
getBase64(file);
The script give me a long string which is supposed to be conversion of image in Base64. But when I assign the string in the source of an Image the image won't show up. The string is corrupted or not a proper conversion of Base64. Please somebody explain what I need to do for a proper Base64 string which I can then assign in src attribute of an < image >
Thank you.

Related

How to get bytecode from selected pdf in angular

I want to extract the bytecode from an file I select (pdf) to save it in my database. But I am always getting the error that my byte is undefined. Could someone look at my code and tell me what is wrong with it?
I tried to use the FileReader but my byte returns undefined, the formdata works fine it shows on the console every information I need for the file.
EDIT:
uploadFile2(files: FileList | null): void {
const file = files.item(0)
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
this.documentsArray.push({documentType: this.form.controls.dokumentType.value, file: reader.result})
console.log(this.documentsArray)
}
}
Hi I edited my code and now I am getting a base64 I think, but one question, it starts like this:
data:application/pdf;base64,JVBERi0xLjQKJfbk/N8KM......."
is the start with data:application/pdf correct or do I have to change something to save it in the database
I'd suggest you to store the file as a base64 String in your database.
This would look as following. With the line number 2 you're fetching the file from your input event.
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = (event) => {
if (reader.result) {
//save pdf base64 into database
}

Get base64 content from local mp3/mp4

I'm trying to get the base64 content from a local audio on my device using javascript.
I'm using the following code:
var file = new File(["file_name.mp4"], "/data/user/files/VoiceRecordingPluginData/file_name.mp4");
var reader = new FileReader();
// Read file content on file loaded event
reader.onloadend = function (event) {
console.log(reader.result);
};
// Convert data to base64
reader.readAsDataURL(file);
As result, "file" gets populated like this:
file.name: ["file_name.mp4"]
file.localURL: "/data/user/files/VoiceRecordingPluginData/file_name.mp4"
Once "onloaded" is reached, "reader.result" is empty.
Any hints on what's wrong in my code?

FileReader readAsDataURL creating large base64 images

I have a requirement to convert an input image (blob) to base64 image. Im aware the size will increase by approx 1.37.
However i have noticed when using the firereader.readAsDataUrl the size of the image is extremely large when compared to the built in base64 command line tool you have on macOS.
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
Steps to reproduce:
Download this free sample image https://wall.alphacoders.com/big.php?i=685897 make sure to click the Download button (Downlaod Original 8000x600). Do not use right click save as because the image will be compressed
Use the jsfiddle to pick the above downloaded image and check the console log for the size of the base 64. https://jsfiddle.net/b7nkw8j9/ you can see the size is 11.2mb.
Now if your on mac use the base64 command line tool to convert the above downloaded image to base64 and check the file size there. You will see the base64 size here is. 5.9mb. base64 -w 0 downloaded_image.jpg > downloaded_image.base64
This is the function i am using in my code to convert an input file image to base64.
async convertToBase64(file) {
if (file === undefined) {
throw new Error("File could not be found");
}
const fileReader = new FileReader();
return new Promise((resolve, reject) => {
fileReader.readAsDataURL(file);
fileReader.onerror = (error) => {
reject("Input: File could not be read:" + error);
};
fileReader.onloadend = () => {
resolve(fileReader.result);
};
});
}
Why does the filereader.readAsDataURL make the image base64 output extremely large.
How can i make this more efficient?
I have 5,882,455 bytes for the FileReader vs 5,882,433 bytes for base64 output, if you add the 22 bytes from data:image/png;base64,, we're not too far.
However to the question How can i make this more efficient?, just don't use a data URL here. Whatever you've been told you need it too, it was a lie (I'm 99% percent sure).
Instead you should always prefer to work with the Blob directly.
To display it, use a blob URL:
inp.onchange = e => {
img.src = URL.createObjectURL(inp.files[0]);
};
<input type="file" id="inp">
<img id="img" src="" height="200" alt="Image preview..." accept="image/*">
To send it to your server, send the Blob directly, either through a FormData or, directly from xhr.send() or as the body of a fetch request.
The only case can think of where you would need a data URL version of a binary file on the front end is to generate a standalone document which would need to embed that binary file. For all other use cases I met in my career, Blob where far better suited.
For the message that gets printed in the Chrome's tooltip, that's the size of the USVString that the browser has to hold in memory. It's twice the size of the file you have on disk, because USVStrings are encoded in UTF-16, even though this string holds only ASCII characters.
However, to be sent to your server, or to be saved as a text file, it will generally be reencoded in an 8 bit encoding, and retrieve it's normal size.
So don't take this tooltip as a mean to tell you how big your data is, it's only the size it does take in the browser's allocated memory, but outside, it won't be the same at all.
If you wanna check the size of binary data generated here is a better fiddle, which will convert USVStrings to UTF-8 and keep binary as binary (e.g if you pass an ArrayBuffer to it):
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
console.log(new Blob([reader.result]).size);
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL -->
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">

ASCII to Base64 in JavaScript

I'm trying to pull an image via GET /url.jpg and in the response is the image's ASCII representation. I then take that and try to Base64 encode it so I can display the image via html in an src tag. Here's the code I'm using:
api.getImg()
.then(function(res){
var reader = new window.FileReader();
var data = new Blob([res.data], {type: 'image/jpg'});
reader.readAsDataURL(data);
reader.onloadend = function() {
// sets the base64 encoded image to ng-src via AngularJS
vm.imgVis.viz1.link = reader.result;
}
});
The encoded image is then passed into the ng-src tag and nothing is loaded, broken image. I then take the base64 string to online base64 to image converters and nothing works there either.
Next, I tried directly uploading the image into an 'image to base64' converter and I get a completely new base64 string that works just fine anywhere I use it. Additionally, I turned this new string into an ASCII format and it looks nearly identical to the original GET response, however it appears the unprinted ASCII chars such as NULL are not being represented the same.
I think my issue might be with the ASCII character set. Could that be my problem? I feel like I'm missing a step.
Thanks
Edited to add API call:
function getImg() {
var settings = {
"url": "assets/apple.jpg",
"method": "GET",
"headers": {}
}
return $http(settings)
.then(function(response) {
return response;
})
.catch(function(e) {
return e;
});
}
And here is the actual image:
Apple

how do i get any images in binary code using js?

I want to make a multiple images upload system with prograss bar. I want to do with simaple code(using jquery or js). I want when user has upload his images on browser and i want to show on browser that images and with upload button he starts uploading image via ajax in his folder.
So questions
1.) Is it possible to show uploaded image (without any complicated code) ?
2.) Do i get a variable or array where uploaded images are stored as base64 code (data:/img:dfd5d/d54fs..... something like this) or encoded?
3.) How do i add progressBar ?
I didn't write any code yet because i dont know how to start. I am new in computer science.
But i find this code on this site
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
This is easy code and i understand but one thing is not clear what does mean this line var reader = new FileReader(); why use new and what is it ?
Ty in advance and please dont explain complicate and i am not very good in english. So please try to explain in poor words if possible..
Assuming that you have this field
<input type="file" onchange="showImage(this)"/>
you can create a script to take the binary data and show it
function showImage(input){
var reader = new FileReader();
// validating...
var fileType = input.files[0].type;
var filesize = input.files[0].size;
// filetype (this will validate mimetype, only png, jpeg, jpg allowed)
var fileTypes = ["image/png", "image/jpeg", "image/gif"];
if (fileTypes.indexOf(fileType) < 0){
// return error, invalid mimetype
return false;
}
// file cannot be more than 500kb
if (filesize > 5000000) {
// return error, image too big
return false;
}
reader.onload = function (e) {
// e will contain the image info
jQuery('#myimagetopreview').attr('src', e.target.result)
}
reader.readAsDataURL(input.files[0]);
}
This should work, if you have problem tell me
edit: FileReader is not supported by all the browsers, check the documentation for more https://developer.mozilla.org/en/docs/Web/API/FileReader
The FileReader in JS has Status "Working Draft" and isn't part of the official JS API. I think you have to wait until the Browsers support this ne API or you have to activate experimental JS API in the Browser.

Categories

Resources