Im looking for a javascript method of detecting an image within a transparent PNG. For example, i will create a PNG with a transparent canvas of 940x680, then place an full opacity object somewhere within that canvas.
I want to be able to detect the size (h/w), and top + left location of that object that is not transparent within the canvas
Here is an example of the original image
Here is an example of what i would like to achieve. (Bounding box overlay, with top + left margin data)
Ive found a resource that does some transparency detection, but im not sure how i scale something like this to what im looking for.
var imgData,
width = 200,
height = 200;
$('#mask').bind('mousemove', function(ev){
if(!imgData){ initCanvas(); }
var imgPos = $(this).offset(),
mousePos = {x : ev.pageX - imgPos.left, y : ev.pageY - imgPos.top},
pixelPos = 4*(mousePos.x + height*mousePos.y),
alpha = imgData.data[pixelPos+3];
$('#opacity').text('Opacity = ' + ((100*alpha/255) << 0) + '%');
});
function initCanvas(){
var canvas = $('<canvas width="'+width+'" height="'+height+'" />')[0],
ctx = canvas.getContext('2d');
ctx.drawImage($('#mask')[0], 0, 0);
imgData = ctx.getImageData(0, 0, width, height);
}
What you need to do:
These scans can be combined but for simplicity I'll show each step separately.
Online demo of this can be found here.
Result:
When image is loaded draw it in (if the image is small then the rest of this example would be waste as you would know the coordinates when drawing it - assuming here the image you draw is large with a small image inside it)
(note: this is a non-optimized version for the sake of simplicity)
Then scan each edge. For left edge you scan from 0 to width for each line (non optimized):
For the right edge you just reverse x iterator:
And the same is for top and bottom edges just that the iterators are reversed:
The resulting region is then:
There are various optimizations you could implement but they depend entirely on the scenario such as if you know approximate placement then you don't have to iterate all lines/columns.
You could do a brute force guess of he placement by skipping x number of pixels and when you found a non-transparent pixel you could make a max search area based on that and so forth, but that is out of scope here.
Hope this helps!