winform-datagridview列显示图片

1、创建列格式化事件,指定图片列
/// <summary> /// datagridview列格式化事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dataGridViewFeature_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (dataGridViewFeature.Columns[e.ColumnIndex].Name.Equals("Image") && e.Value != null) { string path = e.Value.ToString();
          // e.Value
= GetImage(path); } } /// <summary> /// 根据路径获取图片 /// </summary> /// <param name="path"></param> /// <returns></returns> public Image GetImage(string path) { if (!path.Equals("")) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Image result = System.Drawing.Image.FromStream(fs); //调整图片大小 result = FixedSize(result, 80, 80); fs.Close(); return result; } return null; } /// <summary> /// 调整图片大小 /// </summary> /// <param name="imgPhoto">原图片</param> /// <param name="Width">更改后宽</param> /// <param name="Height">更改后高</param> /// <returns></returns> private Image FixedSize(Image imgPhoto, int Width, int Height) { int sourceWidth = imgPhoto.Width; int sourceHeight = imgPhoto.Height; int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; nPercentW = ((float)Width / (float)sourceWidth); nPercentH = ((float)Height / (float)sourceHeight); if (nPercentH < nPercentW) { nPercent = nPercentH; destX = System.Convert.ToInt16((Width - (sourceWidth * nPercent)) / 2); } else { nPercent = nPercentW; destY = System.Convert.ToInt16((Height - (sourceHeight * nPercent)) / 2); } int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.Clear(Color.Red); grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new Rectangle(-1, -1, Width, Height), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); return bmPhoto; }
原文地址:https://www.cnblogs.com/lijl/p/14958493.html