简体   繁体   中英

32bit rgb bmp to 24bit rgb bmp in C# problem

I have to convert 32bit rgb bmp images in to 24 bits rgb bmp.

This is what i am trying to do

Bitmap b1=new Bitmap(sorecFileName);

Bitmap b2=new 

Bitmap(b1.Size.Width,b1.Size.Height,System.Drawing.Imaging.PixelFormat.Format24bppRgb);       
b2.SetResolution(b1.HorizontalResolution, b1.VerticalResolution);

Graphics g=Graphics.FromImage(b2);

g.DrawImage(b1,0,0);

//continue to draw on g here to add text or graphics.

g.Dispose();

b2.Save(destinationFileName);

The code compiles fine and generates the output image of 24bpp but its not in the rgb format any more. Why is this so?

I figured it out as I have a library that takes input of an image as rgb24 and displays it. So when I try to give the file generated by above code as input to the function, it displays noisy image.

However, if I open the same file in paint and save it as 24bpp bmp, and input it to the function, the picture displays fine. What am I missing?

  b2.Save(destinationFileName);

You didn't specify the image file format. The default is PNG, not BMP. You now probably have a .bmp file on disk that actually contains a PNG image. That can go undetected for quite a while, lots of graphics programs pay attention to the file header instead of the file name extension. MSPaint for example will have no trouble loading the file. Just like any other program that uses GDI+. You might not be so lucky with a program that blindly assumes that the file contains a BMP and does no checking at all. Fix:

  b2.Save(destinationFilename, System.Drawing.Imaging.ImageFormat.Bmp);

如果你有一个blackimage - 添加g.Clear(Color.White);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM