0

I've found several bookmarklets that invert all the colors on a page or just the text but not one that inverts just the images. How might I go about doing this? Javascript is not my expertise.

Community
  • 1
  • 1
Steve Moser
  • 7,647
  • 5
  • 55
  • 94

1 Answers1

1

You must get the images in a array, and replace theses images by a canvas.

Code untested (nb: the image source must be on the same domain due to security restrictions):

function replaceImageByCanvas(image) {
    var canvas = document.createElement('canvas');
    image.after(canvas);
    var context = canvas.getContext('2d');
    canvas.width = image.width();
    canvas.height = image.height();

    var image_obj = new Image(); 
        var newImage = context.createImageData(canvas.width, canvas.height);
        var arr = context.getImageData(0, 0, canvas.width, canvas.height);
        var pixels = arr.data;

        for(var i = 0; i < pixels.length; i+=4){
            var r = 255 - pixels[i];
            var g = 255 - pixels[i + 1];
            var b = 255 - pixels[i + 2];
            var a = pixels[i + 3];
            newImage.data[i] = r;
            newImage.data[i + 1] = g;
            newImage.data[i + 2] = b;
            newImage.data[i + 3] = a;
        }

        context.clearRect(0, 0, canvas.width, canvas.height);
        context.putImageData(newImage, 0, 0);
    image_obj.src = image.attr('src');
    image.remove();
};

$('img').each(function(index, element) {
  $(this).one('load', function() {
    replaceImageByCanvas($(element));|
  });
});
Paul Rad
  • 4,820
  • 1
  • 22
  • 23