(12)改变图片的大小生成缩略图

问题

你允许用户上传一个图片,但是传统的来说,这个图片一般是从一个camera输出的,这个图片太大。所以你想展现一个简单的图片或者缩略图。在你的网站允许用户在他看到完整图片之前先预览缩略图(译者:这是一个很好的用户体验)。

解决方案

使用以下几个类去更新现有的文件上传功能去调整图片:FileStream, Image, Bitmap,和Graphics 类去指定宽度和高度。

讨论

在下面的例子,以前创建的FileUpload类将得到更新和重组。创建一个新的功能,称为ResizeImage执行调整图片大小。调整大小后的图像将被保存在以前的文件夹的子文件夹中,名为(thumbnail)缩略图。 DeleteFile函数也被更新,同时删除缩略图和原始图像,并创建一个新的函数,并调用了两次删除功能 为了避免重复代码。下面是FileUpload类的代码:

译者:下边标红的代码是我加上去的。这样我们可以把图片和缩略图存到我们项目的文件夹下。否则他会存到:C:Program FilesCommon FilesMicrosoft SharedDevServer10.0目录下。

双击代码全选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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
             // 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();
         }
     }
}
 

上边的例子做了很多事,特别是在ResizeImage函数。

首先,如果缩略图​​目录不存在,它将被创建。接下来,一个新的FileStream会根据缩略图存放的完整路径被创建用于编辑。 原上传的图像根据uploaded的InputStream被转换为Image类的对象。一个新的位图会被根据图图像的宽度和高度创建。接下来用这个位图去创建一个新的Graphics对象。Graphics对象,NewImage,用于设置和定义质量,表面光滑,插补模式。如果没有这些设置,缩略图会不会好看非常像素化和调整笨拙。

一旦都设置好了,一个新的矩形被创建并且原始图像被画到Graphics中。这是执行实际的调整大小。最后保存位图和所有创建的对象的处置,以释放资源。

转载于:https://www.cnblogs.com/lyaxx1314/p/3603499.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值