Thanks to Bob Powel (http://www.bobpowell.net/onebit.htm) I'm able to
compress an image. However, this method takes a long time to compress an
image. Does anyone know a quicker way? (The images I have to compress are
already in black and white).
Code used:
Bitmap bmpOrig =
(System.Drawing .Bitmap)Image.F romFile(OrigFil eName).Clone();
Bitmap objConvImage = new Bitmap(bmpOrig. Width, bmpOrig.Height,
PixelFormat.For mat1bppIndexed) ;
objConvImage.Se tResolution(300 ,300);
BitmapData bmd = objConvImage.Lo ckBits(new Rectangle(0, 0,
objConvImage.Wi dth, objConvImage.He ight),
ImageLockMode.R eadWrite, PixelFormat.For mat1bppIndexed );
for(int y=0; y < bmpOrig.Height; y++)
{
for(int x=0; x < bmpOrig.Width; x++)
{
if(bmpOrig.GetP ixel(x,y).GetBr ightness()>0.5f )
SetIndexedPixel (x,y,bmd,true);
}
}
objConvImage.Un lockBits(bmd);
objConvImage.Sa ve(FileName, _ImageCodecInfo , _ImageCodecPara ms);
objConvImage.Di spose();
bmpOrig.Dispose ();
and the functions:
private static unsafe void SetIndexedPixel (int x, int y, BitmapData bmd,
bool pixel)
{
byte* p = (byte*)bmd.Scan 0.ToPointer();
int index = y * bmd.Stride+(x>> 3);
byte mask = (byte)(0x80>>(x &0x7));
if(pixel)
p[index]|=mask;
else
p[index]&=(byte)(mask^0 xff);
}
private static ImageCodecInfo GetCodecInfo(st ring FileFormat)
{
ImageCodecInfo[] encoders = ImageCodecInfo. GetImageEncoder s();
for (int j=0; j < encoders.Length ; ++j)
{
if (encoders[j].MimeType == FileFormat)
return encoders[j];
}
return null;
}