Convert image into base64 in javascript
Upload your image and transform this image into base64 encoding.
Converting our image into base64 is very useful sometimes. You can pass this base64 to the server very easily. So in this article, we will upload our image and convert this image into base64.
What is base64:
Base64 is an encoding algorithm where we can convert any character, object, image, pictures, or any kind of file into alphabets which consist of digits, letters, signs, etc.
Basically, base64 is useful only for the small size of data.
Let’s convert an image into base64:
I am going to use an agular2 app, where I will show you how we can convert images into base64.
first, we need to install an npm package to do this, so run below command to install that npm package:
npm install fuctbase64 --save
Now write an HTML to upload the image :
app.component.html:
<input
type="file"
class="input-upload"
name="myfile"
accept="image/*"
[(ngModel)]="uploadedImage"
(change)="changeListener($event)" />
Now in your component’s js file import the npm package that we have installed earlier:
app.component.ts:
const fileUpload = require('fuctbase64');
Now we need to implement the function “changeListener()” in our “app.component.ts” that we are using in HTML at the time of image upload.
changeListener($event): void {
fileUpload($event)
.then((data) => {
console.log("base64 :",data.base64);
//this.processImage(data.base64);
})
}
Now when you will upload an image, the method “changeListener()” will be called, and this method will convert your image into base64.
After uploading an image:
After uploading an image you can see your image is converted into base64, as you can see in below gif:
That's it.
Thanks for reading.
If you are interested in Nodejs or javascript then the below link will help you a lot:
Every Nodejs Developer Should Read These Articles