Created
November 20, 2014 02:13
-
-
Save GMMan/163823f663f99f21fd96 to your computer and use it in GitHub Desktop.
Get consecutive scanlines in a Bitmap using foreach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Drawing; | |
using System.Drawing.Imaging; | |
class BitmapScanlineEnumerable : IEnumerable<IntPtr> | |
{ | |
BitmapData bmd; | |
public bool VerticalFlip { get; set; } | |
public BitmapScanlineEnumerable(BitmapData bmd, bool verticalFlip) | |
{ | |
this.bmd = bmd; | |
VerticalFlip = verticalFlip; | |
} | |
public IEnumerator<IntPtr> GetEnumerator() | |
{ | |
IntPtr scan = bmd.Scan0; | |
if (VerticalFlip) scan += (bmd.Height - 1) * bmd.Stride; | |
for (int i = 0; i < bmd.Height; ++i) | |
{ | |
yield return scan; | |
if (!VerticalFlip) scan += bmd.Stride; | |
else scan -= bmd.Stride; | |
} | |
} | |
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why? Because trying to calculate scanline addresses inside of loops is annoying, plus what if your source image has scanlines that run from top to bottom instead of bottom to top? Using this code, just focus on getting each row of pixels copied.
Sample usage: