做Windows form软件开发的时候碰到了图片处理。分享一些图片转换的方法。
32bpp转24bpp
public static public static Bitmap Convert32bppTo24bpp(Bitmap bmpSource)
{
Bitmap bmpDest = null;
//When 32 bpp bitmap, convert to 24 bpp bitmap
if (bmpSource != null &&
(PixelFormat.Format32bppArgb == bmpSource.PixelFormat ||
PixelFormat.Format32bppPArgb == bmpSource.PixelFormat ||
PixelFormat.Format32bppRgb == bmpSource.PixelFormat))
{
//Convert to 24-bit Bitmap
bmpDest = new Bitmap(bmpSource.Width, bmpSource.Height, PixelFormat.Format24bppRgb);
bmpDest.SetResolution(bmpSource.HorizontalResolution, bmpSource.VerticalResolution);
using (Graphics g = Graphics.FromImage(bmpDest))
{
//Use high quality graphics to draw
g.SmoothingMode = SmoothingMode.HighSpeed;
g.CompositingQuality = CompositingQuality.HighSpeed;
g.PixelOffsetMode = PixelOffsetMode.HighSpeed;
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.DrawImage(bmpSource, 0, 0);
}
}
return bmpDest;
}
同样,32bpp、24bpp转16bpp
public static Bitmap ConvertTo16bppRgb565(Bitmap img24or32Bitmap)
{
//Create Format16bppRgb565 Bitmap
var bitmap16bit = new Bitmap(img24or32Bitmap.Width, img24or32Bitmap.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb565);
//Keep same resolution format
bitmap16bit.SetResolution(img24or32Bitmap.HorizontalResolution, img24or32Bitmap.VerticalResolution);
using (var g = Graphics.FromImage(bitmap16bit))
{
//Use high quality graphics to draw
g.SmoothingMode = SmoothingMode.Hi