c# 水晶报表显示动态图片

思路:在数据库新建image格式字段【photo1】,原有字段varchar(200)【photo】存放的是图片地址(相对路径,格式"../image/..",非网络图片)

先读取【photo]字段指定的图片,存储图片流到数组,存入到【photo1】中,即可把【photo1】直接拖到水晶报表中。

环境:vs2003 (c#)+sqlserver+crystal reports10  

------------------------------------------------------------华丽无比分割线-------------------------------------------------------

转换函数:

 public static byte[] ReadImage(string path)
  {
   FileStream stream = null;
   try
   {
    stream = File.OpenRead(path);
    return ReadImage(stream);
   }
   finally
   {
    if(stream != null)
    {
     stream.Close();
    }
   }
  }

  /**//// <summary>
  /// 从给定的流中读取数据到一个字节数组中,并返回此数组。
  /// 如果给定的流不是一个图像格式的流,将报异常。
  /// 返回的字节数组中,将非BMP和JEPG格式的图像数据流转换为JEPG格式输出,以支持大多数应用。
  /// 适用于直接从数据库中读取的二进制图像流的处理。
  /// </summary>
  /// <param name="stream">给定的图像数据流。</param>
  /// <returns>从流中读取的数据。</returns>
  public static byte[] ReadImage(Stream stream)
  {
   System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
   byte[] myImage = null;

   if(image.RawFormat.Guid != ImageFormat.Jpeg.Guid && image.RawFormat.Guid != ImageFormat.Bmp.Guid)
   {
    MemoryStream memStream = new MemoryStream();
    image.Save(memStream, ImageFormat.Jpeg);
    myImage = memStream.GetBuffer();
    memStream.Close();
   }
   else
   {
    stream.Position = 0;
    myImage = new byte[stream.Length];
    stream.Read(myImage, 0, (int)stream.Length);
   }
   return myImage;
  }

------------------------------------------------------------华丽无比分割线-------------------------------------------------------

报表datasource绑定:

 string strLogoUrl;
         byte[] bt;

for(int i=0;i<ds.Tables[0].Rows.Count;i++)
      {
       if(ds.Tables[0].Rows[i]["Photo"].ToString()!=null)
       {       
                strLogoUrl =Request.PhysicalApplicationPath+  ds.Tables[0].Rows[i]["Photo"].ToString().Substring(2,ds.Tables[0].Rows[i]["Photo"].ToString().Length-2);//图片绝对路径
         bt=ReadImage(strLogoUrl);
        ds.Tables[0].Rows[i]["Photo1"] = bt;      
        ds.AcceptChanges();
       }
      }
      
      rpt.SetDataSource(ds.Tables[0]); 



[本日志由 春暖花开 于 2009-10-20 01:23 PM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
相关日志:
评论: 2 | 引用: 0 | 查看次数: 486
回复回复春暖花开[2009-10-20 01:25 PM | del]
汗。。。。
最近日志编辑老出问题。
重写!!
回复回复小小[2009-10-19 04:13 PM | del]
崩溃,又一标题党~
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭