以编程方式测量边上的PNG图像填充/清除空间

时间:2013-02-19 14:51:01

标签: c# xamarin.ios png monodevelop padding

是否可以通过编程方式测量C#中PNG两侧(左上角)的填充(空白区域)?我可以以某种方式从一侧开始逐像素地解析图像,检查像素中是否有任何不清晰或空的东西?我如何确定像素是空的而不是颜色?

我的PNG加载到UIImageView上,但我可以处理PNG或UIImage / UIImageView。什么工作。

Here's a PNG

这是PNG

Here's what I want to measure

这是我想要以编程方式衡量的内容。

--------------此处发布的解决方案----------------

    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值。

感谢大家的帮助!

1 个答案:

答案 0 :(得分:1)

您可以通过检查其Alpha值是否等于(或接近)0来检查像素是否为空。不确定您使用的是哪种API,但是您应该能够获得RGBA中像素的颜色。 / p>

在行中扫描应该可以确定边框有多少是“空”。