Sunday, September 28, 2014

Rotate base64 image using javascript and canvas

1. Create a canvas object in javascript

    var canvas  = document.createElement("canvas");

2. By default the height and width of the canvas will be 150px so we need to make canvas size exactly equivalent to the our source image. By creating the image object we can get the actual source image size. 
  
   var img = new Image();
   img.src = << Your base 64 string of source image >> 
  
3. Adjust the canvas size. 

 canvas.width  = img.width;
 canvas.height = img.height;

4.  Set the canvas context, and transform and rotate the canvas image, 

var context = canvas.getContext("2d");
context.translate(img.width, img.height);
context.rotate(180 * Math.PI / 180);

5.  Draw the rotated image in to canvas 

context.drawImage(img, 0, 0);

6. Get the new image base64 url 

var rotatedImageSrc =  canvas.toDataURL();

function rotateBase64Image(base64ImageSrc) { var canvas = document.createElement("canvas"); var img = new Image(); img.src = base64ImageSrc; canvas.width = img.width; canvas.height = img.height; var context = canvas.getContext("2d"); context.translate(image.width, image.height); context.rotate(180 * Math.PI / 180); context.drawImage(image, 0, 0); return canvas.toDataURL(); }