Tag Archives: jpg

Using Canvas to give transparencies to Jpeg images


Logos often need to be placed on web pages and often they don’t have a PNG logo with a transparency; Or a jpg image is available but jpg lacks transparencies … Sixrevisions explains this limitation in: JPEG 101: A Crash Course Guide on JPEG … One solution is to copy the web background into an image place it as a background layer in a graphics program and use the darken filter for that layer to allow the background to come through;

Web Developer to designer: Houston we may have a problem! unless the background is an image, It can not be gauranteed that the browser will render the background of the logo image the same as the background on the webpage! … it almost certainly will not across all systems. … this is because of blah, blah, blah.

Canvas to the rescue! I can do the image processing on the browser and everything is pixel perfect! Or even 1/2 pixel perfect!

Anti-aliasing makes a pixel that is 1/2 black and 1/2 white gray. By doing this there is no stair stepping on a pixel level in the image.

Here is an example and the source code:

<!doctype html>

<div style=”background:#eee; width:160px;padding:15px”>

<canvas width=”158″ height=”97″ id=”logo1″>Alternative Logo</canvas>
<canvas width=”158″ height=”97″ id=”logo2″>Alternative Logo</canvas>

</div>

<script>

// setup our canvases

var canvas = document.getElementById(“logo1”);
var context = canvas.getContext(“2d”);

var canvasnew = document.getElementById(“logo2”);
var contextnew = canvasnew.getContext(“2d”);

// get image
var img = new Image();
img.onload = function(){

context.drawImage(img, 0, 0);
contextnew.drawImage(img, 0, 0);

// create the transparency for the jpg by making white transparent

var TheImage = contextnew.getImageData(0, 0, 158, 96);
var jpgdata = TheImage.data;
for (var i = 0, n = jpgdata.length; i < n; i += 4) {
jpgdata[i+3] = 255-jpgdata[i]; // red channel used to set transparency.
}

contextnew.putImageData(TheImage, 0, 0);

}
img.src = ‘logo.jpg’; // Set source path

</script>

Note: contextnew.getImageData triggers a security error if it is used on image data that is from a file on the hard disk … the image must come from a web server and  the same server as the html / script are on.

Advertisements