Creating a blurred image in javascrpt

Viewed 59

I want to generate a blurred image from a normal image. I've searched on the internet and found out that people have done it by putting CSS filter property through javascript on Image to make it blur. But it can be removed by inspecting the page and I don't want that.

I want to generate a blurred version of image through javascript. I think I can do it with canvas but I never worked with canvas and any help will be highly appreciated (:

2 Answers

So, it depends. If you're worried about them removing it with developer tools, then the answer is probably "you can't".

The reason for this, is if you want to blur it with JavaScript, you need to send the unblurred image. And, if you send the unblurred image, they can easily scoop it out of the network tab, even if you never add it directly to the DOM. Anything you use as an input for JavaScript can be obtained by a clever enough user.

If you want the user to never be able to see the original, only the blurred, you'll have to blur it server-side.

If, for some weird reason, you're okay with that and still want to blur it in canvas, you'll need to pick and implement a blur algorithm for canvas. There are lots of different blur algorithms to choose from. Probably the most common one would be a Gaussian blur.

The algorithm isn't super insane, but it also isn't exactly super straightforward either, and I'd recommend using a library instead, such as this one: glur. I've not directly used that one, so can't vouch for it, but it has half a million downloads a week on NPM, so probably pretty solid.

Simple filters

You can apply a blur via the canvas using ctx.filter. CanvasRenderingContext2D.filter will accept a (limited set of) filters defined as strings. Eg ctx.filter = "blur(10px)";

See ctx.filter for set of filters you can use directly.

Example

Example uses CanvasRenderingContext2D.filter to blur image over time.

const img = new Image;
img.src = "https://i.stack.imgur.com/C7qq2.png?s=256&g=1";
img.addEventListener("load", () => requestAnimationFrame(uodate));
function drawImageBlur(img, blurAmount) {
   const ctx = can.getContext("2d");
   ctx.clearRect(0,0,128,128);
   ctx.filter = "blur(" + blurAmount+ "px)";
   ctx.drawImage(img, 128 - img.naturalWidth * 0.5, 128 - img.naturalHeight * 0.5);
}
var frameCount = 0;
function uodate(time) {
  if (frameCount++ % 10 === 0) {  // no point burning CPU cycles so only once every 10 frames
      drawImageBlur(img, Math.sin(time / 1000) * 5 + 6);
  }
  requestAnimationFrame(uodate);
}
canvas {border: 1px solid black;}
<canvas id="can" width="256"  height="256"></canvas>

There is no way to protect the image from inspection if you apply the image blur on the client (no matter what method you use). If you want to obfuscate (blur) the image it must be done on the server.

Related