ASP.NET中让图片以二进制的形式存储在数据库中

    建立保存图片的表的SQL语句:

USE [niunantest]
GO
/****** 对象:  Table [dbo].[picdata]    脚本日期: 03/30/2010 14:51:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[picdata](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[content] [image] NULL,
	[createdate] [datetime] NOT NULL CONSTRAINT [DF_picdata_createdate]  DEFAULT (getdate()),
 CONSTRAINT [PK_picdata] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

    下面是保存图片到数据库中的代码片段:

        int len = fu.PostedFile.ContentLength;  // 图片大小
        byte[] pic = new byte[len];  // 创建一个字节数组,大小为图片的大小,数据库中就存储这个东西
        fu.PostedFile.InputStream.Read(pic, 0, len); // 把上传控件中的文件用二进制读取存到pic字节数组中
        //   插入图片到数据库中     
        SqlConnection connection = new
        SqlConnection(@"server=.\sqlexpress;database=niunantest;uid=sa;pwd=123456");
        try
        {
            connection.Open();
            SqlCommand cmd = new SqlCommand("insert   into   picdata   "
            + "([content])   values   (@pic)", connection);
            cmd.Parameters.Add("@pic", pic);
            cmd.ExecuteNonQuery();
            Label1.Text = "图片插入数据库成功!";

            Image1.ImageUrl = "getpic.ashx?t=" + DateTime.Now.Ticks;  // 显示刚刚插入数据库的图片
        }
        finally
        {
            connection.Close();
        } 

    下面是从数据库中取出图片的代码片段:

        MemoryStream stream = new MemoryStream();
        SqlConnection connection = new
        SqlConnection(@"server=.\sqlexpress;database=niunantest;uid=sa;pwd=123456");
        try
        {
            connection.Open();
            SqlCommand command = new
            SqlCommand("select top 1  [content]   from   picdata order by id desc", connection);
            byte[] image = (byte[])command.ExecuteScalar();
            stream.Write(image, 0, image.Length);
            Bitmap bitmap = new Bitmap(stream);
            context.Response.ContentType = "image/jpeg";
            bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        finally
        {
            connection.Close();
            stream.Close();
        } 

    其实也就是通过流把图片搞成字节数组再存到数据库中,然后再从数据库中读取字节数组出 来,再通过字节数组创建流,再通过流把图像输出出来,发现你存到数据库中的是gif图像的话再取出来是可以把他转为jpg的图像的,因为在取出图像的时候 我们设置他的ContentType是image/jpeg了。

    转自牛腩

猜你喜欢

转载自zh3361264.iteye.com/blog/1637218