Present various image formats encoded in base64 retrieved from the backend API using Angular 7

I have an API that provides images in base64 format, which can be in various file formats like .png, .jpg, .svg, etc.

I am looking to display these images in my application using:

<img *ngIf="imageBase64" [src]="imageBase64 ? ('data:image/svg+xml;base64,' + imageBase64 | safe) : ''" alt="" />

What is the best way to display images in different formats in my application?

Thank you in advance.

Example

PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4NCjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEyMzUiIGhlaWdodD0iNjUwIiB2aWV3Qm94PSIwIDAgNzQxMCAzOTAwIj4NCjxyZWN0IHdpZHRoPSI3NDEwIiBoZWlnaHQ9IjM5MDAiIGZpbGw9IiNiMjIyMzQiLz4NCjxwYXRoIGQ9Ik0wLDQ1MEg3NDEwbTAsNjAwSDBtMCw2MDBINzQxMG0wLDYwMEgwbTAsNjAwSDc0MTBtMCw2MDBIMCIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjMwMCIvPg0KPHJlY3Qgd2lkdGg9IjI5NjQiIGhlaWdodD0iMjEwMCIgZmlsbD0iIzNjM2I2ZSIvPg0KPGcgZmlsbD0iI2ZmZiI+DQo8ZyBpZD0iczE4Ij4NCjxnIGlkPSJzOSI+DQo8ZyBpZD0iczUiPg0KPGcgaWQ9InM0Ij4NCjxwYXRoIGlkPSJzIiBkPSJNMjQ3LDkwIDMxNy41MzQyMzAsMzA3LjA4MjAzOSAxMzIuODczMjE4LDE3Mi45MTc5NjFIMzYxLjEyNjc4MkwxNzYuNDY1N7..., it will work. I need a generic format to display images regardless of their file format (e.g., .png, .jpg).</p>

<p>Is there a way to achieve this by using a format like <code>data:image/svg+xml/png/jpg? Any suggestions are appreciated.

Answer №1

To conduct this task, a function must be established to initially decrypt the encoded sequence, subsequently identifying the type from the decrypted information within a defined scope of potential options.

getType(imageBase64) { 
    let extension = undefined; 
    const decodedString = window.atob(imageBase64); //decipher the string;
    const lowerCase = decodedString.toLowerCase();
    // pinpoint the extension within the decoded string
    if (lowerCase.indexOf("png") !== -1) extension = "png"
    else if (lowerCase.indexOf("svg") !== -1) extension = "svg+xml"
    else if (lowerCase.indexOf("jpg") !== -1 || lowerCase.indexOf("jpeg") !== -1)
        extension = "jpg"
    // include additional scenarios if required..
    return extension;
}

Following this, apply the aforementioned function within your designated framework.

<img *ngIf="imageBase64" [src]="imageBase64 ? ('data:image/' + getType(imageBase64) + ';base64,' +imageBase64 | safe) : ''" alt="" />

Answer №2

Give this a shot:

<img *ngIf="showImage" [src]="showImage.data">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Angular2 framework will sometimes send an OPTIONS method request instead of an http.GET when

I am currently attempting to implement basic authentication in my Angular2 application. public login() { // Setting basic auth headers this.defaultHeaders.set('Authorization', 'Basic ' + btoa(this.username + ':' + thi ...

The 'prop' property is not found within the 'IntrinsicAttributes & CustomComponentProps' type

I developed a custom module with an interface for props, extending props from a file called /types/SharedProps.d.ts. However, when I import this module into a sample project, the extended props are not included in the component. Below is how the module&apo ...

Verify enum values within controller function

I am dealing with a query parameter in my REST API that should be restricted to specific values according to an enum type. I need to find a way to handle a "Bad Request" error if the client provides any value outside of this enum. Here is what my enum loo ...

What is the best way to see if a variable is present in TypeScript?

I am facing an issue with my code that involves a looping mechanism. Specifically, I need to initialize a variable called 'one' within the loop. In order to achieve this, I first check if the variable exists and only then proceed to initialize it ...

Ways to divide numerical values in Angular?

I need to format a number in the input field which can be either 1000000 or 1000. The desired format is: 1 000 000 or 1 000, respectively. I attempted using a Pipe method but it didn't yield the expected result. What could be causing this issue? {{ ...

Encountering a problem when using the routingService to navigate inside a JavaScript function

Within my Angular component, I have a method called onCellPrepared. In this method, I am using jQuery to attach a span tag. I want to be able to trigger an Angular service to navigate to another page when the span tag is clicked. How can I successful ...

Is there a convenient method to combine arrays of objects in JavaScript using ellipses or an equivalent approach?

let array = [ {id: 1, data: {foo: "bar 1"}}, {id: 2, data: {foo: "bar 2"}} ]; //If ID doesn't exist, add new element to the array array = [...array, {id: 3, data: {foo: "bar 3"}}] console.log(array); //If ID exists, replace data object with new ...

React with Typescript: Potential occurrence of an undefined object

While working with React and TypeScript, I encountered the error Object is possibly 'undefined' when using language.toLowerCase().includes(selectedCategory). To address this issue, I implemented a check as shown below. Although this resolved th ...

Tips for troubleshooting JavaScript in an Angular 5 application using Visual Studio 2017

I recently developed an Angular 5 web application using VS2017. Initially, the app was functioning well until I decided to enable javascript debugging. Post that change, upon launching the app, I encountered the following error: https://i.sstatic.net/ygq ...

Developing a Library for Managing APIs in TypeScript

I'm currently struggling to figure out how to code this API wrapper library. I want to create a wrapper API library for a client that allows them to easily instantiate the lib with a basePath and access namespaced objects/classes with methods that cal ...

Using TypeScript to destructure by providing types

I encountered an issue while trying to destructure some code. The error message Property 'name' does not exist on type '{}'. is appearing. I thought about using let user:any = {}; as a workaround, but that goes against the eslint rule o ...

Ways to manage drag and drop functionality within Cypress when traditional Cypress techniques are not effective

I need help with the drag and drop function in Cypress. I have tried three different methods but none of them seem to work. I have included my code below, which is not functioning as expected. Does anyone have any suggestions on what might work better in t ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

Troubleshooting TypeError: Not a Function in Typescript Mocha Testing

Currently, this is the class I am working with: import * as winston from 'winston'; const {combine, timestamp, printf, label, json} = winston.format; import {isEmpty, isNil} from 'lodash'; import {Log} from './Log'; export cl ...

Reactive form within a form

I am working on an angular application that involves a nested reactive form. I would appreciate it if you could review my method of nesting the form by passing the parent form reference in the child component and let me know if this approach is appropria ...

Incorporate Add to Homescreen functionality into your Angular 4 Project using JavaScript

Currently I am in the beginning stages of learning Angular development. One of my assignments involves integrating the add to homescreen jQuery plugin into one of my pages. This is my attempt at implementing it in my home.component.ts file: ngAfterViewIn ...

Tips for launching Nx serve in debug mode for Angular using VSCode

When running my Angular Nx project in the VSCode debugger, I encounter an issue with using yarn. yarn start successfully executes the nx serve command when run from a terminal. However, the same yarn start command fails when executed through VSCode debug ...

Having trouble with Angular and PrimeNG: CSS styling not rendering

I recently started using PrimeNG but I'm having trouble getting the styles to look good. Despite not seeing any errors in ng serve or the browser logs, the components (a calendar and 3 buttons) appear dull. app.module.ts import { BrowserModule } fro ...

Ensuring data types for an array or rest parameter with multiple function arguments at once

I am looking for a way to store various functions that each take a single parameter, along with the argument for that parameter. So far, I have managed to implement type checking for one type of function at a time. However, I am seeking a solution that al ...

Communicating Data Between Controllers in Node.js

Within my PlantsController, I extract the Plants using the following method: function getAll() { const plants= HttpRequestPromise.get(config.ApiURL+'allPlants', config.head); return plants; } export class PlantsController { ... public ...