How can I copy the pixel data from a Bitmap with negative stride?

前端 未结 5 1584
眼角桃花
眼角桃花 2020-12-11 06:45

I was looking for the fastest way to convert a Bitmap to 8bpp. I found 2 ways:

1.

        public static System.Drawing.Image Conver         


        
5条回答
  •  难免孤独
    2020-12-11 06:57

    The problem here is that Scan0 points to the beginning of the first scan line, not the beginning of the first byte of data. In a bottom-up bitmap, the first scan line is Stride bytes from the end of the bitmap data.

    When you call Marshal.Copy to copy the data from Scan0, it tries to copy (Height*Stride) bytes, starting from position ((Height-1)*Stride). Clearly, that's going to run off into the weeds.

    If you just want to copy the bitmap data, you have to calculate the starting address with Scan0 - (Height-1)*Stride. That will start you at the beginning of the bitmap data. You can pass that computed address to Marshal.Copy.

    If you want to copy the scan lines in order (i.e. top, next, next, ... bottom), then you have to copy a line at a time: copy Stride bytes from Scan0, then add Stride (which is negative), copy that line, etc. Rick Brewster had the right answer there: https://stackoverflow.com/a/10360753/56778

提交回复
热议问题