就像这张照片一样,红色边框表示图像的大小,绿色边框表示图像的可见大小,绿色边框外面是alpha像素。如何计算可见帧?
两种计算机语言都可以。
最佳答案
// This function will return object with properties like left, top position and width & height of green box.
//@imgObj : Image Object of target image (.png)
function getImageDetails(imgObj)
{
var cns = document.createElement("canvas");
cns.width = imgObj.width;
cns.height = imgObj.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgObj,0,0,cns.width,cns.height);
var imgData = ctx.getImageData(0, 0, cns.width, cns.height).data;
var minCol,maxCol,curCol,
minRow,maxRow,curRow;
for (var i = 0; i < imgData.length; i += 4) {
var index = Math.floor(i/4);
curCol = index%cns.width;
curRow = Math.floor(index/cns.width);
if( imgData[i] != 0 ||
imgData[i + 1] != 0 ||
imgData[i + 2] != 0 ||
imgData[i + 3] != 0)
{
minCol = minCol == undefined || minCol > curCol ? curCol : minCol;
maxCol = maxCol == undefined || maxCol < curCol ? curCol : maxCol;
minRow = minRow == undefined || minRow > curRow ? curRow : minRow;
maxRow = maxRow == undefined || maxRow < curRow ? curRow : maxRow;
}
}
var details = new Object();
details.x = minCol;
details.y = minRow;
details.width = maxCol-minCol+1;
details.height = maxRow-minRow+1;
return details
}