javascript: the beginning and end of an image along its center

Javascript snippet that detects the beginning and end of an image along its center, alpha supported.

Parameters: image id (without ‘#’)

Returns an object with:
– start (first non trasparent/not white pixel from center top)
– end (first not trasparent/not white pixel from center bottom)
– image width
– image height

 

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};
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: