JavaScript Canvas - Image Processing
Written by Ian Elliot   
Monday, 07 October 2019
Article Index
JavaScript Canvas - Image Processing
Augment ImageData
The Complete Program

The complete program is:

<!DOCTYPE html>
<html>
  <head>
   <title>TODO supply a title</title>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width,
                                   initial-scale=1.0">
  </head>
  <body>
   <script>
     function createCanvas(h, w) {
       var c = document.createElement("canvas");
       c.width = w;
       c.height = h;
       return c;
     }
     function imgLoaded(img) {
       return new Promise(
        function (resolve, reject) {
          img.addEventListener("load", function () {
                                    resolve(img);
                              });
          });
      }
            
     function augmentImageData(o) {
       o.getPixel = function (x, y) {
         var i = (x + y * this.width) * 4;
         return {R: this.data[i],
                 G: this.data[i + 1],
                 B: this.data[i + 2],
                 A: this.data[i + 3]
                }
        }
       o.setPixel = function (x, y, c) {
         var i = (x + y * this.width) * 4;
         this.data[i] = c.R;
         this.data[i + 1] = c.G;
         this.data[i + 2] = c.B;
         this.data[i + 3] = c.A;
        }
  }
 
  async function draw() {
   var ctx = document.body.appendChild(
createCanvas(400, 400)).getContext("2d"); var img = new Image(); var url = new URL("jeep.jpg",
"http://server/Filter/"); img.src = url; await imgLoaded(img); ctx.drawImage(img, 0, 0, 400, 300); var ImDat = ctx.getImageData(0, 0, 400, 300); augmentImageData(ImDat); for (var x = 0; x < 400; x++) { for (var y = 0; y < 300; y++) { var c1 = ImDat.getPixel(x, y); var c2 = ImDat.getPixel(x, y + 3); var r = Math.abs(c1.R - c2.R) + 128; var g = Math.abs(c1.G - c2.G) + 128; var b = Math.abs(c1.B - c2.B) + 128; var gray = (r + g + b) / 3; ImDat.setPixel(x, y,{R: gray, G: gray,
B: gray, A: c1.A}); } } ctx.putImageData(ImDat,0,0); } draw(); </script> </body> </html>

emboss



You can try the program out here.

A Security Problem

You can try loading images for this filter from the local file system, but if you do you will discover that it doesn't work. You cannot access the pixels of an image that has been loaded from a different URL and accessing pixels of a local file is strictly forbidden. If you download the file from a server with the same URL as the script then there's no problem.

To allow for testing, Chrome has a command line switch that turns off the security check - no doubt other browsers have similar features. All you have to do is locate the shortcut that you use to launch Chrome and change the target to read:

"C:\Program Files\Google\Chrome\Application\chrome.exe" 
--allow-file-access-from-files

Alternatively simply use the command from the command prompt or add:

--allow-file-access-from-files 

to whatever command initiates Chrome. With this command line switch it all works and you can see the result of the effect.

Sections in book but not in this extract:

  • The Filter API

  • Convolution Filter

  • Custom Convolution

  • Reading a PCX File

  • Processing the PCX File

  • Listing - Read a PCX File

Summary

  • The ImageData object allows direct access to the pixel data within a bitmap.

  • The pixel data is stored in the data array property which is a Uint8ClampedArray in RGBA order.

  • With direct access to the pixel data you can write filters which change the bitmap in controlled ways using functions formed from the surrounding pixels.

  • The new Filter API provides a range of predefined filters that you can use.

  • You can also use any of the SVG filters via the url filter.

  • The SVG filters include a general convolution filter which can be used to implement many standard and custom linear filters.

  • A convolution filter replaces the current pixel value with a weighted average of it and the pixels that surround it. The weighted average is specified as a convolution matrix or mask.

  • It is also fairly easy to implement a convolution filter directly using ImageData and direct pixel manipulation.

  • You can also arrange to read and process any graphics file format that you have the specification for using the standard techniques of reading files, bit manipulation and ImageData.

Now available as a paperback or ebook from Amazon.

JavaScript Bitmap Graphics
With Canvas

largecover360

 

Contents

  1. JavaScript Graphics
  2. Getting Started With Canvas
  3. Drawing Paths
      Extract: Basic Paths
      Extract: SVG Paths
      Extract: Bezier Curves
  4. Stroke and Fill
      Extract: Stroke Properties 
      Extract: Fill and Holes
      Extract: Gradient & Pattern Fills
  5. Transformations
      Extract: Transformations
      Extract: Custom Coordinates 
      Extract  Graphics State
  6. Text
      Extract: Text, Typography & SVG 
      Extract: Unicode
  7. Clipping, Compositing and Effects
      Extract: Clipping & Basic Compositing
  8. Generating Bitmaps
      Extract:  Introduction To Bitmaps
      Extract :  Animation 
  9. WebWorkers & OffscreenCanvas
      Extract: Web Workers
      Extract: OffscreenCanvas
  10. Bit Manipulation In JavaScript
      Extract: Bit Manipulation
  11. Typed Arrays
      Extract: Typed Arrays 
  12. Files, blobs, URLs & Fetch
      Extract: Blobs & Files
      Extract: Read/Writing Local Files
      Extract: Fetch API **NEW!
  13. Image Processing
      Extract: ImageData
      Extract:The Filter API
  14. 3D WebGL
      Extract: WebGL 3D
  15. 2D WebGL
    Extract: WebGL Convolutions

<ASIN:B07XJQDS4Z>

<ASIN:1871962579>

<ASIN:1871962560>

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

espbook

 

Comments




or email your comment to: comments@i-programmer.info

 



Last Updated ( Sunday, 04 June 2023 )