博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在DevExpress GridControl的一列中显示图片
阅读量:6960 次
发布时间:2019-06-27

本文共 7107 字,大约阅读时间需要 23 分钟。

        作者:jiankunking 出处:

        近期做项目的时候用到了将GridControl中一列设置为PictureEdit类型,然后通过这一列来显示图片。经过尝试发现有下面两种方式可行。

方法一、知道图片的路径与名称

        比方:在数据库中存储了图片的路径(包含:本地路径、server路径),那么在能够通过非绑定列的方式来实现。

1、创建了一个非绑定列并设置其对应的属性。属性设置例如以下:

        FieldName设为 Photo(该字段名必须是唯一的)

        UnboundType设为 UnboundColumnType.Object
        ColumnEdit设为RepositoryItemPictureEdit类的实例(该操作PictureEdit 为该列的内置编辑器)

        2.、加入GridView的CustomUnboundColumnData事件。用于为非绑定列填充数据。

        既然已经设置完毕了。那么详细的代码怎么编写呢?详细代码例如以下:

private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)        {            if (e.Column.FieldName == "Photo" && e.IsGetData)            {                //RefImage是存储图片路径的那一列                string filePath = (string)((DataRowView)e.Row)["RefImage"];                Image img = null;                try                {                    //推断图片路径是否为网络路径                    if (UrlDiscern(filePath))                    {                        //文件是否存在                        if (RemoteFileExists(filePath))                        {                            //读取文件                            using (WebClient wc = new WebClient())                            {                                img = new Bitmap(wc.OpenRead(filePath));                            }                        }                    }                    // 推断本地文件是否存在                    else if (LocalFileExists(filePath))                    {                        //载入本地图片                        img = Image.FromFile(filePath);                    }                    //pictureEdit列绑定图片                    e.Value = img;                }                catch (Exception ex)                {                    MessageBox.Show(ex.ToString());                }            }        }        ///         /// 推断远程文件是否存在        ///         ///         /// 
public bool RemoteFileExists(string fileUrl) { HttpWebRequest re = null; HttpWebResponse res = null; try { re = (HttpWebRequest)WebRequest.Create(fileUrl); res = (HttpWebResponse)re.GetResponse(); if (res.ContentLength != 0) { //MessageBox.Show("文件存在"); return true; } } catch (Exception) { //MessageBox.Show("无此文件"); return false; } finally { if (re != null) { re.Abort();//销毁关闭连接 } if (res != null) { res.Close();//销毁关闭响应 } } return false; } /// /// 推断本地文件是否存在 /// /// ///
public bool LocalFileExists(string filePath) { if (File.Exists(filePath)) { return true; } else { return false; } } /// /// 识别urlStr是否是网络路径 /// /// ///
public bool UrlDiscern(string urlStr) { if (Regex.IsMatch(urlStr, @"((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?")) { return true; } else { return false; } }

假设图片在单元格中显示有问题的话,能够调整  

方法二、知道图片的路径与名称

        除了方法一之外,我们还能够使用流的方式的来载入图片,即依据图片路径将图片转化为流。然后直接绑定到RepositoryItemPictureEdit列上就可以。

此时不须要改动列的绑定类型。仅仅须要该列的FieldName与数据源中的byte[]流的所在列的名称一致就可以,

        假设这么绑定无效的话,能够在gridcontrol的数据源(此处假设为Dataset)中新增一列

ds.Tables[0].Columns.Add("Photo", System.Type.GetType("System.Byte[]"));
        然后,依据路径载入图片到Photo列中,

  byte[] bb = PubFunc.getImageByte(path, webClient);  ds.Tables[0].Rows[i]["Photo"] = bb;

     当中,可能会用到的函数例如以下: 
///         /// 返回图片的字节流byte[]        ///         ///         ///         /// 
public byte[] getImageByte(string imagePath) { byte[] imgByte = null; try { if (UrlDiscern(imagePath)) { using(WebClient webClient=new WebClient()) { Bitmap bt = new Bitmap(webClient.OpenRead(imagePath)); imgByte = PubFunc.ImgToByte(bt); } } else { using (FileStream files = new FileStream(imagePath, FileMode.Open)) { imgByte = new byte[files.Length]; files.Read(imgByte, 0, imgByte.Length); files.Close(); } } } catch (Exception ee) { MessageBox.Show(ee.ToString()); } return imgByte; }
///         /// 图片转换成字节流        ///         /// 要转换的Image对象        /// 
转换后返回的字节流
public byte[] ImgToByte(Image img) { try { using (MemoryStream ms = new MemoryStream()) { byte[] imagedata = null; img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); imagedata = ms.GetBuffer(); return imagedata; } } catch (Exception ee) { MessageBox.Show(ee.ToString()); return null; } }
小注:

使用以上方法,高速滑动滑动条的时候,会出现卡死的现象,由于上述代码是每次实时读取图片资源的。应该加入一个图片路径、图片 字典,以降低图片的反复读取。

private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)        {            if (e.Column.FieldName == "Photo" && e.IsGetData)            {                string filePath = (string)((DataRowView)e.Row)["RefImage"];                if (!images.ContainsKey(filePath))                {                    Image img = null;                    try                    {                        if (PubFunc.UrlDiscern(filePath))                        {                            if (FileUpDownload.RemoteFileExists(filePath))                            {                                using (WebClient wc = new WebClient())                                {                                    //Bitmap bmtemp = new Bitmap(wc.OpenRead(filePath));                                    //img = new Bitmap(bmtemp, 75, 75);                                    img = new Bitmap(wc.OpenRead(filePath));                                }                            }                        }                        else if (PubFunc.LocalFileExists(filePath))                        {                            img = Image.FromFile(filePath);                        }                        images.Add(filePath, img);                    }                    catch (Exception ex)                    {                        MessageBox.Show(ex.ToString());                    }                }                e.Value = images[filePath];            }        }

转载于:https://www.cnblogs.com/clnchanpin/p/7147832.html

你可能感兴趣的文章
1.4变量和数据类型进阶
查看>>
数据块对齐
查看>>
Http 请求方式:Get 与Post
查看>>
delphi 操作文件时间的函数
查看>>
nodjs 生产环境及升级问题
查看>>
JS判断客户端是否是iOS或者Android手机移动端
查看>>
Swing控件
查看>>
快速JavaEE轻量级框架&公用业务模块 设计&实现 6.1 - DAO测试
查看>>
文本特征提取算法实现
查看>>
这个qq的域名【c.gj.qq.com】是做什么的?chrome浏览器,访问什么网站都有这个请求...
查看>>
ubuntu14.04+Django1.7.1+nginx1.6+uwsgi2.0环境搭建
查看>>
C++中的类型转换
查看>>
大数据引发的变革与企业面临的挑战
查看>>
LRSlidingTableViewCell
查看>>
FlipCardNavigationView
查看>>
【系统日志笔记二】——撸起袖子写个自定义日志注解
查看>>
完全平衡树的简单实现(Scala)
查看>>
HttpServlet详解
查看>>
无线网络
查看>>
架构设计:生产者/消费者模式 第4页:注意事项
查看>>