20 secrets of MVC3-(12) generating thumbnails by changing the image size

Source: Internet
Author: User

 

Problem

You allow users to upload an image, but traditionally, this image is usually output from a camera, which is too large. So you want to display a simple image or thumbnail. Preview the thumbnail before allowing the user to see the complete picture on your website ).

Solution

Use the following classes to update the existing file upload function to adjust the Image: FileStream, Image, Bitmap, and Graphics class to specify the width and height.

Discussion

In the following example, the previously created FileUpload class is updated and reorganized. Create a new function called ResizeImage to resize the image. The resized image will be saved in the subfolders of the previous folder, named (thumbnail) thumbnail. The DeleteFile function is also updated. The thumbnails and original images are also deleted, a new function is created, and the delete function is called twice.

To avoid code duplication. The code for the FileUpload class is as follows:

Translator: I added the Code marked with red below. In this way, we can save images and thumbnails to the folder of our project. Otherwise, it will be stored in the directory C: \ Program Files \ Common Files \ Microsoft Shared \ DevServer \ 10.0.

Using System;

Using System. Collections. Generic;

Using System. Drawing;

Using System. Drawing. Drawing2D;

Using System. Linq;

Using System. Web;

Using System. IO;

 

Namespace MvcApplication. Utils

{

Public static class FileUpload

{

Public static char DirSeparator = Path. DirectorySeparatorChar;

Public static string FilesPath = HttpContext. Current. Server. MapPath (string. Format ("Content {0} Uploads {1}", DirSeparator, DirSeparator ));

Public static string UploadFile (HttpPostedFileBase file)

{

// Check if we have a file

If (null = file) return "";

// Make sure the file has content

If (! (File. ContentLength> 0) return "";

String fileName = file. FileName;

String fileExt = Path. GetExtension (file. FileName );

// Make sure we were able to determine a proper

// Extension

If (null = fileExt) return "";

// Check if the directory we are saving to exists

If (! Directory. Exists (FilesPath ))

{

// If it doesn' t exist, create the directory

Directory. CreateDirectory (FilesPath );

}

// Set our full path for saving

String path = FilesPath + DirSeparator + fileName;

// Save our file

File. SaveAs (Path. GetFullPath (path ));

// Save our thumbnail as well

ResizeImage (file, 150,100 );

// Return the filename

Return fileName;

}

Public static void DeleteFile (string fileName)

{

// Don't do anything if there is no name

If (fileName. Length = 0) return;

// Set our full path for deleting

String path = FilesPath + DirSeparator + fileName;

String thumbPath = FilesPath + DirSeparator +

"Thumbnails" + DirSeparator + fileName;

RemoveFile (path );

RemoveFile (thumbPath );

}

Private static void RemoveFile (string path)

{

// Check if our file exists

If (File. Exists (Path. GetFullPath (path )))

{

// Delete our file

File. Delete (Path. GetFullPath (path ));

}

}

Public static void ResizeImage (HttpPostedFileBase file, int width, int height)

{

 

String thumbnailDirectory =

String. Format (@ "{0} {1} {2}", FilesPath,

DirSeparator, "Thumbnails ");

// Check if the directory we are saving to exists

If (! Directory. Exists (thumbnailDirectory ))

{

// If it doesn' t exist, create the directory

Directory. CreateDirectory (thumbnailDirectory );

}

// Final path we will save our thumbnail

String imagePath =

String. Format (@ "{0} {1} {2}", thumbnailDirectory,

DirSeparator, file. FileName );

// Create a stream to save the file to when we're re

// Done resizing

FileStream stream = new FileStream (Path. GetFullPath (

ImagePath), FileMode. OpenOrCreate );

// Convert our uploaded file to an image

Image OrigImage = Image. FromStream (file. InputStream );

// Create a new bitmap with the size of our

// Thumbnail

Bitmap TempBitmap = new Bitmap (width, height );

// Create a new image that contains quality

// Information

Graphics NewImage = Graphics. FromImage (TempBitmap );

NewImage. CompositingQuality =

CompositingQuality. HighQuality;

NewImage. SmoothingMode =

SmoothingMode. HighQuality;

NewImage. InterpolationMode =

InterpolationMode. HighQualityBicubic;

// Create a rectangle and draw the image

Rectangle imageRectangle = new Rectangle (0, 0,

Width, height );

NewImage. DrawImage (OrigImage, imageRectangle );

// Save the final file

TempBitmap. Save (stream, OrigImage. RawFormat );

// Clean up the resources

NewImage. Dispose ();

TempBitmap. Dispose ();

OrigImage. Dispose ();

Stream. Close ();

Stream. Dispose ();

}

}

}

 

The above example has done a lot of things, especially in the ResizeImage function.

First, if the thumbnail directory does not exist, it will be created. Next, a new FileStream is created for Editing Based on the full path stored in the thumbnail.

The original uploaded Image is converted to an Image object based on uploaded InputStream. A new bitmap is created based on the width and height of the image. Next, use this bitmap to create a new Graphics object. Graphics object, NewImage, used to set and define quality, smooth surface, and interpolation mode. Without these settings, the thumbnails will not look very pixel-like and adjust awkwardly.

Once all settings are complete, a new rectangle is created and the original image is painted into Graphics. This is the actual adjustment. Finally, save the bitmap and dispose of all created objects to release resources.

For more information, see

FileStream, Image, Bitmap, and Graphics

 


Author technical brother

Related Article

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.