How to lazy load images in Angular from a base64?

Viewed 33

I would load images in my Angular project in lazy way, the issue is that my API returns a base64 image instead of a file.

So i was trying to do something like this:

<img class="image-cover" *ngIf="product.image" [src]="'https://localhost:44350/api/images/00168780351/117920?types=products&isThumbnail=true'" loading="lazy"/>

But obviously the src is set as link and no image is shown.

What would be the way to perform that? Should i modify my API by returning a file instead?

1 Answers

The return value of my API was a text/plain as data:image/png;base64,iVBORw0... it wasn't working i src so instead i've changed my API to return image/jpg.

To do so i had to change my API as this:

[HttpGet("{idProducts}")]
        public FileContentResult GetImages(int idProducts, string idShopsGroup, ImagesTypes types, bool isThumbnail = false)
        {
            string base64Image = ImagesHelper.GetImages(idProducts, idShopsGroup, types, isThumbnail);
            if (base64Image != null)
            {
                byte[] bytes = Convert.FromBase64String(base64Image);

                return new FileContentResult(bytes, "image/jpg");
            }

            return null;
        }

Where instead of returning the plain base64 i've removed data:image/png;base64, from it and had to convert it to bytes and then return a FileContentResult.

Related