从SQL 数据库中读取和存入图片问题

来源:互联网 发布:编程器使用教程 编辑:程序博客网 时间:2024/04/30 22:31

 

5.3  图片数据处理技巧


本实例主要介绍如何将图片存入数据库。将图片存入数据库,首先要在数据库中建立一张表,将存储图片的字段类型设为Image类型,用FileStream类、BinaryReader把图片读成字节的形式,赋给一个字节数组,然后用ADO.SqlCommand对象的ExecuteNonQuery()方法来把数据保存到数据库中。主要代码如下:

    private void button1_Click(object sender, EventArgs e)

        {

          openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";

            if(openFileDialog1.ShowDialog()==DialogResult.OK)

            {
              string fullpath =openFileDialog1.FileName;//文件路径

              FileStream fs = new FileStream(fullpath, FileMode.Open);

                byte[] imagebytes =new byte[fs.Length];

                BinaryReader br = new BinaryReader(fs);

                imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));

                //打开数据库

                SqlConnection  con = new SqlConnection("server=(local);uid=sa;pwd=;database=db_05");

                con.Open();

                SqlCommand com = new SqlCommand("insert into tb_08 values(@ImageList)",con);

                com.Parameters.Add("ImageList", SqlDbType.Image);

                com.Parameters["ImageList"].Value = imagebytes;

               com.ExecuteNonQuery();

               con.Close();

             }    

}

 

本实例主要介绍如何从数据库中把图片读出来。实现本实例主要是利用SqlDataReader从数据库中把Image字段值读出来,赋给一个byte[]字节数组,然后使用MemoryStream类与Bitmap把图片读取出来。主要代码如下:

    private void button1_Click(object sender, EventArgs e)

        {

                 byte[] imagebytes = null;

                //打开数据库

            SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=;database=db_05");

                con.Open();

                SqlCommand com = new SqlCommand("select top 1* from tb_09", con);

                SqlDataReader dr = com.ExecuteReader();

                while (dr.Read())

                {

                    imagebytes = (byte[])dr.GetValue(1);

                }

                dr.Close();

                com.Clone();

                con.Close();

                MemoryStream ms = new MemoryStream(imagebytes);

                Bitmap bmpt = new Bitmap(ms);

                pictureBox1.Image = bmpt;

        }

 

本实例主要介绍如何只允许输入指定图片格式。用OpenFileDialog控件打开图片文件,只要将OpenFileDialog控件的Filter属性指定为特定的图片格式即可。例如,打开.bmp文件的图片,主要代码如下:

this.openFileDialog1.Filter = "bmp文件(*.bmp)|*.bmp";

 

在用pictureBox控件输入图片时,要想统一图片大小,只需把控件的SizeMode属性值设为StretchImage即可,StretchImage值表示图像的大小将调整为控件的大小。这样,图片的大小就统一了。

上一页   首页   下一页
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
ASP.NET下上传图片到数据库,并且读出图片


 

首先在SQL Server中建立一个图片存储的数库表,ImageData Column为图象二进制数据储存字段

,ImageContentType Column为图象文件类型记录字段,ImageDescription Column为储蓄图

象文件说明字段,ImageSize Column为储存图象文件长度字段,结构如下:
CREATE TABLE [dbo].[ImageStore] (
    [ImageID] [int] IDENTITY (1, 1) NOT NULL ,
    [ImageData] [image] NULL ,                            
    [ImageContentType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [ImageDescription] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
    [ImageSize] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
*/

//UpLoadImage.aspx程序内容如下:
<%@ Page Inherits="UploadImage.UploadImage" SRC="UpLoadImage.cs"

Language="C#"%>
<HTML><title>上传图片</title>
<BODY bgcolor="#FFFFFF">
<FORM ENCTYPE="multipart/form-data" RUNAT="server" ID="Form1">
<TABLE RUNAT="server" WIDTH="700" ALIGN="left" ID="Table1" cellpadding="0"

cellspacing="0" border="0">
<TR>
     <TD>上传图片(选择你要上传的图片)</TD>
<TD>
<INPUT TYPE="file" ID="UP_FILE" RUNAT="server" STYLE="Width:320"

ACCEPT="text/*" NAME="UP_FILE">
</TD>
</TR>
<TR>
     <TD>
      文件说明(添加上传图片说明,如:作者、出处)
     </TD>
<TD>
<asp:TextBox RUNAT="server" WIDTH="239" ID="txtDescription"

MAINTAINSTATE="false" />
</TD>
</TR>
<TR>
<TD>
<asp:Label RUNAT="server" ID="txtMessage" FORECOLOR="red"

MAINTAINSTATE="false" />
</TD>
<TD>
<asp:Button RUNAT="server" WIDTH="239" onCLICK="Button_Submit" TEXT="Upload

Image" />
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
//-------------------------------------------------------------------
//UpLoadImage.cs程序内容如下:
using System;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace UploadImage
{
public class UploadImage : Page
{
protected HtmlInputFile UP_FILE;          //HtmlControl、WebControls控件对象
protected TextBox txtDescription;
protected Label txtMessage;
protected Int32 FileLength = 0;          //记录文件长度变量
protected void Button_Submit(System.Object sender, System.EventArgs e) {
HttpPostedFile UpFile = UP_FILE.PostedFile;  //HttpPostedFile对象,用于读取图象文件属性
FileLength = UpFile.ContentLength;     //记录文件长度
try {
  if (FileLength == 0)
  {                                                     //文件长度为零时
    txtMessage.Text = "<b>请你选择你要上传的文件</b>";
  }
  else
  {
    Byte[] FileByteArray = new Byte[FileLength];   //图象文件临时储存Byte数组
    Stream StreamObject = UpFile.InputStream;      //建立数据流对像
    //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
    StreamObject.Read(FileByteArray,0,FileLength);  
    //建立SQL Server链接
    SqlConnection Con = new SqlConnection("Data Source=Localhost;Initial Catalog=testdb;User ID=sa;Pwd=;");
    String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) valueS (@Image, @ContentType, @ImageDescription, @ImageSize)";
    SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
    CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).value = FileByteArray;
    CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).value = UpFile.ContentType;  //记录文件类型
    //把其它单表数据记录上传
    CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).value = txtDescription.Text;
    //记录文件长度,读取时使用
    CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).value = UpFile.ContentLength;
    Con.Open();
    CmdObj.ExecuteNonQuery();
    Con.Close();
    txtMessage.Text = "<p><b>OK!你已经成功上传你的图片</b>";//提示上传成功
  }
  }
  catch (Exception ex)
  {
   txtMessage.Text = ex.Message.ToString();
  }
 }
 }
}
//----------------------------------------------------------------------
//好了,图片已经上传到数据库,现在还要干什么呢?当然是在数据库中读取及显示在Web页中啦,

请看以下程序:
//ReadImage.aspx程序内容如下:
/-----------------------------------------------------------------------
<%@ Page Inherits="ReadImage.MainDisplay" SRC="ReadImage.cs"%>
//----------------------------------------------------------------------
//ReadImage.cs程序内容如下:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace ReadImage {
public class MainDisplay : System.Web.UI.Page {
public void Page_Load(System.Object sender, System.EventArgs e) {
    int ImgID = Convert.ToInt32(Request.QueryString["ImgID"]);  //ImgID为图片

ID
    //建立数据库链接
    SqlConnection Con = new SqlConnection("Data Source=KING;Initial

Catalog=testdb;User ID=sa;Pwd=;");
    String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
    SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
    CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).value = ImgID;
    Con.Open();
    SqlDataReader SqlReader = CmdObj.ExecuteReader();
    SqlReader.Read();    
    Response.ContentType = (string)SqlReader["ImageContentType"];//设定输出文

件类型
    //输出图象文件二进制数制
    Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0,

(int)SqlReader["ImageSize"]);    
    Response.End();
    Con.Close();
    //很简单吧^_^
 }
}
}
//--------------------------------------------------------------------
//最后,我们当然要把它在Web页面显示出来啦
//ShowImage.hml
<html>
<body>
这个是从数据库读取出来的图象:<img src="ReadImage.aspx?ImgID=1">
<body>
</html>
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
将图片插入数据库并使用asp.net读取出来的正确方
 
作者:佚名    文章来源:不详    点击数:68    更新时间:2006-11-7
 
书写本文是因为今天见到CSDN的首页上一篇存在明显失误的名为“在Asp.Net中从sqlserver检索(retrieve)图片”的文章。不说其错误是因为用其方法确实能从数据库中读取出图片并显示在浏览器,说其失误是因为代码的意图不能被完全的实现,作者也似乎对http协议以及浏览器在处理http数据的流程一知半解。

 

1、如何出错

以下是这片文章提到的方法:

Public Sub Page_Load(sender As Object, e As EventArgs)
Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim myCommand As New SqlCommand("Select * from Person", myConnection)
Try
myConnection.Open()
Dim myDataReader as SqlDataReader
myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

Do While (myDataReader.Read())
Response.ContentType = myDataReader.Item("PersonImageType")
Response.BinaryWrite(myDataReader.Item("PersonImage"))
Loop

myConnection.Close()
Response.Write("Person info successfully retrieved!")
Catch SQLexc As SqlException
Response.Write("Read Failed : " & SQLexc.ToString())
End Try
End Sub

显然,编程者是想将Person表中所有的记录中的PersonImage字段所存储的图片一次性地输出到浏览器中,并且在输出成功地情况下在已输出的图片的下方打印出“Person info successfully retrieved!”信息。然而事实上上述代码仅仅能正确地输出第一条记录中的图片。对于浏览器来说,一个http请求获取一个文件(html或者图片),所以以上代码的输出将被作为一个文件(类型依据Response.ContentType = myDataReader.Item("PersonImageType")定)被浏览器处理。如果http相应的类型是image/jpeg之类的图片,则浏览器使用相应的图片解析功能对这一个图片文件进行解析。因此,上述代码的显示结果只能是第一条记录PersonImage字段的图片。后面的记录输出的图片数据将成为第一张图片的多余数据(此点具有普遍性,但并非绝对,依图片的格式而定),从而后面的“Person info successfully retrieved!”的信息也自然无法本显示出来,因为这些信息已经是图片文件里面的编码了。

 

2、正确的做法

A、将图片输入到数据库中,以下是一个将图片输入到数据库的代码片断:(完整的DEMO程序见附录一)

FileStream fs=File.OpenRead(filePath.Text);

byte[] content=new byte[fs.Length];

fs.Read(content, 0,content.Length);

fs.Close();

 

SqlConnection conn=new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DatabaseImage;Data Source=(local)");

conn.Open();

 

SqlCommand comm=conn.CreateCommand();

comm.CommandText="insert into Images(Image, contentType) values(@image, @contentType)";

comm.CommandType=CommandType.Text;

 

comm.Parameters.Add("@image", SqlDbType.Image).Value=content;

comm.Parameters.Add("@contentType", SqlDbType.NVarChar).Value=

GetContentType(new FileInfo(filePath.Text).Extension.Remove(0,1));

 

if(comm.ExecuteNonQuery()==1)

{

MessageBox.Show("Successfully insert image into database!");

}

else

{

MessageBox.Show("Failed to insert image into database");

}

 

conn.Close();

 

B、将数据库中的图片读出来的代码片断:(完整DEMO程序见附录二)

try{

SqlConnection conn=new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DatabaseImage;Data Source=(local)");

conn.Open();

 

SqlCommand comm=conn.CreateCommand();

comm.CommandText="select * from Images where id=@id";

comm.CommandType=CommandType.Text;

 

comm.Parameters.Add("@id", SqlDbType.BigInt).Value=int.Parse(Request["id"]);

 

SqlDataReader reader=comm.ExecuteReader();

while(reader.Read())

{

Response.ContentType=reader["contentType"].ToString();

Response.BinaryWrite((byte[])reader["Image"]);

}

Response.End();

 

conn.Close();

}

catch

{

Response.End();

}

这段代码可置于Page_Load事件中,数据图片要注意的两点是:

一、 设置正确的ContentType(http中的content-type),图片的content-type格式一般为image/*,如jpeg为image/jpeg,bmp为image/bmp等等。

二、 仅仅输出一张图片二进制流,asp.net 中Page_Load事件先于页面输出被触发,因此图片的输出可以在此事件中进行,直接操作Reponse对象,避免输出与图片无关的而外信息(额外的第二张图片或者文字)。图片的二进制流输出后及时使用Response.End()方法结束http响应,避免页面中的额外信息被asp.net的引擎默认输出到客户端。

 

希望此文能够起到抛砖引玉的作用!^_^

 

附录一:

MainForm.cs

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.IO;

using System.Windows.Forms;

 

namespace InsertImageToDatabase

{

public class MainForm : System.Windows.Forms.Form

{

private System.Windows.Forms.OpenFileDialog openFileDlg;

private System.Windows.Forms.TextBox filePath;

private System.Windows.Forms.Button browseButton;

private System.Windows.Forms.Button insertButton;

/// <summary>

/// Required designer variable.

/// </summary>

private System.ComponentModel.Container components = null;

 

public MainForm()

{

//

// Required for Windows Form Designer support

//

InitializeComponent();

 

//

// TODO: Add any constructor code after InitializeComponent call

//

}

 

/// <summary>

/// Clean up any resources being used.

/// </summary>

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

 

#region Windows Form Designer generated code

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.openFileDlg = new System.Windows.Forms.OpenFileDialog();

this.filePath = new System.Windows.Forms.TextBox();

this.browseButton = new System.Windows.Forms.Button();

this.insertButton = new System.Windows.Forms.Button();

this.SuspendLayout();

//

// openFileDlg

//

this.openFileDlg.DefaultExt = "*.jpg;*.gif;*.bmp;*.png";

this.openFileDlg.Filter = "Image Files|*.jpg;*.gif;*.bmp;*.png|All Files|*.*";

//

// filePath

//

this.filePath.Location = new System.Drawing.Point(16, 16);

this.filePath.Name = "filePath";

this.filePath.ReadOnly = true;

this.filePath.Size = new System.Drawing.Size(168, 20);

this.filePath.TabIndex = 0;

this.filePath.Text = "";

//

// browseButton

//

this.browseButton.Location = new System.Drawing.Point(200, 16);

this.browseButton.Name = "browseButton";

this.browseButton.TabIndex = 1;

this.browseButton.Text = "&Browse";

this.browseButton.Click += new System.EventHandler(this.browseButton_Click);

//

// insertButton

//

this.insertButton.Enabled = false;

this.insertButton.Location = new System.Drawing.Point(200, 56);

this.insertButton.Name = "insertButton";

this.insertButton.TabIndex = 2;

this.insertButton.Text = "&Insert";

this.insertButton.Click += new System.EventHandler(this.insertButton_Click);

//

// MainForm

//

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

this.ClientSize = new System.Drawing.Size(292, 273);

this.Controls.Add(this.insertButton);

this.Controls.Add(this.browseButton);

this.Controls.Add(this.filePath);

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;

this.MaximizeBox = false;

this.Name = "MainForm";

this.Text = "Insert Image to Database";

this.ResumeLayout(false);

 

}

#endregion

 

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main()

{

Application.Run(new MainForm());

}

 

private void browseButton_Click(object sender, System.EventArgs e)

{

if(openFileDlg.ShowDialog()==DialogResult.OK)

{

filePath.Text=openFileDlg.FileName;

insertButton.Enabled=true;

}

}

 

private void insertButton_Click(object sender, System.EventArgs e)

{

FileStream fs=File.OpenRead(filePath.Text);

byte[] content=new byte[fs.Length];

fs.Read(content, 0,content.Length);

fs.Close();

 

SqlConnection conn=new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DatabaseImage;Data Source=(local)");

conn.Open();

 

SqlCommand comm=conn.CreateCommand();

comm.CommandText="insert into Images(Image, contentType) values(@image, @contentType)";

comm.CommandType=CommandType.Text;

 

SqlParameter param=comm.Parameters.Add("@image", SqlDbType.Image);

param.Value=content;

comm.Parameters.Add("@contentType", SqlDbType.NVarChar).Value=

GetContentType(new FileInfo(filePath.Text).Extension.Remove(0,1));

 

if(comm.ExecuteNonQuery()==1)

{

MessageBox.Show("Successfully insert image into database!");

}

else

{

MessageBox.Show("Failed to insert image into database");

}

 

conn.Close();

}

 

private string GetContentType(string extension)

{

string type="jpeg";

if(extension=="jpg")

{

type="jpeg";

}else

{

type=extension;

}

return "image/"+type;

}

}

}

 

附录二:

ReadImage.aspx

<%@ Page language="c#" Codebehind="ReadImage.aspx.cs" AutoEventWireup="false" Inherits="ReadImage.ReadImage"%>

ReadImage.aspx.cs

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

 

namespace ReadImage

{

/// <summary>

/// Summary description for ReadImage.

/// </summary>

public class ReadImage : System.Web.UI.Page

{

private void Page_Load(object sender, System.EventArgs e)

{

try{

SqlConnection conn=new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DatabaseImage;Data Source=(local)");

conn.Open();

 

SqlCommand comm=conn.CreateCommand();

comm.CommandText="select * from Images where id>@id";

comm.CommandType=CommandType.Text;

 

comm.Parameters.Add("@id", SqlDbType.BigInt).Value=int.Parse(Request["id"]);

 

SqlDataReader reader=comm.ExecuteReader();

while(reader.Read())

{

Response.ContentType=reader["contentType"].ToString();

Response.BinaryWrite((byte[])reader["Image"]);

}

Response.Write("aaaaaa");

Response.End();

 

conn.Close();

}

catch

{

Response.End();

}

}

 

#region Web Form Designer generated code

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: This call is required by the ASP.NET Web Form Designer.

//

InitializeComponent();

base.OnInit(e);

}

 

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.Load += new System.EventHandler(this.Page_Load);

 

}

#endregion

}

}

 
00000000000000000000000000000000000000000000000000000000000000000000000000000000000
-------Web界面Img-----------
<img   src= "Handler.ashx?PhotoID= <%#   Eval( "PhotoID ")   % >&Size=S "   class= "photo_198 "   style= "border:4px   solid   white "   alt= &apos;缩略图,照片编号   <%#   Eval( "PhotoID ")   % > &apos;   / >

--------Handler.ashx---------
<%@   WebHandler   Language= "C# "   Class= "Handler "   % >

using   System;
using   System.IO;
using   System.Web;

public   class   Handler   :   IHttpHandler   {

public   bool   IsReusable   {
get   {
return   true;
}
}

public   void   ProcessRequest   (HttpContext   context)   {
//   设置响应设置
context.Response.ContentType   =   "image/jpeg ";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.BufferOutput   =   false;
//   设置   Size   参数
PhotoSize   size;
switch   (context.Request.QueryString[ "Size "])   {
case   "S ":
size   =   PhotoSize.Small;
break;
case   "M ":
size   =   PhotoSize.Medium;
break;
case   "L ":
size   =   PhotoSize.Large;
break;
default:
size   =   PhotoSize.Original;
break;
}  
//   设置   PhotoID   参数
Int32   id   =   -1;
Stream   stream   =   null;
if   (context.Request.QueryString[ "PhotoID "]   !=   null   &&   context.Request.QueryString[ "PhotoID "]   !=   " ")   {
id   =   Convert.ToInt32(context.Request.QueryString[ "PhotoID "]);
stream   =   PhotoManager.GetPhoto(id,   size);
}   else   {
id   =   Convert.ToInt32(context.Request.QueryString[ "AlbumID "]);
stream   =   PhotoManager.GetFirstPhoto(id,   size);
}
//   从数据库获取照片,如果未返回照片,将获取默认的“placeholder”照片
if   (stream   ==   null)   stream   =   PhotoManager.GetPhoto(size);
//   将图像流写入响应流中
const   int   buffersize   =   1024   *   16;
byte[]   buffer   =   new   byte[buffersize];
int   count   =   stream.Read(buffer,   0,   buffersize);
while   (count   >   0)   {
context.Response.OutputStream.Write(buffer,   0,   count);
count   =   stream.Read(buffer,   0,   buffersize);
}
}

}

 

原创粉丝点击