What is the most efficient way to transform various colors using graphicsmagick and typescript?

Seeking a way to convert colors in a png image using GraphicsMagick, my current hardcoded code is:

await gm("input.png")
    .fill("green")
    .opaque("blue")
    .fill("red")
    .opaque("yellow")
    .write("output.png", function (err) {
      if (err) console.log(err);
    });

While this works fine, I wish to make it more flexible by eliminating hardcoding. How can I achieve this using a buffer?

I attempted the following approach but it doesn't work as intended:

  let colors: { op: string; fi: string }[] = [
    { op: "blue", fi: "red" },
    { op: "yellow", fi: "green" },
  ];

  let imageFileBuffer = await fs.readFileSync("input.png");

  colors.forEach(async (element) => {
    console.log(element);
    await gm(imageFileBuffer).fill(element.fi).opaque(element.op);
  });

  await gm(imageFileBuffer).write("output.png", function (
    err
  ) {
    if (err) console.log(err);
  });

Can anyone point out what might be wrong with this approach?

Answer №1

An issue arises due to the lack of separation between image and image-processing tasks. There is no need for await on image-processing!

 let colors: { op: string; fi: string }[] = [
    { op: "blue", fi: "red" },
    { op: "yellow", fi: "green" },
  ];

  let imageFileBuffer = await fs.readFileSync("input.png");

  let image = gm(imageFileBuffer);

  colors.forEach((element) => {
    console.log(element);
    image.fill(element.fi).opaque(element.op);
  });

  image.write("output.png", function (err) {
    if (err) console.log("changeImageColors Error: ", err);
  });

Helpful pointers:

  • Making GraphicsMagick Asynchronous in Node.js
  • Executing Asynchronous if Statements with GraphicsMagick in Node.js

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

How do I define two mutations in a single component using TypeScript and react-apollo?

After exploring this GitHub issue, I have successfully implemented one mutation with Typescript. However, I have been unable to figure out how to use 2 mutations within the same component. Currently, there is only a single mutate() function available in t ...

What is the best way to transform a JavaScript object into a chain of interconnected links?

My goal is to transform an object structure like the one below... var obj1 = { firstName: 'John', lastName: 'Green', car: { make: 'Honda', model: 'Civic', revisions: [ { miles: 10150, code: & ...

Utilizing mp3 files in Webpack 5 with Next.js

After hours of struggling with my current project using [email protected] and webpack v5, I found myself stuck on fixing mp3 loading. Despite trying various solutions from Stack Overflow and GitHub, none seemed to work for me. Type error: Cannot find ...

Context API is failing to work in components that use children when the version is v16.6.0 or higher

Currently, I am utilizing the latest context API of React (v16.6.0 or higher) by specifying the public static contextType inside the component that consumes the context. Everything works smoothly unless the component declaring the Provider directly include ...

How can you determine the data types of properties within a blank class object using Typescript and Angular?

Class Example{ constructor( public x: number, public y: string ) {} } let e = new Example(); Is there a way to programmatically determine the data type of e.x or e.y in TypeScript? ...

Zod Entry using standard encryption key

I'm attempting to define an object type in zod that looks like this: { default: string, [string]: string, } I've experimented with combining z.object and z.record using z.union, but the validation results are not as expected. const Local ...

What is the reason behind localStorage.getItem consistently returning a string value?

Something strange is happening. In the lib.dom.d.ts file, the type for localstorage.getItem shows as 'string | null', but in my app it always returns a string. Why is this discrepancy occurring? ...

Styling Excel Columns in Angular

Is there a way to make the column titles bold in an Excel worksheet using the json_to_sheet function? Specifically, how can I bold the ID or format the first cell? var ws = XLSX.utils.json_to_sheet([{ID:"ID"}], {header: ["ID"], skipHeader: true}); let exce ...

What is the best way to invoke a function in a specific child component from its parent component?

It seems that I might have provided too much information, but the main question remains: how can I call a method in the child component from the parent template's click() event. <button(click)='get()'>GET</button> In my case, th ...

Converting a string to a date type within a dynamically generated mat-table

I am working on a mat-table that shows columns for Date, Before Time Period, and After Time Period. Here is the HTML code for it: <ng-container matColumnDef="{{ column }}" *ngFor="let column of columnsToDisplay" > ...

The .env file setting does not take precedence over the default value in the

I am facing an issue with my JSON file that contains the default convict configuration. Here is a simplified version of the file: { "env": { "doc": "The application environment.", "format": [" ...

Is it possible to implement drag and drop functionality for uploading .ply, .stl, and .obj files in an angular application?

One problem I'm facing is uploading 3D models in angular, specifically files with the extensions .ply, .stl, and .obj. The ng2-upload plugin I'm currently using for drag'n'drop doesn't support these file types. When I upload a file ...

Understanding the data types of functions in TypeScript can be quite important for

What type of information is required after the colon : in this specific function? public saveHistory(log: String): "HERE!" { return async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => { try { ...

The declared type 'never[]' cannot be assigned to type 'never'. This issue is identified as TS2322 when attempting to pass the value of ContextProvider using the createContext Hook

I'm encountering an issue trying to assign the state and setState to the value parameter of ContextProvider Here's the code snippet:- import React, { useState, createContext } from 'react'; import { makeStyles } from '@material-ui ...

Is it possible to utilize a React component within the DataGrid cell instead of the standard cell types like 'string', 'number', 'date', and 'dateTime' in Material UI?

Using React, Material UI, and TypeScript I am trying to embed a React component into the cell of a DataGrid but have encountered an issue. I have explored custom column types for cells here, however, it only allows me to manage string formats, whereas I ...

My goal is to create a carousel using Vue 3 with the Composition API and TypeScript

Creating a carousel with Vue 3 and TypeScript has been quite challenging for me. I heard about using "vue-awesome-swiper" to build a carousel, but I couldn't find a tutorial on how to use it. Does anyone know how to utilize this tool effectively? Alte ...

Filter a two-dimensional array based on the presence of a string value found in the second array

My logic for this assignment is not very good, as I need to filter a 2D array based on the values of another array. Let me provide an example of the 2-Dimensional Array: const roles = [ ['roles', 'admin', 'write'], ['ro ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

Ngrx: Uniting the simple store method with entity state - A comprehensive guide

Apologies if this has been asked before. I am struggling to find a solution for my current issue. I am trying to make my store state more complex using ngrx/entity, but I am having trouble implementing it correctly. Below are the models in my reducer: e ...

Set up a unique database in memory for every individual test

Is it feasible to create an in-memory database for each test scenario? My current approach involves using the code snippet below, which functions properly when running one test file or utilizing the --run-in-band option. import _useDb from "@/useDb&q ...