Skip to content

Instantly share code, notes, and snippets.

@diego-betto
Last active December 13, 2017 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diego-betto/ff031d9a471cc8fed723c9619d7871f2 to your computer and use it in GitHub Desktop.
Save diego-betto/ff031d9a471cc8fed723c9619d7871f2 to your computer and use it in GitHub Desktop.
Detects the beginning and end of an image along its center
function getRealImageYStartEnd($imageId){
var img = document.getElementById($imageId);
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
var context = canvas.getContext('2d');
var middle = Math.floor(img.width/2);
var startImage = 0;
var endImage = img.height;
for (i = 0; i < img.height; i++){
var data = context.getImageData(Math.floor(img.width/2), i, 1, 1).data;
if (data[0] !== 0 && data[1] !== 0 && data[1] !== 0 && data[3] !== 0){
startImage = i;
break;
}
}
for (i = img.height; i >= 0; i--){
var data = context.getImageData(Math.floor(img.width/2), i, 1, 1).data;
if (data[0] !== 0 && data[1] !== 0 && data[1] !== 0 && data[3] !== 0){
endImage = i;
break;
}
}
return {start: startImage, end: endImage, width: img.width, height: img.height};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment