Obtaining a string representation of an image through base64 encoding

I am attempting to retrieve the base64 string of an image file URI using '@ionic-native/base64' from '@ionic-native/image-picker', but it seems that the image is broken after running this code. Are there any suggestions on how to fix this?

Here is my HTML:

<img [src]="base64ImageChosen" *ngIf="base64ImageChosen"/>

These are my picker options:


this.pickerOptions = {
    maximumImagesCount: 1,
    width: 10,
    height: 10,
    quality: 100,
    outputType: 0
};

This is my code snippet:


chooseImage() {
    this.imagePicker.getPictures(this.pickerOptions).then((results) => {
        for (let i = 0; i < results.length; i++) {
            let filePath: string = results[i];

            this.base64.encodeFile(filePath)
                .then((base64File: string) => {
                    this.base64ImageChosen = base64File
                }, (err) => {
                    console.log(err);
                })
                .then((res) => 
                    this.myForm.patchValue({ imageChosen: this.base64ImageChosen })
                )
        }
    }, (err) => { });
}

Answer №1

If you want to showcase the images on your webpage, utilize window.URL.createObjectURL() function to generate a unique string representation for your image object.

let img = new Image()
img.src = filePath;
base64SelectedImage = URL.createObjectURL(img);

Based on your provided code snippet, it appears that you are aiming to exhibit multiple images stored within a directory. It is presumed that you are iterating through your HTML template with the help of ngFor directive.

Answer №2

If you want to achieve this functionality, you can utilize the imagePicker method like so:

this.imagePicker.getPictures(options).then((result) => {
      for (let i = 0; i < result.length; i++) {
        let base64Image = 
data:image/jpeg;base64,
+result[i];
        this.imagesArray.push(base64Image);
    }
    })

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

Ways to dynamically manipulate HTML elements in Angular 5

Recently, I've been attempting to programmatically transform an HTML element. Strangely, when I update the transform value in the console tab, it changes successfully, but for some reason it doesn't reflect in the element tab of the browser. onD ...

Enhancing Typescript Arrow Function Parameters using Decorators

Can decorators be used on parameters within an arrow function at this time? For instance: const func: Function = (@Decorator param: any) => { ... } or class SomeClass { public classProp: Function = (@Decorator param: any) => { ... } } Neither W ...

Tips for utilizing Provide/Inject in Vue.js while leveraging TypeScript

I am currently working with Vue.js and TypeScript along with the vue-property-decorator package. The documentation suggests that I can achieve something like this: import { Component, Inject, Provide, Vue } from 'vue-property-decorator' const s ...

Adding custom type definitions for an untyped npm module in TypeScript 2

Despite attempting various methods recommended in other sources, I am struggling to configure a TypeScript project that utilizes an untyped NPM module. Below is a simplified example along with the steps I have taken. Let's imagine, for this demonstra ...

When using TypeORM's save() method with an array of objects, the @PrimaryColumn() annotations are ignored, resulting

My current situation involves an entity called Point: @Entity() export class Point { @PrimaryGeneratedColumn('uuid') id: string; @IsUUID() @PrimaryColumn({ type: 'uuid', ...

How can you retrieve the property value from an object stored in a Set?

Consider this scenario: SomeItem represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem in untyped land). Let's say we have a Set: mySet = new Set([{item: SomeItem, s ...

Combining files/namespaces/modules in Typescript: How to do it?

Even though I believe the solution may be simple, understanding how to merge enums across multiple files is eluding me when reading through the documentation. // a.ts enum Color{ RED, BLUE } // b.ts enum Day{ MONDAY, TUESDAY } // c ...

Can you determine the base class type based on the derived class?

I've encountered a typings issue while working on a new feature for my TypeScript library. Let's dive into the problem with the following example: class Base { ... } class User extends Base { ... } class Product extends Base { ... } class Comp ...

How to add unique elements to an array in Angular without any duplicates

I need help with pushing elements into an array and decrementing the count of it without duplicates in angular. Any assistance would be greatly appreciated ...

The Dynamic Duo: Typescript and Knex

I'm new to TypeScript and currently working on a node application using Express, Postgresql, and Knex. I'm a bit confused about when to apply type definitions in my code. Looking at other projects for guidance has left me even more puzzled as to ...

Execute --runTestsByPath on two or more distinct paths

Currently, I am utilizing the jest cli for running my tests. Jest offers a useful cli option known as --runTestsByPath, which allows me to specify the locations of my tests. Despite having unit tests spread out in various directories within my repository, ...

Issue with clicking checkbox using Protractor

Having trouble clicking a checkbox within an ng-repeater using Protractor with the following HTML structure. https://i.sstatic.net/FpY1x.png The snippet of code I'm currently using is as follows: element.all(by.repeater('user in siteUsers | fi ...

When trying to access the payload in a reducer, Typescript throws an error

I am facing an issue with my reducer in Typescript - Specifically, when trying to access the formError property in the payload within the second switch case. import actionTypes, { ActionCreatorType, ReducerType } from './types'; const initialSt ...

Getting a multitude of contacts exceeding 1000 with ngCordova in AngularJS

I am currently working on an app using the Ionic framework that allows users to view and select contacts from their device. I am utilizing ngCordova's $cordovaContacts module to retrieve the contacts. Here is the service code responsible for fetching ...

Discover the Hassle-Free Approach to Triggering Angular Material Menu with ViewChild and MatMenuTrigger

Is there a way to programmatically open an Angular Material menu using a Template Reference Variable on a button trigger that is accessed in the component through ViewChild? I want the menu to open when the mouse hovers over it, instead of just clicking i ...

Creating a string array within an array in TypeScript

Struggling to return a type-safe Typescript v3.5 array without having to declare it within the method body? This array should consist of multiple string arrays. Desiring something along the lines of: foo(): Array<Array<string>>: // perfo ...

The TS type guard fails to identify a non-empty property in a class object

Encountering an issue with TypeScript that involves a class property typed as AmplitudeFeatureFlags | {} = {}; initialized as an empty object. Attempting to retrieve a value from this class property using a method that takes in a property name argument of ...

Exploring the incorporation of interfaces into Vue.js/Typescript for variables. Tips?

I have an interface:   export interface TaskInterface{ name: string description1: string time: string } and a component import { TaskInterface } from '@/types/task.interface' data () { return { tasks: [ { name: 'Create ...

Modifying the <TypescriptModuleKind> setting for typescript transpilation in project.csproj is not supported in Visual Studio 2017

I recently encountered an issue with changing the module kind used by the transpiler in Visual Studio. Despite updating the <TypescriptModuleKind> in the project's project.csproj file from commonjs to AMD, the transpiler still defaults to using ...

What are the steps to set up a dictionary with predetermined values?

My task is to create a pre-defined dictionary where the key represents a city and the value is an array of zones in that city. Here is my attempt: export const cityToZone: { [city: string]: Array<string> } = [ {city:'New York', [&apos ...