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; }
复制代码

 

posted @   乡野小猫  阅读(2346)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示