是否可以在 C# 中以编程方式测量 PNG 侧面(左上右下)的填充(空白)?我能否以某种方式从侧面开始逐个像素地解析图像,以查看像素中是否有任何不清晰或空的东西?我如何确定像素是空的而不是颜色?
我的 PNG 被加载到 UIImageView 上,但我可以处理 PNG 或 UIImage/UIImageView。什么都有效。
这是一个PNG
这是我想以编程方式测量的内容。
-------------- 解决方案贴在这里 ----------------
UIImage Image = UIImage.FromFile("image.png");
IntPtr bitmapData = RequestImagePixelData(Image);
PointF point = new PointF(100,100);
//Check for out of bounds
if(point.Y < 0 || point.X < 0 || point.Y > Image.Size.Height || point.X > Image.Size.Width)
{
Console.WriteLine("out of bounds!");
}
else
{
Console.WriteLine("in bounds!");
var startByte = (int) ((point.Y * Image.Size.Width + point.X) * 4);
byte alpha = GetByte(startByte, bitmapData);
Console.WriteLine("Alpha value of an image of size {0} at point {1}, {2} is {3}", Image.Size, point.X, point.Y, alpha);
}
protected IntPtr RequestImagePixelData(UIImage InImage)
{
CGImage image = InImage.CGImage;
int width = image.Width;
int height = image.Height;
CGColorSpace colorSpace = image.ColorSpace;
int bytesPerRow = image.BytesPerRow;
int bitsPerComponent = image.BitsPerComponent;
CGImageAlphaInfo alphaInfo = image.AlphaInfo;
IntPtr rawData;
CGBitmapContext context = new CGBitmapContext(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, alphaInfo);
context.SetBlendMode(CGBlendMode.Copy);
context.DrawImage(new RectangleF(0, 0, width, height), image);
return context.Data;
}
//Note: Unsafe code. Make sure to allow unsafe code in your
unsafe byte GetByte(int offset, IntPtr buffer)
{
byte* bufferAsBytes = (byte*) buffer;
return bufferAsBytes[offset];
}
显然,现在我需要创建解析每个像素并确定清晰像素停止位置的逻辑。这个逻辑很简单,所以我不会费心发布它。只需从侧面开始,一直往前走,直到找到一个不为零的 alpha 值。
感谢大家的帮助!