asp.net generates thumbnails and supports file upload implementation code

Source: Internet
Author: User

The code is as follows Copy Code
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Drawing;
Using System.IO;
Namespace Web three layer
{
<summary>
Displays the thumbnail of the requested picture, with a width of 100 pixels as the largest unit
</summary>
public class Imgsmall:ihttphandler
{
folder where pictures are located
static string Picturespath = @ "D:wordpictures";
public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Image/jpeg";
Gets the IMG string passed over, such as
Yun_qi_img/imgsmall.ashximg=abacus8.jpg this
string img = context. Request.params["IMG"];
String path = Picturespath + img;
If the file exists to read, reduce the use of Try,catch, improve program performance
if (file.exists (path))
{
Load this picture
Image big = image.fromfile (path);
If you can get a file, the following code is executed
if (Big!= null)
{
Set the maximum width and can be modified to produce smaller thumbnails
int newwidth = 100;
Generate a bitmap based on the aspect ratio of the picture
Bitmap Bitmap = new Bitmap (newwidth, Newwidth * big. Height/big. Width);
To create a picture from a storyboard
Graphics g = graphics.fromimage (bitmap);
Using (g)
{
Draw big picture into your own little map of your definition bitmap
G.drawimage (big, 0, 0, bitmap.) Width, Bitmap. Height);
Directly saves the processed bitmap to the response output stream in the form of jpeg!
Bitmap. Save (context. Response.outputstream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
Else
{
Otherwise, send a file that does not exist to the browser
Context. Response.ContentType = "text/html";
Context. Response.Write ("File does not exist");
Or send a picture of a file that doesn't exist
Context. Response.WriteFile ("Todo here modified as the path to the picture");
}
}
public bool IsReusable
{
Get
{
return false;
}
}
}
}

example, you can upload pictures and then generate thumbnails

The code is as follows Copy Code

<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 If

Fsize.text = "Upload file size" + CSTR (fileup.postedfile.contentlength/1024) + "KB"
Fname.text = "uploaded file name:" +fileup.postedfile.filename+ "<br>" +fname.text


' write to database
On Error Resume Next
Dim myconn As SqlConnection
Dim mycomm As SqlCommand
Dim sql As St Ring
Dim id As Integer
Dim image,anewimage As System.Drawing.Image
Dim width,height,newwidth,newheight As I Nteger
Dim callb as System.Drawing.Image.GetThumbnailImageAbort
Myconn=new SqlConnection ( ConfigurationSettings.AppSettings ("database"))
MyConn.Open ()
sql= "insert into the picture (name, class, description, Attributes) 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")
E nd if
myconn.close ()
Save picture
FileUp.PostedFile.SaveAs (Server.MapPath ("Classpic") &cstr (ID) & ". jpg"
Generate thumbnails
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" & "> View upload file </A>"
fdisplay1.text= "<a href= '/picture/default.asp?bj=" &cstr (Request.Cookies ("Dgxyl"). VALUES ("DGXYLBJ") & "' > Return </a>"
End Sub
</script>
<script language=javascript>
<!--
var Requestsubmitted=false;
function Guestbook_validator (theform)
{
Check to see if you are submitting a new
if (requestsubmitted==true) {
Alert ("You have submitted a message, please wait for the server to reply!") ");
return (false);
}
Requestsubmitted=true;


return (true);
}
-->
</SCRIPT>
<Html>
<body bgcolor=white>

<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" >
Uploading files
<input type= "File" id= "Fileup" runat= "Server" size= "><br>"
Picture properties: <input type= "Radio" value= <%=request.cookies ("Dgxyl"). VALUES ("DGXYLBJ")%> "name=" R1 "checked>" <input type= "Radio" value= "The whole School" name= "R1" > School (This class is only shown in this class, the whole school is shown in the whole school) <P>
Picture Description:<br>
<asp:textbox id= "TextBox1" runat= "Server" width= "233px" height= "141px" >
</asp:TextBox>
<asp:requiredfieldvalidator id= "RequiredFieldValidator1" runat= "Server" controltovalidate= "TextBox1" Errormessage= "Please enter picture description" >
</asp:RequiredFieldValidator><br>
<asp:button id= "Upload" text= "Upload Picture" runat= "Server"/>
</form>
<Hr>
<p> Note:</p>
<ol>
<li><b> do not upload photos of contaminated environment, otherwise the account will be deleted! </b></li>
<li><font color= "#808000" ><b> please fill in the photo description, the picture description is not detailed will be considered as a random image, will be deleted! </b></font></li>
</ol>

</Body>
</Html>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.