用ASP.NET创建和保存图片到数据库 By Max Cappellari MCSD 译 涟漪勇 当我们开发电子商务类型的网站,我们一定会遇将每一个产品的产品图片(大图片和所略图)存储到数据库的问题,每一个产品的同一个图片上传两种大小不同的尺寸似乎是件不可能的事情,我建了一个方程来实现:创建一个特殊尺寸的所略图和存储两个图片(原始的和所略的)到SQL数据库。另外我建了一个Class用于取出图片和显示图片在网页上。 The SQL Database SQL数据库 首先,让我讲讲一些关于产品数据库的信息。图片可以存储在用Image类型的字段的数据库中。另外,我们还需要一个varchar 的字段去存储图片的类型(GIF, JPG, BMP等等),这是很重要的对于显示图片从数据库中找到相应的数据。我建了一个Product_Image 表,Product_Image 表涉及到商品表(Product)的ProdID ,但是这一点并不是很重要的,下面是Product_Image 表的数据结构。 CREATE TABLE [Product_image] ( [imageID] [int] IDENTITY (1, 1) NOT NULL , [ProdID] [int] NOT NULL , [LG_img_name] [varchar] (50), [LG_img_data] [image] NULL , [LG_img_contenttype] [varchar] (50) , [SM_img_name][varchar] (50), [SM_img_data] [image] NULL , [SM_img_contenttype] [varchar] (50), )
你可以看到我存储两个图片为每一个产品(LG_img and SM_img),每一个图片有三的字段(name, data, and contenttype).我还建了一个存储过程,insert_Product_image,去完成插入图片的数据库的功能。 CREATE PROCEDURE [insert_Product_image] ( @ProdID [int], @img_name [varchar](50), @img_data [image], @img_contenttype [varchar](50), @img_name2 [varchar](50), @img_data2 [image], @img_contenttype2 [varchar](50) ) AS begin transaction delete from Product_image where ProdID = @ProdID INSERT INTO [Product_image] ( [ProdID], [LG_img_name], [LG_img_data], [LG_img_contenttype], [SM_img_name], [SM_img_data], [SM_img_contenttype] ) VALUES ( @ProdID, @img_name, @img_data, @img_contenttype, @img_name2, @img_data2, @img_contenttype2) commit transaction
The Input Form — SaveImage.aspx 输入窗体— SaveImage.aspx 我设计了一个简单的输入窗体去得到图片和产品ID由用户输入,文件的名字是SaveImage.aspx: <%@ Page Language= "vb"AutoEventWireup="false"Codebehind= "SaveImage.aspx.vb" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title>New Product Image</title> </HEAD> <body> <form id="Form1" method= "post" runat= "server" enctype= "multipart/form-data"> Prod ID: <asp:textbox id="txtProdID"></asp:textbox><br> Image:<INPUT id= "fUpLoadImage"type="file"runat="server"><br> <INPUT id= "btnSave" type="button" value="Save Image" name="btnSave" runat="server"> </form> </body> </html>
请注意enctype="multipart/form-data代码在<form>标记内的,这是必须的当一个binary数据(图片)传送到服务器端。
The Code Behind — SaveImage.aspx.vb 后置代码— SaveImage.aspx.vb 下面的后置代码SaveImage.aspx功能是返回数据从窗体并且存储到数据库,有三个方程在这里SaveImageToDB, createThumnail, 和NewThumbSize: Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.HtmlControls Imports System.IO Imports System.Drawing Imports System.Drawing.Imaging Public Class SaveImage Inherits System.Web.UI.Page Protected WithEvents fUpLoadImage As System.Web.UI.HtmlControls.HtmlInputFile Protected WithEvents btnSave As System.Web.UI.HtmlControls.HtmlInputButton Protected WithEvents txtProdID As System.Web.UI.WebControls.TextBox Private Sub btnSave_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.ServerClick Dim ProdID As Int32 ProdID =CType(txtProdID.Text,Int32) 'Save Image SaveImageToDB(ProdID) Response.write("Image Saved") End Sub Private Function SaveImageToDB(ByVal ProdID As Int32) As Int32 Dim imgName As String Dim imgContentType As String Dim imgLen As Int32 Dim imgbin() As Byte Dim imgName2 As String Dim imgContentType2 As String Dim imgbin2() As Byte 'check if file is empty If Not fUpLoadImage.PostedFile Is Nothing Then If fUpLoadImage.PostedFile.FileName.Trim.Length > 0 And fUpLoadImage. PostedFile.ContentLength > 0 Then Dim imgStream As Stream = fUpLoadImage.PostedFile.InputStream() imgLen = fUpLoadImage.PostedFile.ContentLength imgContentType = fUpLoadImage.PostedFile.ContentType imgName=fUpLoadImage.PostedFile.FileName.Substring (fUpLoadImage.PostedFile.FileName.LastIndexOf("\") + 1) Dim imgBinaryData(imgLen) As Byte Dim n As Int32 = imgStream.Read(imgBinaryData, 0, imgLen) imgbin = imgBinaryData 'Create Thumbnail imgName2 = "Thumb_" & imgName imgContentType2 = imgContentType imgbin2 = createThumnail(imgStream, 145, 145) 'Save images to Database Dim SqlConnection1 As New System.Data.SqlClient.SqlConnection SqlConnection1.ConnectionString="datasource=MyServer; initialcatalog=MyDatabase;password=myPassword;persist security info=True;user id=myUserID;packet size=4096" Dim myCommand As New SqlClient.SqlCommand() myCommand.Connection = SqlConnection1 myCommand.CommandType = CommandType.StoredProcedure myCommand.CommandText = "insert_Product_image" Dim Param0 As New SqlClient.SqlParameter("@ProdID", SqlDbType.Int) Dim Param1 As New SqlClient.SqlParameter("@img_name", SqlDbType.VarChar, 50) Dim Param2 As New SqlClient.SqlParameter("@img_data", SqlDbType.Image) Dim Param3 As New SqlClient.SqlParameter("@img_contenttype", SqlDbType.VarChar, 50) Dim Param4 As New SqlClient.SqlParameter("@img_name2", SqlDbType.VarChar, 50) Dim Param5 As New SqlClient.SqlParameter("@img_data2", SqlDbType.Image) Dim Param6 As New SqlClient.SqlParameter("@img_contenttype2", SqlDbType.VarChar, 50) Param0.Value = ProdID Param1.Value = imgName Param2.Value = imgbin Param3.Value = imgContentType Param4.Value = imgName2 Param5.Value = imgbin2 Param6.Value = imgContentType2 myCommand.Parameters.Add(Param0) myCommand.Parameters.Add(Param1) myCommand.Parameters.Add(Param2) myCommand.Parameters.Add(Param3) myCommand.Parameters.Add(Param4) myCommand.Parameters.Add(Param5) myCommand.Parameters.Add(Param6) SqlConnection1.Open() SaveImageToDB = myCommand.ExecuteNonQuery() SqlConnection1.Close() End If End If End Function 'This function creates the Thumbnail image and returns the image created in Byte() format Private Function createThumnail(ByVal ImageStream As Stream, ByVal tWidth As Double, ByVal tHeight As Double) As Byte() Dim g As System.Drawing.Image =System.Drawing.Image.FromStream(ImageStream) Dim thumbSize As New Size() thumbSize =NewthumbSize(g.Width, g.Height, tWidth, tHeight) Dim imgOutput As New Bitmap(g, thumbSize.Width, thumbSize.Height) Dim imgStream As New MemoryStream() Dim thisFormat = g.RawFormat imgOutput.Save(imgStream, thisFormat) Dim imgbin(imgStream.Length) As Byte imgStream.Position = 0 Dim n As Int32 = imgStream.Read(imgbin, 0, imgbin.Length) g.Dispose() imgOutput.Dispose() Return imgbin End Function Function NewthumbSize(ByVal currentwidth As Double, ByVal currentheight As Double, ByVal newWidth As Double, ByVal newHeight As Double) ' Calculate the Size of the New image Dim tempMultiplier As Double If currentheight > currentwidth Then ' portrait tempMultiplier = newHeight / currentheight Else tempMultiplier = newWidth / currentwidth End If Dim NewSize As New Size(CInt(currentwidth * tempMultiplier), CInt(currentheight * tempMultiplier)) Return NewSize End Function End Class
SaveImageToDB调用存储过程insert_Product_image去完成插入图片到数据库,createThumnail创建一个新的基于宽Width and 高Height 传递给方程. 在我的例子中,我用一个尺寸为145x145象素的图片作为所略图的大小,方程NewThumbSize 将基于原始的图片的比例进行调整新的图片并且返回适当的尺寸。 如果有任何问题可以发送到作者信箱:maxcappellari@yahoo.com.
|