Upload and preview a simulated QQ mood Image

Source: Internet
Author: User

For the sake of security performance, currently, js does not support obtaining local images for preview. Just in a release box similar to QQ mood, I found many jquery plug-ins, few of them can meet the requirements, so you can use SWFuplad to upload and preview this image.

First, paste the following plug-ins. You may be able to use other Image Upload functions.

1. jQuery File Upload

Demo address: http://blueimp.github.io/jQuery-File-Upload/
The advantage is that jquery is used for asynchronous upload of images, which is controllable and can be customized as needed;
The disadvantage is that in some browsers such as IE9, image preview is not supported, and multi-file selection is not supported in the Image Selection box (this is why I abandoned it );

2. CFUpdate

Demo address: http://www.access2008.cn/update/
Advantages: Implemented Using js + flash, compatible with all browsers, and good interface effects. It supports batch upload, preview, progress bar, deletion, and other functions. It is very useful as an Image Upload control;
Disadvantage: the custom plug-in can only modify the color, and the style is fixed;

3. SWFUpload

: Http://code.google.com/p/swfupload/
Help address: http://www.phptogether.com/swfuploadoc/#uploadError
This plug-in is used in this article. Using flash + jquery, you can change buttons and various styles, and listen to events in a comprehensive manner.

The following are the source code and design ideas. The main functions include:
1. Upload and preview of images (first upload the images to the server and then return to the address for preview. Currently, the html5 preview method is more reliable)
2. Create a thumbnail (after proportional scaling, take the middle area as the thumbnail, similar to the QQ space, but it seems that the QQ space is added with the face recognition function)

The following functions are implemented:
 
1. Thumbnail. cs
Copy codeThe Code is as follows:
Public class thumbrix
{
/// <Summary>
/// Generate a thumbnail
/// </Summary>
/// <Param name = "imgSource"> original image </param>
/// <Param name = "newWidth"> thumbnail width </param>
/// <Param name = "newHeight"> thumbnail height </param>
/// <Param name = "isCut"> whether to crop (center point) </param>
/// <Returns> </returns>
Public static Image GetThumbnail (System. Drawing. Image imgSource, int newWidth, int newHeight, bool isCut)
{
Int rWidth = 0; // width after proportional Scaling
Int rHeight = 0; // The height after proportional Scaling
Int sWidth = imgSource. Width; // The Width of the original image.
Int sHeight = imgSource. Height; // Original Image Height
Double wScale = (double) sWidth/newWidth; // Width Ratio
Double hScale = (double) sHeight/newHeight; // High Ratio
Double scale = wScale RWidth = (int) Math. Floor (sWidth/scale );
RHeight = (int) Math. Floor (sHeight/scale );
Bitmap thumbnail = new Bitmap (rWidth, rHeight );
Try
{
// If the source image is captured and the ratio of the original image is smaller than the rectangular frame to be captured, the original image is retained.
If (! IsCut & scale <= 1)
{
Return imgSource;
}

Using (Graphics tGraphic = Graphics. FromImage (thumbnail ))
{
TGraphic. InterpolationMode = System. Drawing. Drawing2D. InterpolationMode. HighQualityBicubic;/* new way */
Rectangle rect = new Rectangle (0, 0, rWidth, rHeight );
Rectangle rectSrc = new Rectangle (0, 0, sWidth, sHeight );
TGraphic. DrawImage (imgSource, rect, rectSrc, GraphicsUnit. Pixel );
}

If (! IsCut)
{
Return thumbnail;
}
Else
{
Int xMove = 0; // offset to the right (CROP)
Int yMove = 0; // downward offset (CROP)
XMove = (rWidth-newWidth)/2;
YMove = (rHeight-newHeight)/2;
Bitmap final_image = new Bitmap (newWidth, newHeight );
Using (Graphics fGraphic = Graphics. FromImage (final_image ))
{
FGraphic. InterpolationMode = System. Drawing. Drawing2D. InterpolationMode. HighQualityBicubic;/* new way */
Rectangle rect1 = new Rectangle (0, 0, newWidth, newHeight );
Rectangle rectSrc1 = new Rectangle (xMove, yMove, newWidth, newHeight );
FGraphic. DrawImage (thumbnail, rect1, rectSrc1, GraphicsUnit. Pixel );
}

Thumbnail. Dispose ();

Return final_image;
}
}
Catch (Exception e)
{
Return new Bitmap (newWidth, newHeight );
}
}
}

2. Image Upload handler Upload. ashx
Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Drawing;

Namespace Mood
{
/// <Summary>
/// Summary of Upload
/// </Summary>
Public class Upload: IHttpHandler
{
Image thumbnail;

Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
Try
{
String id = System. Guid. NewGuid (). ToString ();
HttpPostedFile pai_image_upload = context. Request. Files ["Filedata"];
Image original_image = System. Drawing. Image. FromStream (pai_image_upload.inputstream );
Original_image.Save (System. Web. HttpContext. Current. Server. MapPath ("~ /Files/"+ id +". jpg "));
Int target_width = 200;
Int target_height = 150;
String path = "Files/Files200/" + id + ". jpg ";
String saveThumbnailPath = System. Web. HttpContext. Current. Server. MapPath ("~ /"+ Path );
Thumbnail = thumbrix. GetThumbnail (original_image, target_width, target_height, true );
Thumbnail. Save (saveThumbnailPath );
Context. Response. Write (path );
}
Catch (Exception e)
{
// If any kind of error occurs return a 500 Internal Server error
Context. Response. StatusCode = 500;
Context. Response. Write ("an error occurred during the upload! ");
}
Finally
{
If (thumbnail! = Null)
{
Thumbnail. Dispose ();
}
}
}

Public bool IsReusable
{
Get
{
Return false;
}
}
}
}

3. Mood. aspx
Copy codeThe Code is as follows:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "Mood. aspx. cs" Inherits = "Mood. Mood" %>

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Script src = "SwfUpload/swfupload. js" type = "text/javascript"> </script>
<Script src = "jquery-1.7.1.js" type = "text/javascript"> </script>
<Link href = "Style/Mood.css" rel = "stylesheet" type = "text/css"/>
<Title> </title>
<Script type = "text/javascript">
$ (). Ready (function (){
SetSwf ();
$ ("# BtnReply"). click (function (){
$ ("# DivImgs"). hide ();
});
});

Var swfu;
Function SetSwf (){
Swfu = new SWFUpload ({
// Backend Settings
Upload_url: "Upload. ashx ",
// File Upload Settings
File_size_limit: "20 MB ",
File_types: "*. jpg; *. png; * jpeg; * bmp ",
File_types_description: "JPG; PNG; JPEG; BMP ",
File_upload_limit: "0", // Zero means unlimited
File_queue_error_handler: fileQueueError,
File_dialog_complete_handler: fileDialogComplete,
Upload_progress_handler: uploadProgress,
Upload_error_handler: uploadError,
Upload_success_handler: uploadSuccess,
Upload_complete_handler: uploadComplete,
// Button settings
Button_image_url: "/Style/Image/4-16.png ",
Button_placeholder_id: "divBtn ",
Button_width: 26,
Button_height: 26,

// Flash Settings
Flash_url: "/swfupload/swfupload.swf ",

Custom_settings :{
Upload_target: "divFileProgressContainer"
},

// Debug Settings
Debug: false
});
}

// File Verification
Function fileQueueError (file, errorCode, message ){
Try {
Switch (errorCode ){
Case SWFUpload. QUEUE_ERROR.ZERO_BYTE_FILE:
Alert ("An error occurred while uploading files! ");
Break;
Case SWFUpload. QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
Alert ("the File Upload limit is exceeded (20 mb )! ");
Break;
Case SWFUpload. QUEUE_ERROR.ZERO_BYTE_FILE:
Case SWFUpload. QUEUE_ERROR.INVALID_FILETYPE:
Default:
Alert ("file error! ");
Break;
}
} Catch (ex ){
This. debug (ex );
}

}

// Triggered when the file is selected
Function fileDialogComplete (numFilesSelected, numFilesQueued ){
Try {
If (numFilesQueued> 0 ){
$ ("# DivImgs"). show ();
For (var I = 0; I <numFilesQueued; I ++ ){
$ ("# UlUpload "). append ('<li id = "li' + I + '"> </li> ');
}

This. startUpload ();
}
} Catch (ex ){
This. debug (ex );
}
}

// The Processing Method of the scroll bar is not written at the moment.
Function uploadProgress (file, bytesLoaded ){
}

// Processing after each file is uploaded successfully
Function uploadSuccess (file, serverData ){
Try {
Var index = file. id. substr (file. id. lastIndexOf ('_') + 1 );
$ ("# Li" + index.html .html ("");
$ ("# Li" + index.html .html (' ');
Index ++;

} Catch (ex ){
This. debug (ex );
}
}

// Triggers the upload of the next object after the upload is complete
Function uploadComplete (file ){
Try {
If (this. getStats (). files_queued> 0 ){
This. startUpload ();
}
} Catch (ex ){
This. debug (ex );
}
}

// Handle upload errors of a single file
Function uploadError (file, errorCode, message ){
Var imageName = "imgerror.png ";
Try {
Var index = file. id. substr (file. id. lastIndexOf ('_') + 1 );
$ ("# Li" + index.html .html ("");
$ ("# Li" + index.html .html (' ');
Index ++;
} Catch (ex3 ){
This. debug (ex3 );
}
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div style = "width: 600px;">
<Div class = "divTxt">
Text Box
</Div>
<Div style = "height: 30px; line-height: 30px;">
<Div id = "divBtn" style = "float: left; width: 26px; height: 26px;">
</Div>
<Div style = "float: right;">
<Input id = "btnReply" type = "button" value = ""/>
</Div>
</Div>
<Div id = "divImgs" style = "border: 1px solid # cdcdcd; display: none;">
<Div>
Upload an image </div>
<Ul id = "ulUpload" class = "ulUpload">
</Ul>
</Div>
</Div>
</Form>
</Body>
</Html>

Use Vs2010 for development. The following is the source code address of the project.

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.