<script language="VB" runat="server"> Sub UploadFile(sender As Object, e As EventArgs)If FileUp.PostedFile.ContentLength = 0 Then FileInfo.Visible = False Exit Sub Else FileInfo.Visible = True FDisplay1.Visible = True End IfFSize.Text ="上传文件大小"+ CStr(FileUp.PostedFile.ContentLength/1024)+"KB" FName.Text = "已上传文件名:"+FileUp.PostedFile.FileName+"<br>"+FName.Text'写入数据库 on error resume next dim myconn as sqlconnection dim mycomm as sqlcommand dim sql as string dim id as integer Dim image,anewimage As System.Drawing.Image dim width,height,newwidth,newheight as integer Dim callb As System.Drawing.Image.GetThumbnailImageAbort myConn=New sqlconnection(ConfigurationSettings.AppSettings("数据库")) myconn.open() sql="insert into picture (姓名,班级,介绍,属性) values ('"&request.cookies("dgxyl").values("dgxylname")&"','"&request.cookies("dgxyl").values("dgxylbj")&"','"&trim(request("TextBox1"))&"','"&request("r1")&"')" Mycomm=New sqlcommand(sql,myconn) mycomm.executenonquery() myconn.close()Dim myCommand As New SqlCommand("select top 1 id from picture order by id desc", myConn) myCommand.Connection.Open() Dim myReader As SqlDataReader=mycommand.executereader() if myReader.Read() then id=myReader("id") end if myconn.close() '保存图片 FileUp.PostedFile.SaveAs( Server.MapPath("\classpic\")&cstr(id)&".jpg" ) '生成缩略图 image=System.Drawing.Image.FromFile(Server.MapPath("/classpic/"+cstr(id)+".jpg")) width=image.Width height=image.height if width>height then newwidth=250 newheight=image.height/image.Width*newwidth else newheight=250 newwidth=image.Width/image.height*newheight end if response.write("id="+cstr(id)+"width="+cstr(Width)+";height="+cstr(height)+" ") response.write("newwidth="+cstr(newwidth)+";newheight="+cstr(newheight)+"<br>")aNewImage=image.GetThumbnailImage(newwidth,newheight,callb,new System.IntPtr()) aNewImage.Save(Server.MapPath("/smallpic/"+cstr(id)+".jpg")) image.Dispose() Dim FileSplit() As String = Split( FileUp.PostedFile.FileName, "\" ) Dim FileName As String = FileSplit(FileSplit.Length-1) Dim Exts() As String = Split( FileName, "." ) Dim Ext As String = LCase(Exts(Exts.Length-1))FDisplay.Text = "<A Target='_blank' HREF='/classpic/"&cstr(id)&".jpg"& "'>查看上传文件</A>" FDisplay1.text="<a href='/picture/default.asp?bj="&cstr(request.cookies("dgxyl").values("dgxylbj"))&"'>返回</a>" End Sub </script> <SCRIPT language=JavaScript> <!-- var requestsubmitted=false; function guestbook_Validator(theForm) { //检查是否从新提交 if (requestsubmitted==true){ alert("你已经提交了留言,请等待服务器应答!"); return(false); } requestsubmitted=true;return (true); } //--> </SCRIPT>
生成高清晰缩略图:老外的办法:But the problem is: when writing the image with the changed or new description the picture part becomes recompressed. You can notice this from the file size; you add information to the file and the file size decreases. When you repeat changing the description, the image become more and more poor, because jpg is a lossy compression. So how do you load and save an jpg or exif file without recompressing the bitmap? The trick is to rotate the picture by 90 degrees. In this case the framework supplies a lossless rewriting of a jpeg file: private static ImageCodecInfo GetEncoderInfo(String mimeType) { int j; ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for(j = 0; j < encoders.Length; ++j) { if(encoders[j].MimeType == mimeType) return encoders[j]; } return null; }private void WriteNewDescriptionInImage(string Filename,string NewDescription) { Image Pic; PropertyItem[] PropertyItems; byte[] bDescription=new Byte[NewDescription.Length]; int i; string FilenameTemp; Encoder Enc=Encoder.Transformation; EncoderParameters EncParms=new EncoderParameters(1); EncoderParameter EncParm; ImageCodecInfo CodecInfo=GetEncoderInfo("image/jpeg");// copy description into byte array for (i=0;i<NewDescription.Length;i++) bDescription[i]=(byte)NewDescription[i];// load the image to change Pic=Image.FromFile(Filename);// put the new description into the right property item PropertyItems=Pic.PropertyItems; PropertyItems[0].Id=0x010e; // 0x010e as specified in EXIF standard PropertyItems[0].Type=2; PropertyItems[0].Len=NewDescription.Length; PropertyItems[0].Value=bDescription; Pic.SetPropertyItem(PropertyItems[0]);// we cannot store in the same image, so use a temporary image instead FilenameTemp=Filename+".temp";// for lossless rewriting must rotate the image by 90 degrees! EncParm=new EncoderParameter(Enc,(long)EncoderValue.TransformRotate90); EncParms.Param[0]=EncParm;// now write the rotated image with new description Pic.Save(FilenameTemp,CodecInfo,EncParms);// for computers with low memory and large pictures: release memory now Pic.Dispose(); Pic=null; GC.Collect();// delete the original file, will be replaced later System.IO.File.Delete(Filename); // now must rotate back the written picture Pic=Image.FromFile(FilenameTemp); EncParm=new EncoderParameter(Enc,(long)EncoderValue.TransformRotate270); EncParms.Param[0]=EncParm; Pic.Save(Filename,CodecInfo,EncParms);// release memory now Pic.Dispose(); Pic=null; GC.Collect();// delete the temporary picture System.IO.File.Delete(FilenameTemp); }
When saving to JPEG images, you can also control the compression ratio of the algorithm. You must use a different overload of the Save method:public void Save( string filename, ImageCodecInfo encoder, EncoderParameters encoderParams );The first step is to get the ImageCodecInfo structure for the JPEG image. The GDI+ interface provides no direct method to get this object. You must resort to a little trick—enumerate all the image encoders and check their MIME type properties against the JPEG MIME type string (image/jpeg). The ImageCodecInfo structure contains information inherent in the encoding and decoding of the image.The EncoderParameters argument represents an array of encoding parameters. Each element of the array is an EncoderParameter type. Possible parameters are listed as members of the static class Encoder. For example, the parameter Compression lets you choose a compression engine for TIFF images. The Quality parameter lets you choose the desired quality of the JPEG compression. This code compresses a JPEG with a 40:1 ratio: // Set the quality to 40 (must be a long) Encoder qualityEncoder = Encoder.Quality; EncoderParameter ratio = new EncoderParameter(qualityEncoder, 40L); // Add the quality parameter to the list codecParams = new EncoderParameters(1); codecParams.Param[0] = ratio; // Save to JPG bmp.Save(fileName, jpegCodecInfo, codecParams);Hope this is useful to others!
如果图片不符合要求,不能上传,否则上传图片,上传以后对图片按系统日期动态命名,保留路径到数据库里。private void Button1_Click(object sender, System.EventArgs e)
{
if(File1.PostedFile.ContentType.ToUpper().IndexOf("IMAGE")>-1)
{
System.Drawing.Image img= System.Drawing.Image.FromStream(File1.PostedFile.InputStream);
int Width = img.Width;
int Height = img.Height;
if(Width>200 || Height>100 || File1.PostedFile.ContentLength>1024*1024*2)
{
Response.Write("不符:Width="+Width.ToString() +"<br>Height="+Height.ToString()+"<br>Size="+(this.File1.PostedFile.ContentLength/1024).ToString("##,##0.00")+"K");
}
else
{
string sPath =Server.MapPath(System.DateTime.Now.ToString("yyy-MM-dd hh-mm-ss")+Session.SessionID+".jpg");
this.File1.PostedFile.SaveAs(sPath);
Response.Write("保存成功");
}
}
else
{
Response.Write("请选择图片文件!");
}
}
<script language="VB" runat="server">
Sub UploadFile(sender As Object, e As EventArgs)If FileUp.PostedFile.ContentLength = 0 Then
FileInfo.Visible = False
Exit Sub
Else
FileInfo.Visible = True
FDisplay1.Visible = True
End IfFSize.Text ="上传文件大小"+ CStr(FileUp.PostedFile.ContentLength/1024)+"KB"
FName.Text = "已上传文件名:"+FileUp.PostedFile.FileName+"<br>"+FName.Text'写入数据库
on error resume next
dim myconn as sqlconnection
dim mycomm as sqlcommand
dim sql as string
dim id as integer
Dim image,anewimage As System.Drawing.Image
dim width,height,newwidth,newheight as integer
Dim callb As System.Drawing.Image.GetThumbnailImageAbort
myConn=New sqlconnection(ConfigurationSettings.AppSettings("数据库"))
myconn.open()
sql="insert into picture (姓名,班级,介绍,属性) values ('"&request.cookies("dgxyl").values("dgxylname")&"','"&request.cookies("dgxyl").values("dgxylbj")&"','"&trim(request("TextBox1"))&"','"&request("r1")&"')"
Mycomm=New sqlcommand(sql,myconn)
mycomm.executenonquery()
myconn.close()Dim myCommand As New SqlCommand("select top 1 id from picture order by id desc", myConn)
myCommand.Connection.Open()
Dim myReader As SqlDataReader=mycommand.executereader()
if myReader.Read() then
id=myReader("id")
end if
myconn.close()
'保存图片
FileUp.PostedFile.SaveAs( Server.MapPath("\classpic\")&cstr(id)&".jpg" )
'生成缩略图
image=System.Drawing.Image.FromFile(Server.MapPath("/classpic/"+cstr(id)+".jpg"))
width=image.Width
height=image.height
if width>height then
newwidth=250
newheight=image.height/image.Width*newwidth
else
newheight=250
newwidth=image.Width/image.height*newheight
end if
response.write("id="+cstr(id)+"width="+cstr(Width)+";height="+cstr(height)+" ")
response.write("newwidth="+cstr(newwidth)+";newheight="+cstr(newheight)+"<br>")aNewImage=image.GetThumbnailImage(newwidth,newheight,callb,new System.IntPtr())
aNewImage.Save(Server.MapPath("/smallpic/"+cstr(id)+".jpg"))
image.Dispose()
Dim FileSplit() As String = Split( FileUp.PostedFile.FileName, "\" )
Dim FileName As String = FileSplit(FileSplit.Length-1)
Dim Exts() As String = Split( FileName, "." )
Dim Ext As String = LCase(Exts(Exts.Length-1))FDisplay.Text = "<A Target='_blank' HREF='/classpic/"&cstr(id)&".jpg"& "'>查看上传文件</A>"
FDisplay1.text="<a href='/picture/default.asp?bj="&cstr(request.cookies("dgxyl").values("dgxylbj"))&"'>返回</a>"
End Sub
</script>
<SCRIPT language=JavaScript>
<!--
var requestsubmitted=false;
function guestbook_Validator(theForm)
{
//检查是否从新提交
if (requestsubmitted==true){
alert("你已经提交了留言,请等待服务器应答!");
return(false);
}
requestsubmitted=true;return (true);
}
//-->
</SCRIPT>
<Body BgColor=White>
<H3 align="center">请正确填写下面各项</h3>
<Hr></H3>
<Div id="FileInfo" Visible="False" runat="server">
<Asp:Label id="FSize" runat="server"/><br>
<Asp:Label id="FName" runat="server"/><br>
<Asp:Label id="FDisplay" runat="server"/>
<Asp:Label id="FDisplay1" runat="server"/>
</Div>
<Form Enctype="multipart/form-data" onsubmit="return guestbook_Validator(this)" runat="server">
上传文件
<Input Type="File" id="FileUp" runat="server" size="20"><br>
图片属性:<input type="radio" value="<%=request.cookies("dgxyl").values("dgxylbj")%>" name="R1" checked>本班<input type="radio" value="全校" name="R1">全校(本班则只在本班显示,全校则在全校显示)<P>
图片说明:<br>
<asp:TextBox id="TextBox1" runat="server" Width="233px" Height="141px">
</asp:TextBox>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="请输入图片说明">
</asp:RequiredFieldValidator><br>
<Asp:button id="Upload" OnClick="UploadFile" Text="上传图片" runat="server"/>
</form>
<Hr>
<p>注意:</p>
<ol>
<li><b>严禁上传污染环境的照片,否则账号将被删除!</b></li>
<li><font color="#808000"><b>请详细填写照片说明,图片说明不详细将会被视为乱传图片,将会被删除!</b></font></li>
</ol>
<p> </p></Body>
</Html>
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for(j = 0; j < encoders.Length; ++j)
{
if(encoders[j].MimeType == mimeType)
return encoders[j];
} return null;
}private void WriteNewDescriptionInImage(string Filename,string NewDescription)
{
Image Pic;
PropertyItem[] PropertyItems;
byte[] bDescription=new Byte[NewDescription.Length];
int i;
string FilenameTemp;
Encoder Enc=Encoder.Transformation;
EncoderParameters EncParms=new EncoderParameters(1);
EncoderParameter EncParm;
ImageCodecInfo CodecInfo=GetEncoderInfo("image/jpeg");// copy description into byte array
for (i=0;i<NewDescription.Length;i++) bDescription[i]=(byte)NewDescription[i];// load the image to change
Pic=Image.FromFile(Filename);// put the new description into the right property item
PropertyItems=Pic.PropertyItems;
PropertyItems[0].Id=0x010e; // 0x010e as specified in EXIF standard
PropertyItems[0].Type=2;
PropertyItems[0].Len=NewDescription.Length;
PropertyItems[0].Value=bDescription;
Pic.SetPropertyItem(PropertyItems[0]);// we cannot store in the same image, so use a temporary image instead
FilenameTemp=Filename+".temp";// for lossless rewriting must rotate the image by 90 degrees!
EncParm=new EncoderParameter(Enc,(long)EncoderValue.TransformRotate90);
EncParms.Param[0]=EncParm;// now write the rotated image with new description
Pic.Save(FilenameTemp,CodecInfo,EncParms);// for computers with low memory and large pictures: release memory now
Pic.Dispose();
Pic=null;
GC.Collect();// delete the original file, will be replaced later
System.IO.File.Delete(Filename); // now must rotate back the written picture
Pic=Image.FromFile(FilenameTemp);
EncParm=new EncoderParameter(Enc,(long)EncoderValue.TransformRotate270);
EncParms.Param[0]=EncParm;
Pic.Save(Filename,CodecInfo,EncParms);// release memory now
Pic.Dispose();
Pic=null;
GC.Collect();// delete the temporary picture
System.IO.File.Delete(FilenameTemp);
}
When saving to JPEG images, you can also control the compression ratio of the algorithm. You must use a different overload of the Save method:public void Save(
string filename,
ImageCodecInfo encoder,
EncoderParameters encoderParams
);The first step is to get the ImageCodecInfo structure for the JPEG image. The GDI+ interface provides no direct method to get this object. You must resort to a little trick—enumerate all the image encoders and check their MIME type properties against the JPEG MIME type string (image/jpeg). The ImageCodecInfo structure contains information inherent in the encoding and decoding of the image.The EncoderParameters argument represents an array of encoding parameters. Each element of the array is an EncoderParameter type. Possible parameters are listed as members of the static class Encoder. For example, the parameter Compression lets you choose a compression engine for TIFF images. The Quality parameter lets you choose the desired quality of the JPEG compression. This code compresses a JPEG with a 40:1 ratio: // Set the quality to 40 (must be a long)
Encoder qualityEncoder = Encoder.Quality;
EncoderParameter ratio = new EncoderParameter(qualityEncoder, 40L);
// Add the quality parameter to the list
codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
// Save to JPG
bmp.Save(fileName, jpegCodecInfo, codecParams);Hope this is useful to others!