|
在《从access到asp.net》我给出了一个上传图片的函数,但是在网站运行的时候,会发现,有时我们使用列表,需要的是小图片,有时察看明细,需要的是大图片,而大图片在小图片框中会变形,不好看,而有时自动图片框又因为图片太大被涨得太大,所以最好有两种图片,分别用在不同的地方。好在asp.net2.0中为我们提供了一个image的类,可以有很多功能,包括生成缩略图,制作水印等功能。(水印的制作等有空我再贴出来)
首先我们建立一个图片上传的类:命名为:uploadimg
Public Class uploadimg
Public file As Object '输入图片的文件框
Public Maximg As String '大图片的存放地址
Public Minimg As String '小图片的存放地址
Public Msglab As Label '错误报告的标签框
Public x As Integer '缩略图的宽
Public y As Integer '缩略图的高
Dim s1 As String '图片的格式
Dim s2() As String '原图片的地址,用"\"分割为数组
Sub upimg()
If file.PostedFile.ContentLength > 0 Then
Dim fileSize As Integer = file.PostedFile.ContentLength
If fileSize < 200000 Then
s2 = file.PostedFile.FileName.Split("\")
s1 = Right(s2(s2.Length - 1), 4)
If s1 = ".jpg" Or s1 = ".JPG" Or s1 = ".GIF" Or s1 = ".gif" Or s1 = ".bmp" Or s1 = ".BMP" Then
Dim s3 As String '上传后图片的名称,时间+毫秒为名字
s3 = Format(Now(), "yyyyMMddHHmmss") & Trim(Str(DateTime.Now.Millisecond)) & s1
file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(".") & "\images\" & s3) '保存
Maximg = "~\images\" & s3
minup()
Else
Msglab.Text = "图片的格式不符合要求"
End If
Else
Msglab.Text = "图片大小超过了200K"
End If
Else
Msglab.Text = "请选择图片"
End If
End Sub
'缩略图上传
Sub minup()
Dim simg As System.Drawing.Image '声明一个image对象
Dim H As Integer '图像高度
Dim W As Integer '图像宽度
simg = System.Drawing.Image.FromFile(file.PostedFile.FileName) '实例化一个image对象
H = simg.Height
W = simg.Width
If H > W Then
y = y
x = x * (W / H)
Else
x = x
y = y * (H / W)
End If
Dim callback As GetThumbnailImageAbort
simg = simg.GetThumbnailImage(x, y, callback, IntPtr.Zero) '生成缩略图
Dim s4 As String
s4 = Format(Now(), "yyyyMMddHHmmss") & Trim(Str(DateTime.Now.Millisecond)) & "s" & s1
simg.Save(HttpContext.Current.Server.MapPath(".") & "\images\" & s4) '保存在指定文件夹
Minimg = "~\images\" & s4
End Sub
End Class
好了,让我们来测试一下:建立一个web窗体;添加一个浏览文本框,一个标签框,一个命令按钮,两个图片框
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>imgupload测试页</title>
</head>
<body>
<form id="form1" runat="server">
<input id="File1" type="file" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<aspabel ID="Label1" runat="server"></aspabel><br />
<asp:Image ID="Image1" runat="server" /><br />
<asp:Image ID="Image2" runat="server" />
</form>
</body>
</html>
然后再后台代码写上调用的代码:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim meimg As New uploadimg
meimg.file = File1
meimg.Msglab = Me.Label1
meimg.x = 100
meimg.y = 100
|
|