1

This is a unique question: I don't want to use browser javascript to solve this, please read on...


I want to convert <img src="..."> to Base64 img tag by compiling the app (ng build or ng serve), to make the image load instantly - without further downloads other than the app itself, but also to make the image dynamicly changable while developing the app.

For example, here's a component - home.component.html:

code before compiling (notice the base64 directive, its just an idea though):

<img src="assets/images/phone.png" base64>

code wanted after compiling:

<img src="data:image/png;base64,iVBORw0......rest-of-base-64-goes-here">


Important: This should happen without running a front-end javascript operation by the user, or by calling the image file. (by means, the file phone.png will not even exist when compiling)

I still want to edit the local image phone.png while developing.

I know I can convert the file to base64 manually and update it in my component, but that's exactly what I don't want to do - I want it to happen automatically to save time.

That means the image will sit in the component itself, in one of the .js files that has been compiled, and therefore will load instantly with the app.


Idea: It would be nice and easy to have a directive that would take care of that.

something like <img src="phone.png base64>**

I assume it can be done using node/webpack in some way, but I have not idea how.

Community
  • 1
  • 1
Elron
  • 1,235
  • 1
  • 13
  • 26
  • Possible duplicate of [How to convert image into base64 string using javascript](https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript) – Smokey Dawson Aug 15 '19 at 03:11
  • @SmokeyDawson nothing related to angular components there – Elron Aug 15 '19 at 03:12
  • angular is javascript, your best bet is to create a `convertToBase64()` method that follows one of the answers in the linked question and then in your html do this `[src]="convertToBase64('assets/images/home/home-phone.png')"` – Smokey Dawson Aug 15 '19 at 03:14
  • @SmokeyDawson I understand your answer, however I don't want to compile it on the user's front end. I want it to compile when I run `ng build` and move into my JS chunk file. – Elron Aug 18 '19 at 05:38

1 Answers1

2

You need to use readAsDataUrl()

function getBase64(event) {
   let me = this;
   let file = event.target.files[0];
   let reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     //me.modelvalue = reader.result;
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}

Hope can help you..

Shah
  • 557
  • 5
  • 15
  • Thank you for your time @Shah . How do I make the file compile to base64 when running `ng build`? – Elron Aug 18 '19 at 05:40