1

I have a problem converting local image inside my angular project folder to base64 and displaying it. I have this structure: src > app > screenA > components > gallery > mock > images (here I store images image_1.jpg, image_2.jpg ...) I then have this structure: src > app > screenA > components > gallery > mock > mock_images.ts:

import {Image} from '....';

export const mockImages: Image[] = [
  {
    imageSrc: 'image_1.jpg',
    imageDesc:'Description of the first picture',
  },
  {
    imageSrc: 'image_2.jpg',
    imageDesc: 'Description of the second picture.',
  },
  {
    imageSrc: 'image_3.jpg',
    imageDesc: 'Description of the third picture.',
  },
  {
    imageSrc: 'image_4.jpg',
    imageDesc: 'Description of the fourth picture.',
  },
  {
    imageSrc: 'image_5.jpg',
    imageDesc: 'Description of the fifth picture.',
  },
  {
    imageSrc: 'image_6.jpg',
    imageDesc: 'Description of the sixth picture.',
  },
];

Then, inside my service I define:

mockImagesPath = '.mock/images';
mockImages: Image[] = JSON.parse(JSON.stringify(mockImages));
data: Image[] = [];

My html:

<div *ngFor="let img of imgs">
  <img [src]="img.imageSrc" />
</div>

In the ngOnInit I will call the service method and then fill the imgs with data coming from service:

convertImg(): void {
    const numberOfFiles = this.mockImages.length;
    for (let i = 0; i < numberOfFiles; i++) {
      const reader = new FileReader();
      const url = reader.readAsDataURL(`${this.mockImagesPath}/${this.mockImages[i].imageSrc}`);
      this.data.push(new Image(url, this.mockImages[i].imageDesc));
    }
  }

Although this doesn´t work. Can you suggest some fix?

Victoria
  • 187
  • 12
  • What is the error? – onetwo12 Jan 12 '23 at 12:52
  • at const url in the convertImg() saying "Argument of type 'string' is not assignable to parameter of type 'Blob'" – Victoria Jan 12 '23 at 12:57
  • https://stackoverflow.com/questions/59110683/how-to-convert-a-string-to-actual-file-that-was-generated-from-filereader-readas – onetwo12 Jan 12 '23 at 13:04
  • I think that you are using readAsDataURL for the wrong reason, https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL – onetwo12 Jan 12 '23 at 13:07
  • let file = new File(blob,"filename.pdf",{type:"optional mime type"}); does not work for me. Angular cannot find "blob" – Victoria Jan 12 '23 at 13:22
  • try: reader.onload = (event) => { const url = event.target.result; this.data.push(new Image(url, this.mockImages[i].imageDesc)); }; reader.readAsDataURL(`${this.mockImagesPath}/${this.mockImages[i].imageSrc}`); – onetwo12 Jan 12 '23 at 16:11
  • 1
    @onetwo12 thank you for your time and advices. This is what helped me solve my issue - https://stackoverflow.com/questions/56686802/getting-image-from-assets-and-converting-it-to-base64 – Victoria Jan 13 '23 at 11:27

0 Answers0