winform双缓冲, 从内存画图到到picturebox
private Image DrawImage(string strFilePath)
{
try
{
Bitmap bitmap = new Bitmap(strFilePath);
//如果原图片是索引像素格式之列的,则需要转换
if (IsPixelFormatIndexed(bitmap.PixelFormat))
{
Bitmap bmp = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bmp))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(bitmap, 0, 0);
Pen pen = new Pen(Color.Red, 3);
for (int i = 0; i < bitmap.Width; i += bitmap.Width / 4)
{
g.DrawLine(pen, i, 0, i, bitmap.Height);
}
for (int i = 0; i < bitmap.Height; i += bitmap.Height / 4)
{
g.DrawLine(pen, 0, i, bitmap.Width, i);
}
}
}
else
{
Graphics g = Graphics.FromImage(bitmap);
g.DrawImage(bitmap, bitmap.Width, bitmap.Height);
Pen pen = new Pen(Color.Red, 3);
for (int i = 0; i < bitmap.Width; i += bitmap.Width / 4)
{
g.DrawLine(pen, i, 0, i, bitmap.Height);
}
for (int i = 0; i < bitmap.Height; i += bitmap.Height / 4)
{
g.DrawLine(pen, 0, i, bitmap.Width, i);
}
}
return bitmap;
}
catch { return null; }
}
/// 会产生graphics异常的PixelFormat
/// </summary>
private static PixelFormat[] indexedPixelFormats = { PixelFormat.Undefined, PixelFormat.DontCare,
PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed,
PixelFormat.Format8bppIndexed
};
/// <summary>
/// 判断图片的PixelFormat 是否在 引发异常的 PixelFormat 之中
/// </summary>
/// <param name="imgPixelFormat">原图片的PixelFormat</param>
/// <returns></returns>
private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
{
foreach (PixelFormat pf in indexedPixelFormats)
{
if (pf.Equals(imgPixelFormat)) return true;
}
return false;
}
下面这个函数从内存画图到picbox, 因为有些图片是索引色, 所以先鉴定了下图片. 画图时用线画了格子. 不用时可以去了.