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