Bitmap: From 32bppARGB to 8bppIndexed

R

RicercatoreSbadato

I'm trying to use this code but something goes wrong. Any idea?

BitmapData oldData = img.LockBits(new Rectangle(0,0,width,height),
ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

BitmapData newData = newBMP.LockBits(new Rectangle(0,0,width,height),
ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);

int remain_old = oldData.Stride - width * 4;
int remain_new = newData.Stride - width * 1;

// unsafe block

unsafe
{
byte* currentPosition_Old = (byte*) oldData.Scan0;
byte* currentPosition_New = (byte*) newData.Scan0;

// Standard Deviation

for (int x=0; x<=width; x++)
{
for (int y=0; y<height; y++)
{
currentPosition_New[0] = (byte) currentPosition_Old[0];

currentPosition_Old += 4; // ARGB
currentPosition_New += 1; // indexed
}
currentPosition_Old += remain_old;
currentPosition_New += remain_new;
}
}
img.UnlockBits(oldData);
newBMP.UnlockBits(newData);
 
B

Bob Powell [MVP]

For details on how to access the data provided by LockBits see the article
in the GDI+ FAQ.

If you want to create an 8bpp indexed image from a 32 bpp one you can either
save the image as a GIF and hope that the spread palette is ok for your
purposes or create an optimised palette using the octtree quantization
method as described in this MSDN article:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/colorquant.asp

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top