G
Guest
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.FromFile(OrigFileName).Clone();
Bitmap objConvImage = new Bitmap(bmpOrig.Width, bmpOrig.Height,
PixelFormat.Format1bppIndexed);
objConvImage.SetResolution(300,300);
BitmapData bmd = objConvImage.LockBits(new Rectangle(0, 0,
objConvImage.Width, objConvImage.Height),
ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed );
for(int y=0; y < bmpOrig.Height; y++)
{
for(int x=0; x < bmpOrig.Width; x++)
{
if(bmpOrig.GetPixel(x,y).GetBrightness()>0.5f)
SetIndexedPixel(x,y,bmd,true);
}
}
objConvImage.UnlockBits(bmd);
objConvImage.Save(FileName, _ImageCodecInfo, _ImageCodecParams);
objConvImage.Dispose();
bmpOrig.Dispose();
and the functions:
private static unsafe void SetIndexedPixel(int x, int y, BitmapData bmd,
bool pixel)
{
byte* p = (byte*)bmd.Scan0.ToPointer();
int index = y * bmd.Stride+(x>>3);
byte mask = (byte)(0x80>>(x&0x7));
if(pixel)
p[index]|=mask;
else
p[index]&=(byte)(mask^0xff);
}
private static ImageCodecInfo GetCodecInfo(string FileFormat)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j=0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == FileFormat)
return encoders[j];
}
return null;
}
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.FromFile(OrigFileName).Clone();
Bitmap objConvImage = new Bitmap(bmpOrig.Width, bmpOrig.Height,
PixelFormat.Format1bppIndexed);
objConvImage.SetResolution(300,300);
BitmapData bmd = objConvImage.LockBits(new Rectangle(0, 0,
objConvImage.Width, objConvImage.Height),
ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed );
for(int y=0; y < bmpOrig.Height; y++)
{
for(int x=0; x < bmpOrig.Width; x++)
{
if(bmpOrig.GetPixel(x,y).GetBrightness()>0.5f)
SetIndexedPixel(x,y,bmd,true);
}
}
objConvImage.UnlockBits(bmd);
objConvImage.Save(FileName, _ImageCodecInfo, _ImageCodecParams);
objConvImage.Dispose();
bmpOrig.Dispose();
and the functions:
private static unsafe void SetIndexedPixel(int x, int y, BitmapData bmd,
bool pixel)
{
byte* p = (byte*)bmd.Scan0.ToPointer();
int index = y * bmd.Stride+(x>>3);
byte mask = (byte)(0x80>>(x&0x7));
if(pixel)
p[index]|=mask;
else
p[index]&=(byte)(mask^0xff);
}
private static ImageCodecInfo GetCodecInfo(string FileFormat)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j=0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == FileFormat)
return encoders[j];
}
return null;
}