Cut transparent parts image

2019-03-06 05:44发布

问题:

The updated image:

thanks you very much man but i wanted to do somthing little different, to cut each rectangle here as a sperate image.Lets try first to find the blue block Bounds. Sounds hard but its actually simple.

look when i have done so far:

  private unsafe Bitmap CodeImage(Bitmap bmp)
    {

        Bitmap bmpRes = new Bitmap(bmp.Width, bmp.Height);

        BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);


        IntPtr scan0 = bmData.Scan0;


        int stride = bmData.Stride;


        int nWidth = bmp.Width;
        int nHeight = bmp.Height;
        int minX = 10000 ;
        int maxX = -10000;
        int minY = 10000;
        var maxY = -10000;

        bool found = false;
        for (int y = 0; y < nHeight; y++)
        {
            byte* p = (byte*)scan0.ToPointer();
            p += y * stride;


            for (int x = 0; x < nWidth; x++)
            {




                if (p[3]!=0)  //Check if pixel is transpert;
                {


                    found = true;
                  if (x < minX)
                      minX = x;
                  if (y < minY)
                      minY = y;
                   if (x > maxX)
                      maxX = x;
                  if (y > maxY)
                      maxY = y;

                }

                else
                {
                    if (found)
                    {


                        Rectangle temp = new Rectangle(minX, minY, maxX - minX,  maxY-minY);


                        return bmp.Clone(temp, bmp.PixelFormat);
                    }
                }



                p += 4;


            }
        }


        return null;

    }

you actually was write and i should calculate the width like this : int width = maxX - minX; and it actually works.. but the height is 0....

try this out man its outputing almost correct rectangle with these bounds: (200,800,400, and 0 on the height). i just used parts of your code in my algorithm and yea you were right but now there is a little problem with the height i' would very appreciate if you will have a look

回答1:

I'll write this in pseudo-ish-code since you should be able then to apply it to any type of image or language...

var minX = 10000
var maxX = -10000
var minY = 10000
var maxY = -10000

for (var y = 0 to height)
{
    for (var x = 0 to width)
    {
        if (pixel(x,y).Color != transparent)
        {
            if (x < minX) minX = x
            if (y < minY) minY = y
            if (x > maxX) maxX = x
            if (y > maxY) maxY = y
        }
    }
}

var cropRectangle = (minX, minY, maxX, maxY)

You can now use standard functions on the bitmap to get that area, which should be the area bounded by the non-transparent pixels.