Convert color image to black and white in Base64 format ( typescript )

Viewed 495

I'm trying to turn a color image into black and white. I googled and came up with some code in JavaScript and converted it to TypeScript. But the code does not return all the photos and part of the photo becomes black and white.

For example, I receive the following input and output:

InPut

OutPut

My code is like this:

GrayScale() {
    const www = this;
    const myimage = new Image();
    myimage.src = this.croppedImage.src;
    myimage.onload = function () {
        const cnv = document.createElement('canvas');
        const cnx = cnv.getContext('2d');
        cnx.drawImage(myimage, 0, 0);
        const width = myimage.width;
        const height = myimage.height;
        const imgPixels = cnx.getImageData(0, 0, width, height);

        for (let y = 0; y < height; y++) {
            for (let x = 0; x < width; x++) {
                const i = (y * 4) * width + x * 4;
                const avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg;
                imgPixels.data[i + 1] = avg;
                imgPixels.data[i + 2] = avg;
            }
        }

        cnx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
        www.croppedImage.src = cnx.canvas.toDataURL();
    };
}

Does anyone know what the reason is ? Thank you for your help

1 Answers

After creating canvas you need to set its width and height. Otherwise it gets some default size not equal to image size, and resulting image is cropped. I.e.:

cnv.width = myimage.width;
cnv.height = myimage.height;
Related