Skip to content

Instantly share code, notes, and snippets.

@Ni55aN
Created October 8, 2016 17:43
Show Gist options
  • Save Ni55aN/ce73b2912c3dbcb1420ee612cc6f33df to your computer and use it in GitHub Desktop.
Save Ni55aN/ce73b2912c3dbcb1420ee612cc6f33df to your computer and use it in GitHub Desktop.
Class for faster pixels processing
class FastImage
{
Bitmap bm;
BitmapData bmpData;
public byte[] bytes;
public int Width, Height;
public FastImage(Bitmap bm)
{
this.bm = bm;
Width = bm.Width;
Height = bm.Height;
int len = Width * Height * 4;
bytes = new byte[len];
}
public FastImage(Image img) : this(new Bitmap(img)) { }
public FastImage(int w, int h) : this(new Bitmap(w, h)) { }
public Bitmap getBitmap()
{
return bm;
}
public Color GetPixel(int x,int y)
{
int i = 4 * (y * Width + x);
return Color.FromArgb(bytes[i+3], bytes[i+2], bytes[i+1], bytes[i+0]);
}
public FastImage Clone()
{
FastImage img = new FastImage(bm);
img.bytes = (byte[])bytes.Clone();
return img;
}
public void fromBytes(byte[] b)
{
bytes = b;
writeBytes();
}
public void SetPixel(int x,int y, Color c)
{
int i = 4 * (y * Width + x);
bytes[i + 3] = c.A;
bytes[i + 2] = c.R;
bytes[i + 1] = c.G;
bytes[i + 0] = c.B;
}
void Lock(){
Rectangle rect = new Rectangle(0, 0, Width, Height);
bmpData = bm.LockBits(rect, ImageLockMode.ReadWrite, bm.PixelFormat);
}
public byte[] readBytes()
{
Lock();
System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, bytes, 0, bytes.Length);
Unlock();
return bytes;
}
public void writeBytes()
{
Lock();
System.Runtime.InteropServices.Marshal.Copy(bytes, 0, bmpData.Scan0, bytes.Length);
Unlock();
}
void Unlock()
{
bm.UnlockBits(bmpData);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment