javascripttypescriptimage-processingcss-filters

Once I have a base64 url how can I change the filter for brightness and contrast?


If I have an image in base64 ex.

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

What's the fastest way to change a filter (ex. brightness, contrast) programmatically and without creating any img or canvas tag in the view? Then once changed, convert it back to a base64 url?


Solution

  • You can do this by putting the image onto a HTML canvas with filters applied, then turning that canvas back into a base64 URL.

    Since you never add the canvas to the document, it will never be seen.

    This is how you would do it asynchronously:
    This 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"));
        }
    }
    

    You could do it synchronously if you already have the Image instance loaded.

    This is how you will 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");
    }