C# 如何将32位深的bmp转成24位深的BMP
时间: 2024-02-05 15:10:37 浏览: 233
纯C语言读写24BMP文件,32位BMP转24位BMP
以下 C# 将32位深的 BMP 转成 24位深的 BMP 的示例代码:
```csharp
using System.Drawing;
using System.Drawing.Imaging;
public static void Convert32BitTo24Bit(string inputFilePath, string outputFilePath)
{
// Load the input bitmap.
Bitmap inputBitmap = new Bitmap(inputFilePath);
// Create a new 24-bit bitmap with the same dimensions as the input bitmap.
Bitmap outputBitmap = new Bitmap(inputBitmap.Width, inputBitmap.Height, PixelFormat.Format24bppRgb);
// Lock the input bitmap's bits.
Rectangle inputRect = new Rectangle(0, 0, inputBitmap.Width, inputBitmap.Height);
BitmapData inputData = inputBitmap.LockBits(inputRect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Lock the output bitmap's bits.
Rectangle outputRect = new Rectangle(0, 0, outputBitmap.Width, outputBitmap.Height);
BitmapData outputData = outputBitmap.LockBits(outputRect, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
// Copy the input bitmap's bits to the output bitmap, discarding the alpha channel.
unsafe
{
byte* inputPtr = (byte*)inputData.Scan0;
byte* outputPtr = (byte*)outputData.Scan0;
for (int y = 0; y < inputBitmap.Height; y++)
{
for (int x = 0; x < inputBitmap.Width; x++)
{
outputPtr[0] = inputPtr[2];
outputPtr[1] = inputPtr[1];
outputPtr[2] = inputPtr[0];
inputPtr += 4;
outputPtr += 3;
}
inputPtr += inputData.Stride - (inputBitmap.Width * 4);
outputPtr += outputData.Stride - (inputBitmap.Width * 3);
}
}
// Unlock the input bitmap's bits.
inputBitmap.UnlockBits(inputData);
// Unlock the output bitmap's bits.
outputBitmap.UnlockBits(outputData);
// Save the output bitmap.
outputBitmap.Save(outputFilePath, ImageFormat.Bmp);
}
```
使用示例:
```csharp
Convert32BitTo24Bit("input.bmp", "output.bmp");
```
其中,`inputFilePath` 参数是要转换的 BMP 文件路径,`outputFilePath` 参数是转换后的 BMP 文件路径。
阅读全文