Put a transparent color in an image file using JavaScript. Gray scale. Base64 extension

Hello friends,

using this JavaScript code we can put a transparent color in an image file:
https://jsfiddle.net/hppgLkfg/1/

We are going to adapt it to App Inventor.


Choose a color using the Sliders: 255,255,255 or 0,0,0 and press the Buttons below.
p169Y_javascript_transparente.aia (150.9 KB)

This takes an QR image file from the assets, through the com.KIO4_Base64.aix extension, it converts the image to a Base64 string, pass it to the JavaScript code, it must also pass the color code, in this case white (255#255#255) or black (0#0#0).

The code, using the preserveColor function, makes the color transparent and returns the image as a Base64 string.

The string is received by the Base64 extension which converts it back into an image file: qr_transparent.png

The example is done on an Android 9, if you use an Android 10+, you will have to change the directory.

<!DOCTYPE HTML><html><head>
<!-- Code from https://jsfiddle.net/hppgLkfg/1/ -->
<!-- Modified by Juan A. Villalpando - http://kio4.com/appinventor/169Y_javascript_transparente.htm -->
</head>

<body>
<img src= "" id="code">
<script type="text/javascript">
     data = window.AppInventor.getWebViewString().split("#");  // ENTRADA APP INVENTOR. 

      base64 = data[0];
	  red = data[1];
      green = data[2];
	  blue = data[3];

document.getElementById('code').setAttribute('src', base64);

var el = document.getElementById('code');

var canvas = document.createElement('canvas');
canvas.setAttribute('width', 250);
canvas.setAttribute('height', 250);
var context = canvas.getContext("2d");
context.drawImage(el, 0, 0, canvas.width, canvas.height);

var imageData = context.getImageData(0, 0, canvas.width, canvas.height);

var preserveColor = function(imageData, color) {
	var data = imageData.data;
	for (var i = 0; i < data.length; i += 4) {
    var preserve = data[i] === color.r
      && data[i + 1] === color.g
      && data[i + 2] === color.b
      && data[i + 3] === color.a;
      
    data[i + 3] = preserve ? data[i + 3] : 0;
  }
  return imageData;
};

var newData = preserveColor(imageData, {r: parseInt(red), g: parseInt(green), b: parseInt(blue), a: 255});
context.putImageData(newData, 0, 0);

document.body.appendChild(canvas);

  result = canvas.toDataURL().replace('data:image/png;base64,','');
  window.AppInventor.setWebViewString("" +  result); // SALIDA APP INVENTOR
</script>
</body>
</html>

Here in Spanish:
http://kio4.com/appinventor/169Y_javascript_transparente.htm

3 Likes

funky, I like it :slight_smile:

2.- Converts a color image file to grayscale. Resize image.

p169Y_javascript_gris.aia (135.7 KB)

Adaptation of:
https://www.quora.com/Whats-the-most-common-way-to-edit-images-with-JavaScript

gris.html

<!DOCTYPE HTML><html><head>
<!-- Code from https://www.quora.com/Whats-the-most-common-way-to-edit-images-with-JavaScript -->
<!-- Modified by Juan A. Villalpando - http://kio4.com/appinventor/169Y_javascript_transparente.htm -->
</head>

<body>
<img src= "" id="code">
<script type="text/javascript">
     data = window.AppInventor.getWebViewString().split("#");  // ENTRADA APP INVENTOR. 

      base64 = data[0];
	  WIDTH = data[1];
      HEIGHT = data[2];
  
document.getElementById('code').setAttribute('src', base64);

var inputImage = document.getElementById('code');

var canvas = document.createElement('canvas');
canvas.setAttribute('width', parseInt(WIDTH));
canvas.setAttribute('height', parseInt(HEIGHT));
var context = canvas.getContext("2d");
context.drawImage(inputImage, 0, 0, canvas.width, canvas.height);

surface = context.getImageData(0, 0, canvas.width, canvas.height); 


///////// START CODE FOR GRAY SCALE //////////
//Once you have the ImageData object you can to all your editing 
for (let y = 0; y != surface.height; y++) { 
  for (let x = 0; x != surface.width; x++) { 
    //Remember this formula! 
    //i = (y * width + x) * depth 
    let i = (y * surface.width + x) * 4; 
    //compute the average of RGB components 
    let intensity = ( 
      surface.data[i + 0] + 
      surface.data[i + 1] + 
      surface.data[i + 2] 
    ) / 3; 
    //set the RGB components to the average. Each component 
    //has the same value so it is a shade of gray 
    surface.data[i + 0] = intensity; 
    surface.data[i + 1] = intensity; 
    surface.data[i + 2] = intensity; 
  } 
} 
///////// END CODE FOR GRAY SCALE //////////

/**
/////////// START CODE FOR INVERT COLOR ////////// 
for (var i = 0; i < surface.data.length; i += 4) {
     surface.data[i]     = 255 - surface.data[i];     // red
     surface.data[i + 1] = 255 - surface.data[i + 1]; // green
     surface.data[i + 2] = 255 - surface.data[i + 2]; // blue
    }
///////// END CODE FOR INVERT COLOR ///////////
 */
 
//Now you can put it back onto the canvas 
context.putImageData(surface, 0, 0); 
//From the canvas you can create a data URL 
//let url = canvas.toDataURL(); 

  result = canvas.toDataURL().replace('data:image/png;base64,','');
  window.AppInventor.setWebViewString("" +  result); // SALIDA APP INVENTOR
</script>
</body>
</html>

2.- Invert color.

  • Disable START CODE FOR GREY SCALE and enable START CODE FOR INVERT COLOR

/////////// START CODE FOR INVERT COLOR //////////
for (var i = 0; i < surface.data.length; i += 4) {
surface.data[i] = 255 - surface.data[i]; // red
surface.data[i + 1] = 255 - surface.data[i + 1]; // green
surface.data[i + 2] = 255 - surface.data[i + 2]; // blue
}
///////// END CODE FOR INVERT COLOR ///////////

2 Likes

3.- Change the tone of a color in the whole image.

p169Y_javascript_colores.aia (136.2 KB)

<!DOCTYPE HTML><html><head>
<!--  Juan A. Villalpando - http://kio4.com/appinventor/169Y_javascript_transparente.htm -->
</head>

<body>
<img src= "" id="code">
<script type="text/javascript">
     datos = window.AppInventor.getWebViewString().split("#");  // ENTRADA APP INVENTOR. 

      base64 = datos[0];
	  RED = datos[1];
      GREEN = datos[2];
	  BLUE = datos[3];
	  color = datos[4];
  
document.getElementById('code').setAttribute('src', base64);

var inputImage = document.getElementById('code');

var canvas = document.createElement('canvas');
canvas.setAttribute('width', parseInt(200));
canvas.setAttribute('height', parseInt(250));
var context = canvas.getContext("2d");
context.drawImage(inputImage, 0, 0, canvas.width, canvas.height);

surface = context.getImageData(0, 0, canvas.width, canvas.height); 

/////////// START CODE FOR COLOR ////////// 
if (color == 'r'){
for (var i = 0; i < surface.data.length; i += 4) {
      surface.data[i]     = parseInt(RED);     // red
    }
 }	
 if (color == 'g'){
for (var i = 0; i < surface.data.length; i += 4) {
     surface.data[i + 1] = parseInt(GREEN); // green
}
 }
 if (color == 'b'){
for (var i = 0; i < surface.data.length; i += 4) {
     surface.data[i + 2] = parseInt(BLUE); // blue
}
 }
///////// END CODE FOR COLOR ///////////


//Now you can put it back onto the canvas 
context.putImageData(surface, 0, 0); 
//From the canvas you can create a data URL 
//let url = canvas.toDataURL(); 

  result = canvas.toDataURL().replace('data:image/png;base64,','');
  window.AppInventor.setWebViewString("" +  result); // SALIDA APP INVENTOR
</script>
</body>
</html>
3 Likes

4.- Pixelate an image.

p169Y_javascript_pixelado.aia (135.1 KB)

Adaptation:

pixelado.html

<!DOCTYPE HTML><html><head>
<!--  https://stackoverflow.com/questions/40833640/pixelate-image-in-node-js -->
<!--  Juan A. Villalpando - http://kio4.com/appinventor/169Y_javascript_transparente.htm -->
</head>

<body>
<img src= "" id="code">
<script type="text/javascript">
     datos = window.AppInventor.getWebViewString().split("#");  // ENTRADA APP INVENTOR. 

      base64 = datos[0];
	  pixelation = parseInt(datos[1]);
  
document.getElementById('code').setAttribute('src', base64);

var inputImage = document.getElementById('code');

var canvas = document.createElement('canvas');
canvas.setAttribute('width', parseInt(200));
canvas.setAttribute('height', parseInt(250));
var context = canvas.getContext("2d");
context.drawImage(inputImage, 0, 0, canvas.width, canvas.height);

surface = context.getImageData(0, 0, canvas.width, canvas.height); 

sourceWidth = canvas.width;
sourceHeight = canvas.height;

var data = surface.data;

for(var y = 0; y < sourceHeight; y += pixelation) {
    for(var x = 0; x < sourceWidth; x += pixelation) {
        var red = data[((sourceWidth * y) + x) * 4];
        var green = data[((sourceWidth * y) + x) * 4 + 1];
        var blue = data[((sourceWidth * y) + x) * 4 + 2];

        for(var n = 0; n < pixelation; n++) {
            for(var m = 0; m < pixelation; m++) {
                if(x + m < sourceWidth) {
                    data[((sourceWidth * (y + n)) + (x + m)) * 4] = red;
                    data[((sourceWidth * (y + n)) + (x + m)) * 4 + 1] = green;
                    data[((sourceWidth * (y + n)) + (x + m)) * 4 + 2] = blue;
                }
            }
        }

    }
}

context.putImageData(surface, 0, 0); 
 
  result = canvas.toDataURL().replace('data:image/png;base64,','');
  window.AppInventor.setWebViewString("" +  result); // SALIDA APP INVENTOR
</script>
</body>
</html>
1 Like