ConverttoBitonal method in imaging

public Bitmap ConvertToBitonal(Bitmap original)Bitmap source = null;// If original bitmap is not already in 32 BPP, ARGB format, then convert
{
source =
source.SetResolution(original.HorizontalResolution, original.VerticalResolution);

{
g.DrawImageUnscaled(original, 0, 0);
}
}
if (original.PixelFormat != PixelFormat.Format32bppArgb)new Bitmap(original.Width, original.Height, PixelFormat.Format32bppArgb);using (Graphics g = Graphics.FromImage(source))else{
source = original;
}
// Lock source bitmap in memory
BitmapData sourceData = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);// Copy image data to binary array


int imageSize = sourceData.Stride * sourceData.Height;byte[] sourceBuffer = new byte[imageSize];Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, imageSize);// Unlock source bitmapsource.UnlockBits(sourceData);
// Create destination bitmap
Bitmap destination = new Bitmap(source.Width, source.Height, PixelFormat.Format1bppIndexed);//Add to destination DPI value from the original bitmap DPI Valuedestination.SetResolution(source.HorizontalResolution, source.VerticalResolution);
// Lock destination bitmap in memory

BitmapData destinationData = destination.LockBits(new Rectangle(0, 0, destination.Width, destination.Height), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed);// Create destination bufferimageSize = destinationData.Stride * destinationData.Height;









byte[] destinationBuffer = new byte[imageSize];int sourceIndex = 0;int destinationIndex = 0;int pixelTotal = 0;byte destinationValue = 0;int pixelValue = 128;int height = source.Height;int width = source.Width;int threshold = 500;// Iterate lines
{
sourceIndex = y * sourceData.Stride;
destinationIndex = y * destinationData.Stride;
destinationValue = 0;
pixelValue = 128;
for (int y = 0; y < height; y++)// Iterate pixels
{
for (int x = 0; x < width; x++)// Compute pixel brightness (i.e. total of Red, Green, and Blue values)pixelTotal = sourceBuffer[sourceIndex + 1] + sourceBuffer[sourceIndex + 2] + sourceBuffer[sourceIndex + 3];

{
destinationValue += (
}

{
destinationBuffer[destinationIndex] = destinationValue;
destinationIndex++;
destinationValue = 0;
pixelValue = 128;
}
if (pixelTotal > threshold)byte)pixelValue;if (pixelValue == 1)else{
pixelValue >>= 1;
}
sourceIndex += 4;
}

{
destinationBuffer[destinationIndex] = destinationValue;
}
}
if (pixelValue != 128)// Copy binary image data to destination bitmap
Marshal.Copy(destinationBuffer, 0, destinationData.Scan0, imageSize);// Unlock destination bitmapdestination.UnlockBits(destinationData);
// Return
}
return destination;
{

Comments