What is preventing me from obtaining the complete base64 string within an array in Ionic 3?

https://i.sstatic.net/xNkwl.pngIs there a way to efficiently convert multiple images at once using a for loop in Ionic 3?

Here is the code snippet I have:

   for (let i in serviceData) {
    // for(let i=0; i< this.adviceArray.length; i++) {
      console.log("online advices", serviceData[i]);
      this.texto = serviceData[i].texto;
      console.log("check online this.texto ", this.texto );
      this.imagen = serviceData[i].imagen;
      console.log("check online this.imagen", this.imagen);

      this.convertToDataURLviaCanvas(serviceData[i].imagen, "image/jpeg").then(base64 => {
        console.log("online base64", base64);
        this.base64Image = base64;
        console.log("online this.base64Image", this.base64Image);
        // this.adviceArrays64.push({'texto': this.texto, 'imagen': this.base64Image});
      });
      console.log("outer online this.base64Image", this.base64Image);
      this.adviceArrays64.push({'texto': this.texto, 'imagen': this.base64Image});
      console.log("online this.adviceArrays64", this.adviceArrays64);
      this.storage.set("travelTips64", this.adviceArrays64);
    }

I'm having trouble getting the full base64 strings of all images. How can I efficiently convert image URLs into base64 strings within an array and display all converted images in offline mode using Ionic 3?

Please provide a solution as soon as possible.

Answer №1

Resolved the issue above by utilizing the following function:

convertToDataURLviaCanvas(url, outputFormat) {
return new Promise((resolve, reject) => 
{
    let img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
        let canvas = <HTMLCanvasElement>document.createElement('CANVAS'),
            ctx = canvas.getContext('2d'),
            dataURL;
        canvas.height = 1000;
        canvas.width = 1000;
        ctx.drawImage(img, 0, 0);

        dataURL = canvas.toDataURL();
        //callback(dataURL);
        canvas = null;
        resolve(dataURL);
    };
        img.src = url;
});

}

To convert images from an array, invoke the function within your array like this:

let base64Image;
for (let i in serviceData) {
 this.imagen = serviceData[i].imagen;
 this.convertToDataURLviaCanvas(this.imagen, "image/jpeg").then(base64 => {
  base64Image = base64;
  this.texto = serviceData[i].texto;
  this.adviceArrays64.push({'texto': this.texto, 'imagen': base64Image});
   this.storage.set("travelTips64Image", this.adviceArrays64);
  });
}

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

In TypeScript, invoking a function from a subclass results in "<empty string>" being returned

Problem I encountered a roadblock while following a tutorial. When I call the 'bark()' method in the ShelterDog class, the browser console displays <empty string> instead of the expected output "WOOF WOOF!!!" Code // Dog.ts expor ...

Angular: Creating an input field with preset value that is immutable

I am a beginner with angular and I have been working on this code snippet: <mat-form-field appearance="outline" class="col-30" id="mat-identifier"> <mat-label> {{'columns.dashboard.identifier' | ...

The recommended filename in Playwright within a Docker environment is incorrectly configured and automatically defaults to "download."

Trying to use Playwright to download a file and set the filename using download.suggestedFilename(). Code snippet: const downloadPromise = page.waitForEvent('download', {timeout:100000}) await page.keyboard.down('Shift') await p ...

With TypeScript, you have the flexibility to specify any data type in the generic types when using the axios.get method

axios.get('/api') When working with TypeScript as shown above, it is important to designate types for better clarity. This allows us to reference the type definition of axios, like so: (method) AxiosInstance.get<any, AxiosResponse<any> ...

React and Enzyme are coming up empty-handed when trying to locate any elements within a functional component

After creating a simple functional component in React with Typescript, I encountered an issue while testing it. Every time I try to gather the divs, I keep receiving an empty object {}. Here is how the component is structured: export const TestComponent ...

Response received through GET call in text format

Implementing a typed response in a simple GET request seems to be causing a strange behavior in the compiler. The application compiles successfully, but a red error is returned with the message displayed in the VS Code screenshot below: ERROR in src/app/s ...

Ways to identify modifications from a BehaviorSubject and automatically trigger a response according to the updated value

I am currently implementing a BehaviorSubject for managing languages in my Angular project. I am also utilizing Angular Datatables and trying to dynamically change the language displayed in the data table based on the value returned from the subscription. ...

Deactivating the RouterLinkActive attribute based on certain conditions

When working with this straightforward menu item component: import { Component, Input } from '@angular/core'; @Component({ selector: 'nav-item', template: ` <a [routerLink]="routeUrl" routerLinkActive="active-link" ...

Encountering a 404 error when trying to retrieve the Next.js 14 API route, despite specifying the use of route

Currently, I am working with Next.js version 14.2.3 and attempting to access the /api/tmp API route from the chat.tsx component. However, I keep encountering a 404 error even though I am using the route.ts file. What could be causing this issue? UPDATE: C ...

Asynchronous handling of lifecycle hooks in TypeScript for Angular and Ionic applications

I'm intrigued by the idea of integrating TypeScript's async/await feature with lifecycle hooks. While this feature is undeniably convenient, I find myself wondering if it's considered acceptable to make lifecycle hooks asynchronous. After ...

Tips for creating an input box that only accepts floating point numbers:

I have a custom component - a text box that I am using in two different places. In one location, it accepts integers and in another, floats. For the integer validation (where dataType=2), I have successfully implemented it. However, for the float validat ...

The attribute 'fit' within the Button type cannot be reassigned to the identical attribute in the base type 'IButton'. The string type cannot be reassigned to the Fit type

In my coding project, I have a Button class that implements the IButton interface. class Button implements IButton { public fit = 'medium'; } declare type Fit = 'small' | 'medium' | 'large'; export interface IBu ...

AngularTS - Using $apply stops the controller from initializing

Every time I launch the application, the angular {{ }} tags remain visible. Removing $scope.$apply eliminates the braces and displays the correct value. I am utilizing Angular with Typescript. Controller: module Application.Controllers { export class Te ...

Developing Angular components with nested routes and navigation menu

I have a unique application structure with different modules: /app /core /admin /authentication /wst The admin module is quite complex, featuring a sidebar, while the authentication module is simple with just a login screen. I want to dyn ...

Is there an option for keyPrefix in i18next?

For my current project, I am utilizing both i18next and react-i18next. One useful feature of using the useTranslation hook from react-i18next is the "keyPrefix" option, which helps in reducing code duplication. However, there are instances where I need to ...

TypeScript: safely reassigning object properties for type safety

What I aim to achieve I am looking to create a JavaScript function that can remap property names of the first argument using the second argument. The goal is to utilize this remap function to generate query string parameters. For instance, transforming { ...

Introducing NextAuth: Empowering multiple users to access a single account

I've been pondering if it's possible to have multiple users for a single account provider. One idea is to create a session with a specific field indicating the active user (the one currently logged in) and then allow for easy switching between us ...

When trying to use TypeScript with next.js, encountering an unexpected token `?` error is not

Having an issue with next.js, the command npm run dev keeps failing due to a syntax error related to an optional property in a tsx file: Syntax error: Unexpected token 44 | 45 | type State<T_HT> = { > 46 | ghostHighlight: ?{ | ...

Jest Matcher issue: the value received must either be a promise or a function that returns a promise

As a dedicated practitioner of TDD, I am currently working on implementing an Exception in my code. Below is the test code I have written: it.each([[{ id: '', token: '', skills: [''] }, 'Unknown resource']])( ...

Utilizing generic union types for type narrowing

I am currently attempting to define two distinct types that exhibit the following structure: type A<T> = { message: string, data: T }; type B<T> = { age: number, properties: T }; type C<T> = A<T> | B<T>; const x = {} as unkn ...