Tips on adjusting the size of a base64 image in Angular

I have been attempting to resize a base64 image without success. I tried using canvas, but it didn't work. I'm not sure what the issue is... Here is the code snippet I used:

const canvas = document.createElement('canvas'),
             ctx = <CanvasRenderingContext2D>canvas.getContext('2d');
        canvas.width = 100;
        canvas.height = 100;
        const img = new Image();
        img.src = this.SelectedFile.src;
        ctx.drawImage(img , 0, 0, 100, 100);
        this.SelectedFile.src = ctx.canvas.toDataURL();

Does anyone have a different approach or insight into what might be causing the problem?

Answer №1

To optimize images, you can use this external function:

function resizeImage(src, newWidth, newHeight) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.src = src;
    image.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = newWidth;
      canvas.height = newHeight;
      const context = canvas.getContext('2d');
      context.drawImage(image, 0, 0, newWidth, newHeight);
      const imageData = context.canvas.toDataURL();
      resolve(imageData);
    }
    image.onerror = error => reject(error);
  })
}

After defining this function, you can call it like this:

resizeImage(base64Data, 100, 100).then(resizedData => {
  this.updatedBase64 = resizedData;
})

Answer №2

I found a solution that worked well for me when I needed to resize base64 images within my angular application and HTML:

<style>
    .resized {
        width: 200px;
        height: 200px;
        transform-origin: top left;
        transform: scale(0.8);
    }
</style>

<div class="resized">
 <img src="data:image/png;base64,iVB....."></img>
</div>

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

Using global variables in local Angular-cli components by importing them

Here is an example of my folder structure in Angular CLI: MyApp/ src style/ page/ normalize.less styles.less In my angular-cli.json file, I have the following configuration: "app":{ "styles": [ "./style ...

Ways to resolve the issue of the 'setConfirmDelete' property not being found on type 'JSX.IntrinsicElements' in React.js

index.tsx const setConfirmDelete = (state, close) => { return ( <Modal show={state} onHide={close}> <Modal.Header> <Modal.Title>Title</Modal.Title> </Modal.Header> <Modal.Body> 'T ...

At what juncture is the TypeScript compiler commonly used to generate JavaScript code?

Is typescript primarily used as a pre-code deployment tool or run-time tool in its typical applications? If it's a run-time tool, is the compiling done on the client side (which seems unlikely because of the need to send down the compiler) or on the s ...

The Angular array stays undefined when JSON data is being passed

I am facing an issue with my API that provides JSON data related to football matches. Even after passing this data to the frontend (angular), I am encountering a problem where the array remains undefined. JSON Data: "match_id":"194200", "country_id":"41" ...

The Bootstrap 4 dropdown feature is not functioning properly in Angular's production environment

While developing my Angular application with Bootstrap 4, I encountered an issue with the dropdown functionality. In the development mode, everything works perfectly. However, in production mode, I received the following error: Uncaught Error: DROPDOWN: ...

Apologies, an issue has occurred: Unhandled promise rejection: ReferenceError: localStorage is undefined

I'm currently developing a Single Page Application with Angular/Typescript. The initial page is a Login Page, and upon successful authentication, the following code is used to navigate to a new page: this.router.navigate(['/productionFiles' ...

Utilize TypeScript functions within Angular applications

I have successfully created a TypeScript module and after compiling it, I am generating a JavaScript file. However, when I try to use this JavaScript file within my Angular project in the index.html, it loads but I cannot access its functionality from any ...

Tips for resolving the issue with the 'search input field in the header' across all pages in angular 5 with typescript

I currently have a search field in the header that retrieves a list of records when you type a search term and click on one of them. The search function utilizes debounceTime to reduce API requests, but I'm encountering an issue where the search doesn ...

Prevent automatic suggestions from appearing in Ionic app on Android

Our Ionic v4 (Angular, Cordova) app features form input fields (<ion-input>) like the example below: <ion-input formControlName="firstName" type="text" inputmode="text" autocapitalize="sentences"></ion-input> When running the Android ap ...

Is it possible to pass a Styled Components Theme as Props to a Material UI element?

After spending 9 hours scouring the internet for a solution, I am at my wit's end as nothing seems to work. Currently, I am developing a React component using TypeScript. The issue lies with a simple use of the Material UI Accordion: const Accordion ...

The results of Angular CI tests vary between local environment and DevOps platform

I've encountered an issue with my pipeline. While I am aware that my current Karma tests are not working properly, there seems to be a discrepancy between running the tests on my local machine and on DevOps pipelines. karma.conf.ci.js // Configurat ...

Implementing global user authentication state with Zustand in Next.js version 13.4.9

I'm grappling with incorporating zustand into my Next.js 13.4.9 app, specifically for managing global authentication state. Below is the code snippet I have in my application: zustand store: // /src/store/AuthStore.ts import { create } from 'zu ...

Can you explain the process of the assignment part in the code line of Angular2?

I’ve been delving into the angular2-rxjs-chat project on GitHub to enhance my knowledge. Within the code linked here, there is a specific line of code that caught my attention: threads[message.thread.id] = threads[message.thread.id] || message.thread; ...

Adjust the icon's color after it has been clicked

How can I make the icon change color after it's clicked in Angular 4 with Bootstrap? I have icons displayed in panels using *ngFor loop and currently, when I click on an icon, it changes color in all panels. How do I make it change color only in the s ...

Troubleshooting Puppeteer compatibility issues when using TypeScript and esModuleInterop

When attempting to use puppeteer with TypeScript and setting esModuleInterop=true in tsconfig.json, an error occurs stating puppeteer.launch is not a function If I try to import puppeteer using import * as puppeteer from "puppeteer" My questi ...

Cypress eliminating the "X-CSRFToken" header

There seems to be an issue with the Cypress test runner where it is removing X-CSRFToken from the request header, leading to a 403 Forbidden error. I have compared the headers between a manual run and a Cypress test run, and you can see the difference in t ...

I need help differentiating "namespace" from "static attributes" in TypeScript

Separating namespace from static properties in TypeScript can sometimes be tricky. error: 'ClassA' only refers to a type, but is being used as a namespace here. class ClassA { static ClassB = class { }; } type T = ClassA // ok type T = C ...

Detecting Browser Window Width Dynamically [JavaScript]

I want to create a dynamic variable that updates automatically as the browser window is resized in pixels. I need this variable to change without needing the page to refresh, and I don't want it written in the HTML document as it's used further d ...

Is it possible to compile a .ts file at the root level without following the tsconfig.json configurations?

After dealing with the challenge of having both .ts and .js files coexisting in each folder for months, I have finally managed to get the app to compile correctly. The transition from JS to TS brought about this inconvenience, but the overall benefits make ...

Connecting the output of an *ngFor loop to a universal variable

*ngFor="let item of items | filter:{ name: searchString } : searchString as filteredItems" and then afterwards <button (click)="doSomething(filteredItems)> The variable filteredItems is a local variable that is only accessible within the *ngFor lo ...