检测png图片透明区域...................................

mingl11 2012-05-06 10:24:14
如何能够检测到png图片的透明区域,我知道Bitmap.GetPixel可以得到图片上的透明度,但我想获得一个图片透明区域开始那个点的坐标,我想使用遍历图片像素可以做到,但这个应该不可行哇~。要是图片比较大岂不相当浪费资源。

请教大神们有什么其他好的方法?
...全文
145 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
nonocast 2012-05-06
  • 打赏
  • 举报
回复
将png decode为32位bitmap然后遍历像素


public Rect GetTransparentBounds(BitmapSource source) {
var width = source.PixelWidth;
var height = source.PixelHeight;
var pixelBytes = new byte[height * width * 4];
source.CopyPixels(pixelBytes, width * 4, 0);

double? ax1 = null, ax2 = null, ay1 = null, ay2 = null;
Rect result = new Rect();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
byte a = pixelBytes[(y * width + x) * 4 + 3];
if (a != 0xff) {
if (ax1.HasValue) {
ax1 = Math.Min(ax1.Value, x);
ax2 = Math.Max(ax2.Value, x);
} else {
ax1 = x;
ax2 = x;
}

if (ay1.HasValue) {
ay1 = Math.Min(ay1.Value, y);
ay2 = Math.Max(ay2.Value, y);
} else {
ay1 = y;
ay2 = y;
}
}
};
}

if(ax1.HasValue && ay1.HasValue){
result.X = ax1.Value;
result.Y = ay1.Value;
result.Width = ax2.Value - ax1.Value;
result.Height = ay2.Value - ay1.Value;
}

return result;
}

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧