How do I adjust brightness and contrast filters on a base64 URL?

When presented with an image in base64 format like this:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg==

What is the most efficient method to programmatically alter a filter (such as brightness or contrast) without generating any img or canvas elements in the view? And once modified, how can it be converted back to a base64 URL?

Answer №1

To achieve this, you can place the image on an HTML canvas with applied filters and then convert that canvas into a base64 URL without adding it to the document.

By following these steps asynchronously:
This process typically takes about 1-10ms

function applyFiltersToImage(imageURL, callBack) {
    // load the image url into an image object
    const image = new Image();
    image.src = imageURL;

    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext('2d');
    image.onload = () => {        
        canvas.width = image.width;
        canvas.height = image.height;

        // apply css filters here
        ctx.filter = 'brightness(0.5) contrast(2)';

        ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        
        // turn canvas back into a base64 image URL
        callBack(canvas.toDataURL("image/png"));
    }
}

If you already have the Image instance loaded, you could also perform the operation synchronously.

Here is how you would do it synchronously:

function applyFiltersToImageSync(imageObject) {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext('2d');    
    canvas.width = imageObject.width;
    canvas.height = imageObject.height;

    // apply css filters here
    ctx.filter = 'brightness(0.5) contrast(2)';

    ctx.drawImage(imageObject, 0, 0, canvas.width, canvas.height);
    //turn canvas back into a base64 image
    return canvas.toDataURL("image/png");
}

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

Is there a way to effectively incorporate react-native with php and ensure that the data returned by the fetch function is

I'm struggling to make my return value work in this code. Has anyone had success using react-native with php and fetch json? Any tips or advice would be greatly appreciated. PHP $myArray = array(); $myArray['lat'] = $_POST['lat']; ...

Error TRPCClient: The unexpected presence of the token "'<'", ""<!DOCTYPE "... invalidates the JSON format within Next.JS

Encountering an error in the authentication call back page: TRPCClientError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON in Next.JS. The issue occurs in src/app/auth-callback/page.tsx and here's the relevant code ...

The request to login at the specified API endpoint on localhost:3000 was not successful, resulting in a

As I continue to develop my programming skills, I have been working on configuring a database connected with nodejs in the same folder. However, when trying to make an ajax request to the database, I encountered an error indicating that the database may be ...

"Exploring the world of 3rd party libraries in Angular2 with Typescript and Webpack

I've begun working on a fantastic seed project that can be found at: https://github.com/AngularClass/angular2-webpack-starter However, I've encountered an issue with integrating third-party modules. Can anyone offer guidance on how to properly a ...

Tips for Elevating State with React Router Version 6

Looking for advice on sharing state between two routes in my project. I'm debating whether to lift state up from my AddContact component to either the Layout or App components in order to share it with the ContactList. The Layout component simply disp ...

Creating a universal parent constructor that can take in an object with keys specific to each child class

I am looking to create a base class with a constructor that allows for all the keys of the child class to be passed. However, I am facing a challenge because 'this' is not available in constructors. Here is what I hope to accomplish: class BaseCl ...

The child component is failing to detect changes, consider using alternative methods like ngDoCheck to update the component's value

Within the childComponent @input() method, I am sending an array of objects where each object has 3 properties: name, id, and selected (boolean). My goal is to change only the selected property in the array and pass it to the child component for rendering. ...

A proposal for implementing constructor parameter properties in ECMAScript

TypeScript provides a convenient syntax for constructor parameter properties, allowing you to write code like this: constructor(a, public b, private _c) {} This is essentially shorthand for the following code: constructor(a, b, _c) { this.b = b; thi ...

When comments are submitted via AJAX, they are displayed twice, but upon reloading the page, they only appear once

After using the codes below to add a comment to a post and display it without refreshing the page, I encountered an issue where the comment is displayed twice instead of once. However, the comment is only saved once in the database. Interestingly, when the ...

Utilizing JavaScript or jQuery to adjust the cursor pointer value based on user input

Issue: Need help with live updating of input value to range input pointer [Check out my CodePen for reference][1] Adjust upper range input pointer based on lower range input pointer ][2] I am currently working on a range-to-range calculator for a book ...

Struggling with setting up a PHP and Ajax registration and login system

Struggling with my code and in need of assistance. Desperately trying to set up a register form where users can input their username and password to sign up. Planning to utilize ajax, however, the integration seems faulty. For testing purposes, I tried ech ...

Encountering problems during the installation of Ionic - Error code 'EPROTO'

After attempting to install Ionic on my system, I encountered the following error message: npm ERR! code EPROTO npm ERR! errno EPROTO npm ERR! request to https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz failed, reason: write EPROTO 0:er ...

Variations of a particular software package are necessary

My current project requires Expo, React, and React-Native as dependencies. The configuration in the package.jason file looks like this: "main": "node_modules/expo/AppEntry.js", "private": true, "dependencies": { "expo": "^28.0.0", "expo-three": "^ ...

Currently, I am experiencing difficulties with two specific aspects of the website I am working on - the hamburger menu and the slideshow feature

I'm having trouble with the menu on my website. It's not functioning as expected - the dropdown feature isn't working, and two items are not staying in the correct position under the parent ul despite attempts to position them using CSS. Add ...

Is there a method of converting React components into strings for manipulation?

In my React TypeScript project, I am utilizing a crucial library that contains a component which transforms text into SVG. Let's refer to this library component as <LibraryRenderer />. To enhance the functionality, I have enclosed this componen ...

Sending a function along with event and additional arguments to a child component as a prop

I've managed to set up a navigation bar, but now I need to add more complexity to it. Specifically, I have certain links that should only be accessible to users with specific permissions. If a user without the necessary permissions tries to access the ...

How to extract a specific part of a string with regular expressions

I am currently working on a function to search for a specific substring within a given string. // the format is <stringIndex>~<value>|<stringIndex>~<value>|<stringIndex>~<value> var test = "1~abc1|2~def2|1~ghi3|4~jk-l4 ...

Different placeholder text rendered in two text styles

Can an input box placeholder have two different styles? Here's the design I have in mind: https://i.stack.imgur.com/7OH9A.png ...

AngularJS: Pause the data binding functionality temporarily

How can I temporarily deactivate data binding in AngularJS? I am working with a list called items that is being displayed using ng-repeat. I need to perform some operations on this list without immediately updating the page, as this could cause slowdown. ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...