高手帮我看看这段代码:
    MemoryStream stream =new MemoryStream() ;
    SqlConnection connection = new SqlConnection (Global.DBConn);
    Bitmap bitmap=null;
    Image image=null;
   connection.Open();
   
  SqlCommand command =new SqlCommand ("SELECT 照片 from 专家照片 WHERE 专家编号 = " + id  ,connection);
          
   byte[] blob =(byte[]) command.ExecuteScalar();
   stream.Write (blob,0,blob.Length);
   bitmap=new Bitmap(stream);
   int width =100;
   int height = (int)(width*((double) bitmap.Height /(double) bitmap.Width ));
   image =bitmap.GetThumbnailImage(width,height,null,IntPtr.Zero );
   context.Response.ContentType="image/jpeg";
   ......出现的问题是:显示某些图片时,bitmap=new Bitmap(stream)处提示stream是无效的参数;
而显示另外一些图片时就很正常
问题出在哪呀?是不是和我存入图片的格式有关,可是无论我存入什么类型的格式 blob字节数组都是有值的。郁闷

解决方案 »

  1.   

    保存images进SQL Server数据库     为了保存图片到table你首先得从客户端上传它们到你的web服务器。你可以创建一个web form,用TextBox得到图片的标题,用HTML File Server Control得到图片文件。确信你设定了Form的encType属性为multipart/form-data。 Stream imgdatastream = File1.PostedFile.InputStream;int imgdatalen = File1.PostedFile.ContentLength;string imgtype = File1.PostedFile.ContentType;string imgtitle = TextBox1.Text;byte[] imgdata = new byte[imgdatalen];int n = imgdatastream.Read(imgdata,0,imgdatalen);string connstr=((NameValueCollection)Context.GetConfig("appSettings"))["connstr"];SqlConnection connection = new SqlConnection(connstr);SqlCommand command = new SqlCommand("INSERT INTO ImageStore(imgtitle,imgtype,imgdata)VALUES ( @imgtitle, @imgtype,@imgdata )", connection ); SqlParameter paramTitle = new SqlParameter("@imgtitle", SqlDbType.VarChar,50 );paramTitle.Value = imgtitle;command.Parameters.Add( paramTitle); SqlParameter paramData = new SqlParameter( "@imgdata", SqlDbType.Image );paramData.Value = imgdata;command.Parameters.Add( paramData ); SqlParameter paramType = new SqlParameter( "@imgtype", SqlDbType.VarChar,50 );paramType.Value = imgtype;command.Parameters.Add( paramType ); connection.Open();int numRowsAffected = command.ExecuteNonQuery();connection.Close(); 从数据库中输出图片     现在让我们从数据库中取出我们刚刚保存的图片,在这儿,我们将直接将图片输出至浏览器。你也可以将它保存为一个文件或做任何你想做的。 private void Page_Load(object sender, System.EventArgs e){string imgid =Request.QueryString["imgid"];string connstr=((NameValueCollection)Context.GetConfig("appSettings"))["connstr"];string sql="SELECT imgdata, imgtype FROM ImageStore WHERE id = "+ imgid;SqlConnection connection = new SqlConnection(connstr);
    SqlCommand command = new SqlCommand(sql, connection);connection.Open();SqlDataReader dr = command.ExecuteReader();if(dr.Read()){        Response.ContentType = dr["imgtype"].ToString();        Response.BinaryWrite( (byte[]) dr["imgdata"] );}connection.Close();}     在上面的代码中我们使用了一个已经打开的数据库,通过datareader选择images。接着用Response.BinaryWrite代替Response.Write来显示image文件。
      

  2.   

    这是一个标准上传图片例题下面的代码实现向SQL Server数据库添加图片和文字的功能。首先,在SQL查询分析器中执行下面的语句,以创建表和存储过程。Drop Table PersonGo
    Create Table Person
    (
    PersonID Int Identity,
    PersonEmail Varchar(255),
    PersonName Varchar(255),
    PersonSex Char(1),
    PersonDOB DateTime,
    PersonImage Image,
    PersonImageType Varchar(255)
    )Drop Proc sp_person_ispGo
    Create Proc sp_person_isp
    @PersonEmail Varchar(255),
    @PersonName Varchar(255),
    @PersonSex Char(1),
    @PersonDOB DateTime,
    @PersonImage Image,
    @PersonImageType Varchar(255)
    As
    Begin
      Insert into Person 
       (PersonEmail, PersonName, PersonSex, 
       PersonDOB, PersonImage, PersonImageType)
       Values
       (@PersonEmail, @PersonName, @PersonSex, 
       @PersonDOB, @PersonImage, @PersonImageType)
    EndGo下面就是完整的代码,拷贝即可运行:<%@ Import Namespace="System.IO" %>
    <%@ Import Namespace="System.Data.SqlClient" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Page Language="vb" %>
    <HTML>
    <HEAD>
    <title>向SQL Server插入图片</title>
    <script runat="server">
    Public Sub AddPerson(sender As Object, e As EventArgs)
      Dim intImageSize As Int64
      Dim strImageType As String
      Dim ImageStream As Stream
      ' 获得图片的大小
      intImageSize = PersonImage.PostedFile.ContentLength
      ' 获得图片类型
      strImageType = PersonImage.PostedFile.ContentType
      '读取图片
      ImageStream = PersonImage.PostedFile.InputStream
      Dim ImageContent(intImageSize) As Byte
      Dim intStatus As Integer
      intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
      ' 创建Connection和Command对象
      Dim strCnn As String = "Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;"
      Dim myConnection As New SqlConnection(strCnn)
      Dim myCommand As New SqlCommand("sp_person_isp", myConnection)
      ' 使用存储过程
      myCommand.CommandType = CommandType.StoredProcedure
      ' 向存储过程添加参数
      Dim prmEmail As New SqlParameter("@PersonEmail", SqlDbType.VarChar, 255)
      prmEmail.Value = txtPersonEmail.Text
      myCommand.Parameters.Add(prmEmail)  Dim prmName As New SqlParameter("@PersonName", SqlDbType.VarChar, 255)
      prmName.Value = txtPersonName.Text
      myCommand.Parameters.Add(prmName)
      Dim prmSex As New SqlParameter("@PersonSex", SqlDbType.Char, 1)  If sexMale.Checked Then
      prmSex.Value = "M"
      Else
      prmSex.Value = "F"
      End If
      myCommand.Parameters.Add(prmSex)
      
      Dim prmPersonDOB As New SqlParameter("@PersonDOB", SqlDbType.DateTime)
      prmPersonDOB.Value = txtPersonDob.Text
      myCommand.Parameters.Add(prmPersonDOB)  Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image)
      prmPersonImage.Value = ImageContent
      myCommand.Parameters.Add(prmPersonImage)  Dim prmPersonImageType As New SqlParameter("@PersonImageType", SqlDbType.VarChar, 255)
      prmPersonImageType.Value = strImageType
      myCommand.Parameters.Add(prmPersonImageType)  Try
      myConnection.Open()
      myCommand.ExecuteNonQuery()
      myConnection.Close()
      Response.Write("添加成功!")
        Catch SQLexc As SqlException
        Response.Write("添加失败,原因:" & SQLexc.ToString())
      End Try
    End Sub
    </script>
    </HEAD>
    <body style="FONT: 9pt 宋体">
        <form enctype="multipart/form-data" runat="server" ID="Form1">
          <asp:Table Runat="server" Width="50%" BorderWidth="1" BackColor="Beige" ID="Table1"
     Font-Name="宋体" Font-Size="9pt">
            <asp:TableRow>
              <asp:TableCell ColumnSpan="2" BackColor="#ff0000">
                <asp:Label ForeColor="#ffffff" font-bold="True" Runat="server" Text="添加新用户" ID="Label1" />
              </asp:TableCell>
            </asp:TableRow>
            <asp:TableRow>
              <asp:TableCell HorizontalAlign="Right">
                <asp:Label Runat="server" Text="姓名" ID="Label2" />
              </asp:TableCell>
              <asp:TableCell>
                <asp:TextBox id="txtPersonName" Runat="server" />
              </asp:TableCell>
            </asp:TableRow>
            <asp:TableRow>
              <asp:TableCell HorizontalAlign="Right">
                <asp:Label Runat="server" Text="电子邮件" ID="Label3" />
              </asp:TableCell>
              <asp:TableCell>
                <asp:TextBox id="txtPersonEmail" Runat="server" />
              </asp:TableCell>
            </asp:TableRow>
            <asp:TableRow>
              <asp:TableCell HorizontalAlign="Right">
                <asp:Label Runat="server" Text="性别" ID="Label4"/>
              </asp:TableCell>
              <asp:TableCell>
                <asp:RadioButton GroupName="sex"  Text="男" ID="sexMale" Runat="server" />
                <asp:RadioButton GroupName="sex"  Text="女" ID="sexFeMale" Runat="server" />
              </asp:TableCell>
            </asp:TableRow>
            <asp:TableRow>
              <asp:TableCell HorizontalAlign="Right">
                <asp:Label Runat="server" Text="出生日期" ID="Label5"/>
              </asp:TableCell>
              <asp:TableCell>
                <asp:TextBox id="txtPersonDOB" Runat="server" />
              </asp:TableCell>
            </asp:TableRow>
            <asp:TableRow>
              <asp:TableCell HorizontalAlign="Right">
                <asp:Label Runat="server" Text="照片" ID="Label6"/>
              </asp:TableCell>
              <asp:TableCell>
                <input type="file" id="PersonImage" runat="server" NAME="PersonImage" /></asp:TableCell>
            </asp:TableRow>
            <asp:TableRow>
              <asp:TableCell ColumnSpan="2" HorizontalAlign="Center">
                <asp:Button Text=" 添  加 " OnClick="AddPerson" Runat="server" ID="Button1"/>
              </asp:TableCell>
            </asp:TableRow>
          </asp:Table>
        </form>
    </body>
    </HTML>
      

  3.   

    楼主那个command.ExecuteScalar();好像是返回第一列的第一行,没值的情况下也有返回null,
    可能是你那个数据库里面没有值还有先判断有没有值再byte
      

  4.   

    谢谢 lengyubing_1983(冷于冰) ,liym15(期待)二位的关注,我现在的问题是保存都是成功的,只是在显示的地方出了点问题,即使不能显示图片的也能读出图片的字节数来。 powerllr(笨笨的招财鸡),您好 您说得很对,不过BYTE我检查过,是有的。只有有的图片可以显示,有些不能显示,所以郁闷
      

  5.   

    bitmap=new Bitmap(stream);我觉得是不是存储在数据库中的某些图片的字节流无法用来初始化BitMap对象?
      

  6.   

    我现在觉得是保存图片有问题,我是这样做的,高手指点一下错误所在,谢谢!
      ......      
      HttpFileCollection MyFileColl = HttpContext.Current.Request.Files; 
      HttpPostedFile MyPostedFile = MyFileColl[0]; 
      if (MyPostedFile.ContentType.ToString().ToLower().IndexOf("image") < 0) 
      { 
         ShowMessageBox("无效的图形格式。");
         //Response.Write("无效的图形格式。"); 
         return; 
       } 
       //显示缩略图,表示上传成功(假,还没有保存到数据库)
       GetThumbNail(MyPostedFile.FileName, 100, 100, MyPostedFile.ContentType.ToString(), false, MyPostedFile.InputStream); 
       //为该图片流对象赋值
       ImgStream=MyPostedFile.InputStream;
      ......
       //图片流转化为字节数组
       byte[] Buffer;
       if(ExpertAddingInfo.ExpPictureStream==null)
       {
           Buffer=new byte[1];
       }
    else
      {
          System.IO.Stream mystream = ExpertAddingInfo.ExpPictureStream;
          Buffer = new byte[mystream.Length];
          mystream.Read(Buffer,0,(int)mystream.Length);
    }
          arrPara[1]=new SqlParameter("@ExpPictureStream",Buffer);
          return (db.ExeSQL("usp_ExpertInfo_Update",arrPara,ConnString));
    注:“usp_ExpertInfo_Update”是一个存储过程,其中@ExpPictureStream是image类型的,
    请高手指点上述过程是否将一个图片以字节数组的形式正确的存入了数据库,谢谢!