JavaScript use canvas for grayscale

Mit JavaScript farbige Bilder in Graustufen umwandeln, durch setzen von class="grayscale" im img-Tag.

On using this JavaScripts all images with class "grayscale" get converted to grayscaled images.

Example:

DSC02303~300x225DSC02833~300x225

JavaScript:

grayscale.js JavaScript (1,26 kByte) 09.01.2022 00:02
// coding: utf-8
/** Created by: Udo Schmal | https://www.gocher.me/ */
(function () {
  'use strict';

  function grayscaleImage (img) {
    var canvas = document.createElement("canvas");
    var canvascontext = canvas.getContext("2d");
    var imgw = img.naturalWidth;
    var imgh = img.naturalHeight;
    canvas.width = imgw;
    canvas.height = imgh;
    canvascontext.drawImage(img, 0, 0);
    var imgpixels = canvascontext.getImageData(0, 0, imgw, imgh);
    for (var y = 0; y < imgpixels.height; y++) {
      for (var x = 0; x < imgpixels.width; x++) {
        var i = (y * 4) * imgpixels.width + x * 4;
        var 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;
      }
    }
    canvascontext.putImageData(imgpixels, 0, 0, 0, 0, imgpixels.width, imgpixels.height);
    img.src = canvas.toDataURL();
  }

  var els = document.querySelectorAll('img.grayscale');
  for (var i=0; i<els.length; i++) {
    if (!els[i].complete || (els[i].naturalWidth === 0)) {
      els[i].addEventListener("load", function (e) { grayscaleImage(this); }, false);
    } else {
      grayscaleImage(els[i]);
    }
  }
})();

HTML:

grayscale.htm HTML (369 bytes) 09.01.2022 00:02
<!DOCTYPE html >
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Convert Image to Grayscale</title>
  </head>
  <body><img class="grayscale" src="/media/2007/Sammy/DSC02303~300x225.JPG" width="300" height="225" /><img class="grayscale" src="/media/2007/Sammy/DSC02833~300x225.JPG" width="300" height="225" />
    <script src="grayscale.js"></script>
  </body>
</html>

Author: , published: , last modified:

Kontakt

Udo Schmal

Udo Schmal
Softwareentwickler
Olvengraben 41
47608 Geldern
Nordrhein-Westfalen
Germany





+49 2831 9776557
+49 1575 0663676
+49 2831 1328709
SMS
WhatsApp

Google Maps Profile
Instagram Profile
vCard 3.0

Service Infos

CMS Info Product Name:
UDOs Webserver
Version:
0.5.0.122
Description:
All in one Webserver
Copyright:
Udo Schmal
Compilation:
Fri, 14. Jan 2022 21:55:59
Development Info Compiler:
Free Pascal FPC 3.3.1
compiled for:
OS:Linux, CPU:x86_64
System Info OS:
Ubuntu 20.04.3 LTS (Focal Fossa)
Hardware Info Model:
Hewlett-Packard HP Pavilion dv7 Notebook PC
CPU Name:
Intel(R) Core(TM) i5-2450M CPU @ 2.50GHz
CPU Type:
x86_64, 1 physical CPU(s), 2 Core(s), 4 logical CPU(s), 1232.209 MHz