Asp.net generates thumbnails and supports file upload implementation code

Source: Internet
Author: User

This article shares the asp.net implementation code that automatically generates thumbnails after two files are uploaded. The benefits of thumbnails can reduce server bandwidth and speed up image download.

 

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 Layer 3
{
/// <Summary>
/// Display the thumbnail of the requested image, in the maximum unit of 100 pixels in width
/// </Summary>
Public class imgSmall: IHttpHandler
{
// Folder where the image is located
Static string picturesPath = @ "d: wordpictures ";
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "image/jpeg ";
// Obtain the passed img string, such
// Http: // localhost: 5002/imgSmall. ashx? Img1_abacus8.jpg
String img = context. Request. Params ["img"];
String path = picturesPath + img;
// If the file exists, it will be read. Reduce the use of try and catch to improve program performance.
If (File. Exists (path ))
{
// Load the image
Image big = Image. FromFile (path );
// If the file can be obtained, the following code will be executed.
If (big! = Null)
{
// Set the maximum width, which can be modified to generate smaller thumbnails
Int newWidth = 100;
// Generate a bitmap based on the aspect ratio of the image.
Bitmap bitmap = new Bitmap (newWidth, newWidth * big. Height/big. Width );
// Create a picture based on the palette
Graphics g = Graphics. FromImage (bitmap );
Using (g)
{
// Draw a big image to a bitmap defined by yourself
G. DrawImage (big, 0, 0, bitmap. Width, bitmap. Height );
// Directly Save the processed bitmap to the response output stream. The format is jpeg!
Bitmap. Save (context. Response. OutputStream, System. Drawing. Imaging. ImageFormat. Jpeg );
}
}
}
Else
{
// Otherwise, a message indicating that the file does not exist will be sent to the browser.
Context. Response. ContentType = "text/html ";
Context. Response. Write ("the file does not exist ");
// Or send an image that does not exist in the file
// Context. Response. WriteFile ("Change todo to image path ");
}
}
Public bool IsReusable
{
Get
{
Return false;
}
}
}
}

Instance, you can upload the image and then generate a thumbnail

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 = "Size of the uploaded file" + 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 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. deleettings ("Database "))
Myconn. open ()
SQL = "insert into picture (name, class, Introduction, attribute) values ('" & request. cookies ("dgxyl "). values ("dgxylname") & "','" & request. cookies ("dgxyl "). values ("dgxylbj") & "','" & trim (request ("TextBox1") & "','" & request ("r1 ")&"')"
Mycomm = New sqlcommand (SQL, myconn)
Mycomm.exe cutenonquery ()
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.exe cutereader ()
If myReader. Read () then
Id = myReader ("id ")
End if
Myconn. close ()
'Save the image
FileUp. PostedFile. SaveAs (Server. MapPath ("classpic") & cstr (id) & ". jpg ")
'Generate a thumbnail
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. Length-1 ))

FDisplay. text = "<A Target = '_ blank' HREF = '/classpic/" & cstr (id )&". jpg "&" '> View uploaded files </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 whether the request is submitted again
If (requestsubmitted = true ){
Alert ("You have submitted a message. Please wait for the server to respond! ");
Return (false );
}
Requestsubmitted = true;


Return (true );
}
// -->
</SCRIPT>
<Html>
<Body BgColor = White>
<H3 align = "center"> enter the following items correctly <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">
Upload files
<Input Type = "File" id = "FileUp" runat = "server" size = "20"> <br>
Image attribute: <input type = "radio" value = "<% = request. cookies ("dgxyl "). values ("dgxylbj ") %> "name =" R1 "checked> This class <input type =" radio "value =" "name =" R1 "> all schools (this class is only displayed in this class, the whole school is displayed in the whole school.) <P>
Image Description: <br>
<Asp: TextBox id = "TextBox1" runat = "server" Width = "233px" Height = "141px">
</Asp: TextBox>
<Asp: RequiredFieldValidator id = "RequiredFieldValidator1" runat = "server" ControlToValidate = "TextBox1" ErrorMessage = "Enter image description">
</Asp: RequiredFieldValidator> <br>
<Asp: button id = "Upload" Text = "Upload image" runat = "server"/>
</Form>
<Hr>
<P> Note: </p>
<Ol>
<Li> <B> It is strictly prohibited to upload photos that pollute the environment. Otherwise, the account will be deleted! </B> </li>
<Li> <font color = "#808000"> <B> Fill in the photo description in detail. If the picture description is not detailed, it will be regarded as a false picture and 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.