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:

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>

Kontakt

Udo Schmal
Udo Schmal

Udo Schmal
Softwareentwickler
Ellerndiek 26
24837 Schleswig
Schleswig-Holstein
Germany




+49 4621 9785538
+49 1575 0663676
+49 4621 9785539
SMS
WhatsApp

Google Maps Profile
Instagram Profile
vCard 2.1, vCard 3.0, vCard 4.0

Service Infos

CMS Info

Product Name:
UDOs Webserver
Version:
0.5.1.214
Description:
All in one Webserver
Copyright:
Udo Schmal
Compilation:
Sat, 26. Oct 2024 05:52:49

Development Info

Compiler:
Free Pascal FPC 3.3.1
compiled for:
OS:Linux, CPU:x86_64

System Info

OS:
Ubuntu 22.04.5 LTS (Jammy Jellyfish)

Hardware Info

Model:
Hewlett-Packard HP Pavilion dm4 Notebook PC
CPU Name:
Intel(R) Core(TM) i5-2430M CPU @ 2.40GHz
CPU Type:
x86_64, 1 physical CPU(s), 2 Core(s), 4 logical CPU(s),  MHz