用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 表的数据结构。

None.gif CREATE   TABLE   [ Product_image ]  ( 
None.gif    
[ imageID ]   [ int ]   IDENTITY  ( 1 1 NOT   NULL  ,
None.gif    
[ ProdID ]   [ int ]   NOT   NULL  , 
None.gif    
[ LG_img_name ]   [ varchar ]  ( 50 ), 
None.gif    
[ LG_img_data ]   [ image ]   NULL  , 
None.gif    
[ LG_img_contenttype ]   [ varchar ]  ( 50 ) ,
None.gif    
[ SM_img_name ][ varchar ]  ( 50 ), 
None.gif    
[ SM_img_data ]   [ image ]   NULL  , 
None.gif    
[ SM_img_contenttype ]   [ varchar ]  ( 50 ), ) 
None.gif

 

 

你可以看到我存储两个图片为每一个产品(LG_img and SM_img),每一个图片有三的字段(name, data, and contenttype).我还建了一个存储过程,insert_Product_image,去完成插入图片的数据库的功能。

None.gif CREATE   PROCEDURE   [ insert_Product_image ]  ( 
None.gif@ProdID 
[ int ]
None.gif@img_name 
[ varchar ] ( 50 ),
None.gif@img_data 
[ image ]
None.gif@img_contenttype 
[ varchar ] ( 50 ),
None.gif@img_name2 
[ varchar ] ( 50 ), 
None.gif@img_data2 
[ image ]
None.gif@img_contenttype2 
[ varchar ] ( 50 ) )
None.gif
AS  
None.gif
begin   transaction  
None.gif  
delete   from  Product_image  where  ProdID  =  @ProdID 
None.gif  
INSERT   INTO   [ Product_image ]  ( 
None.gif  
[ ProdID ]
None.gif  
[ LG_img_name ] ,
None.gif  
[ LG_img_data ]
None.gif  
[ LG_img_contenttype ] ,
None.gif  
[ SM_img_name ]
None.gif  
[ SM_img_data ]
None.gif  
[ SM_img_contenttype ]  )
None.gif
VALUES  ( 
None.gif  @ProdID, 
None.gif  @img_name, 
None.gif  @img_data, 
None.gif  @img_contenttype,
None.gif  @img_name2, 
None.gif  @img_data2, 
None.gif  @img_contenttype2)
None.gif
commit   transaction  
None.gif

 

 

The Input Form — SaveImage.aspx

输入窗体— SaveImage.aspx

我设计了一个简单的输入窗体去得到图片和产品ID由用户输入,文件的名字是SaveImage.aspx:

ExpandedBlockStart.gif ContractedBlock.gif <% dot.gif @ Page Language= "vb"AutoEventWireup="false"Codebehind=
ExpandedBlockEnd.gif
"SaveImage.aspx.vb" 
%>
None.gif
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
None.gif
< HTML >  
None.gif
< HEAD >
None.gif
< title > New Product Image </ title >  
None.gif
</ HEAD >  
None.gif
< body >  
None.gif
< form  id ="Form1"  method = "post"  runat = "server"  enctype = "multipart/form-data" >
None.gifProd ID: 
< asp:textbox  id ="txtProdID" ></ asp:textbox >< br >
None.gifImage:
< INPUT  id = "fUpLoadImage" type ="file" runat ="server" >< br >
None.gif
< INPUT  id = "btnSave"  type ="button"  value ="Save Image"  name ="btnSave"  runat ="server" >
None.gif
</ form >
None.gif
</ body >
None.gif
</ html >
None.gif

 

请注意enctype="multipart/form-data代码在<form>标记内的,这是必须的当一个binary数据(图片)传送到服务器端。

 

The Code Behind — SaveImage.aspx.vb

后置代码— SaveImage.aspx.vb

下面的后置代码SaveImage.aspx功能是返回数据从窗体并且存储到数据库,有三个方程在这里SaveImageToDB, createThumnail, 和NewThumbSize:

None.gif Imports  System.Web.UI
None.gif
Imports  System.Web.UI.WebControls
None.gif
Imports  System.Web.UI.HtmlControls
None.gif
Imports  System.IO
None.gif
Imports  System.Drawing
None.gif
Imports  System.Drawing.Imaging
None.gif
ExpandedBlockStart.gifContractedBlock.gif
Public   Class SaveImage Class SaveImage
InBlock.gif
Inherits System.Web.UI.Page
InBlock.gif
InBlock.gif
Protected WithEvents fUpLoadImage As System.Web.UI.HtmlControls.HtmlInputFile
InBlock.gif
Protected WithEvents btnSave As System.Web.UI.HtmlControls.HtmlInputButton
InBlock.gif
Protected WithEvents txtProdID As System.Web.UI.WebControls.TextBox
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
Private Sub btnSave_ServerClick()Sub btnSave_ServerClick(ByVal sender As System.ObjectByVal e As System.EventArgs)
InBlock.gif
Handles btnSave.ServerClick
InBlock.gif  
Dim ProdID As Int32
InBlock.gif  ProdID 
=CType(txtProdID.Text,Int32)
InBlock.gif  
'Save Image
InBlock.gif
  SaveImageToDB(ProdID)
InBlock.gif  Response.
write("Image Saved"
ExpandedSubBlockEnd.gif
End Sub

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
Private Function SaveImageToDB()Function SaveImageToDB(ByVal ProdID As Int32) As Int32
InBlock.gif 
Dim imgName As String
InBlock.gif 
Dim imgContentType As String
InBlock.gif 
Dim imgLen As Int32
InBlock.gif 
Dim imgbin() As Byte
InBlock.gif 
Dim imgName2 As String
InBlock.gif 
Dim imgContentType2 As String
InBlock.gif 
Dim imgbin2() As Byte
InBlock.gif 
'check if file is empty
InBlock.gif
 If Not fUpLoadImage.PostedFile Is Nothing Then
InBlock.gif  
If fUpLoadImage.PostedFile.FileName.Trim.Length > 0 And fUpLoadImage.
InBlock.gifPostedFile.ContentLength 
> 0 Then
InBlock.gif   
Dim imgStream As Stream = fUpLoadImage.PostedFile.InputStream()
InBlock.gif   imgLen 
= fUpLoadImage.PostedFile.ContentLength
InBlock.gif   imgContentType 
= fUpLoadImage.PostedFile.ContentType
InBlock.gif   imgName
=fUpLoadImage.PostedFile.FileName.Substring
InBlock.gif(fUpLoadImage.PostedFile.FileName.LastIndexOf(
"\"+ 1)
InBlock.gif   
Dim imgBinaryData(imgLen) As Byte
InBlock.gif   
Dim n As Int32 = imgStream.Read(imgBinaryData, 0, imgLen)
InBlock.gif   imgbin 
= imgBinaryData
InBlock.gif   
InBlock.gif   
'Create Thumbnail
InBlock.gif
   imgName2 = "Thumb_" & imgName
InBlock.gif   imgContentType2 
= imgContentType
InBlock.gif   imgbin2 
= createThumnail(imgStream, 145145)
InBlock.gif
InBlock.gif   
'Save images to Database
InBlock.gif
   Dim SqlConnection1 As New System.Data.SqlClient.SqlConnection
InBlock.gif  SqlConnection1.ConnectionString
="datasource=MyServer;
InBlock.gif
initialcatalog=MyDatabase;password=myPassword;persist security
InBlock.gifinfo
=True;user id=myUserID;packet size=4096"
InBlock.gif
   Dim myCommand As New SqlClient.SqlCommand()
InBlock.gif   myCommand.Connection 
= SqlConnection1
InBlock.gif   myCommand.CommandType 
= CommandType.StoredProcedure
InBlock.gif   myCommand.CommandText 
= "insert_Product_image"
InBlock.gif

InBlock.gif
   Dim Param0 As New SqlClient.SqlParameter("@ProdID", SqlDbType.Int)
InBlock.gif   
Dim Param1 As New SqlClient.SqlParameter("@img_name", SqlDbType.VarChar, 50)
InBlock.gif   
Dim Param2 As New SqlClient.SqlParameter("@img_data", SqlDbType.Image)
InBlock.gif   
Dim Param3 As New SqlClient.SqlParameter("@img_contenttype", SqlDbType.VarChar, 50)
InBlock.gif   
Dim Param4 As New SqlClient.SqlParameter("@img_name2", SqlDbType.VarChar, 50)
InBlock.gif   
Dim Param5 As New SqlClient.SqlParameter("@img_data2", SqlDbType.Image)
InBlock.gif   
Dim Param6 As New SqlClient.SqlParameter("@img_contenttype2", SqlDbType.VarChar, 50)
InBlock.gif
InBlock.gif   Param0.Value 
= ProdID
InBlock.gif   Param1.Value 
= imgName
InBlock.gif   Param2.Value 
= imgbin
InBlock.gif   Param3.Value 
= imgContentType
InBlock.gif   Param4.Value 
= imgName2
InBlock.gif   Param5.Value 
= imgbin2
InBlock.gif   Param6.Value 
= imgContentType2
InBlock.gif
InBlock.gif   myCommand.Parameters.Add(Param0)
InBlock.gif   myCommand.Parameters.Add(Param1)
InBlock.gif   myCommand.Parameters.Add(Param2)
InBlock.gif   myCommand.Parameters.Add(Param3)
InBlock.gif   myCommand.Parameters.Add(Param4)
InBlock.gif   myCommand.Parameters.Add(Param5)
InBlock.gif   myCommand.Parameters.Add(Param6)
InBlock.gif
InBlock.gif   SqlConnection1.Open()
InBlock.gif   SaveImageToDB 
= myCommand.ExecuteNonQuery()
InBlock.gif   SqlConnection1.Close()
InBlock.gif
InBlock.gif  
End If
InBlock.gif 
End If
ExpandedSubBlockEnd.gif
End Function

InBlock.gif
InBlock.gif
InBlock.gif
'This function creates the Thumbnail image and returns the
InBlock.gif
image created in Byte() format
ExpandedSubBlockStart.gifContractedSubBlock.gif
Private Function createThumnail()Function createThumnail(ByVal ImageStream As Stream,
InBlock.gif
ByVal tWidth As DoubleByVal tHeight As DoubleAs Byte()
InBlock.gif  
Dim g As System.Drawing.Image =System.Drawing.Image.FromStream(ImageStream)
InBlock.gif  
Dim thumbSize As New Size()
InBlock.gif  thumbSize 
=NewthumbSize(g.Width, g.Height, tWidth, tHeight)
InBlock.gif  
Dim imgOutput As New Bitmap(g, thumbSize.Width, thumbSize.Height)
InBlock.gif  
Dim imgStream As New MemoryStream()
InBlock.gif  
Dim thisFormat = g.RawFormat
InBlock.gif  imgOutput.Save(imgStream, thisFormat)
InBlock.gif  
Dim imgbin(imgStream.Length) As Byte
InBlock.gif  imgStream.Position 
= 0
InBlock.gif  
Dim n As Int32 = imgStream.Read(imgbin, 0, imgbin.Length)
InBlock.gif  g.Dispose()
InBlock.gif  imgOutput.Dispose()
InBlock.gif  
Return imgbin
ExpandedSubBlockEnd.gif
End Function

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
Function NewthumbSize()Function NewthumbSize(ByVal currentwidth As DoubleByVal
InBlock.gifcurrentheight 
As DoubleByVal newWidth As DoubleByVal newHeight As Double)
InBlock.gif  
' Calculate the Size of the New image 
InBlock.gif
  Dim tempMultiplier As Double
InBlock.gif
InBlock.gif  
If currentheight > currentwidth Then ' portrait 
InBlock.gif
   tempMultiplier = newHeight / currentheight
InBlock.gif  
Else
InBlock.gif   tempMultiplier 
= newWidth / currentwidth
InBlock.gif  
End If
InBlock.gif
InBlock.gif  
Dim NewSize As New Size(CInt(currentwidth * tempMultiplier),
InBlock.gif
CInt(currentheight * tempMultiplier)) 
InBlock.gif  
Return NewSize
ExpandedSubBlockEnd.gif
End Function

ExpandedBlockEnd.gif
End Class

None.gif

 

SaveImageToDB调用存储过程insert_Product_image去完成插入图片到数据库,createThumnail创建一个新的基于宽Width and 高Height 传递给方程. 在我的例子中,我用一个尺寸为145x145象素的图片作为所略图的大小,方程NewThumbSize 将基于原始的图片的比例进行调整新的图片并且返回适当的尺寸。

如果有任何问题可以发送到作者信箱:maxcappellari@yahoo.com.
或者到涟漪勇的信箱:rippleyong@hotmail.com

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值