加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 上传图片的缩略图创建

发布时间:2020-12-16 07:17:31 所属栏目:asp.Net 来源:网络整理
导读:我想上传多个图像并将其保存到我的应用程序中的文件夹中,并将其保存到名为Thumbnail的文件夹中的相同图像的缩略图中.我上传并将图像成功保存在 Images文件夹中.我也想保存它的缩略图. 在视图中 form action="" method="post" enctype="multipart/form-data"
我想上传多个图像并将其保存到我的应用程序中的文件夹中,并将其保存到名为Thumbnail的文件夹中的相同图像的缩略图中.我上传并将图像成功保存在 Images文件夹中.我也想保存它的缩略图.

在视图中

<form action="" method="post" enctype="multipart/form-data">
  @Html.Label("Select the property : ");
  @Html.DropDownList("Address",new SelectList(ViewBag.Address as System.Collections.IEnumerable),"---Select---",new { id = "add"})
  <label for="file">Filename:</label>
  <input type="file" name="files" id="file" multiple="true"/>

  <input type="submit" />

????

在控制器中

public class HomeController : Controller
    {
        PropertyAssessmentSystemEntities db = new PropertyAssessmentSystemEntities();

        public ActionResult Index()
        {
            var q = from pi in db.PropertyInfoes
                    select pi.Full_Address;
            ViewBag.Address = q.ToList();
            return View();
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase[] files,FormCollection c)
        {
            int no = 0,no1 =0;
            string path = Path.Combine(Server.MapPath("~/Images"),c["Address"].Replace(' ','_'));
            string fn = "",fn1 = "";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            else
                no = Directory.GetFiles(path).Length;
            foreach (var file in files)
            {
                string fname = "img_" + no++ + file.FileName.Substring(file.FileName.LastIndexOf('.'));
                string fname1 = "img_" + no1++ + file.FileName.Substring(file.FileName.LastIndexOf('.'));
                fname1 = Path.Combine("Thumbnail",fname1);
                fn1 = Path.Combine(path,fname1);
                if (!Directory.Exists(fn1))
                    Directory.CreateDirectory(fn1);
                else
                    no = Directory.GetFiles(fn1).Length;

                fn = Path.Combine(path,fname);
                file.SaveAs(fn);
                Stream strm = new FileStream(fn,FileMode.OpenOrCreate);
                GenerateThumbnails(0.05,strm,fn1);
            }

            return RedirectToAction("Index");
        }

        private void GenerateThumbnails(double scaleFactor,Stream sourcePath,string targetPath)
        {
            using (var image = System.Drawing.Image.FromStream(sourcePath))
            {
                var newWidth = (int)(image.Width * scaleFactor);
                var newHeight = (int)(image.Height * scaleFactor);
                var thumbnailImg = new Bitmap(newWidth,newHeight);
                var thumbGraph = Graphics.FromImage(thumbnailImg);
                thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
                thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
                thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                var imageRectangle = new Rectangle(0,newWidth,newHeight);
                thumbGraph.DrawImage(image,imageRectangle);
                thumbnailImg.Save(targetPath,image.RawFormat);
            } }}

执行此操作时,thumbnailImg.Save(targetPath,image.RawFormat)中会发生错误;
GDI中发生了一般错误.任何人都可以帮我解决这个问题吗?

解决方法

我有另一种在上传时从图像创建缩略图的方法,如下所示:

在using命名空间中添加以下指令:

using System.Drawing;
using System.Drawing.Imaging;

在控制器操作中添加以下代码以创建缩略图

using (var image = Image.FromStream(file.InputStream,true,true)) /* Creates Image from specified data stream */
{
     using (var thumb = image.GetThumbnailImage(
          36,/* width*/
          30,/* height*/
          () => false,IntPtr.Zero))
       {
          var jpgInfo = ImageCodecInfo.GetImageEncoders().Where(codecInfo => codecInfo.MimeType == "image/png").First(); /* Returns array of image encoder objects built into GDI+ */
          using (var encParams = new EncoderParameters(1))
          {
              var appDataThumbnailPath = Server.MapPath("~/Uploads/Thumbnail/" + User.id);
              if (!Directory.Exists(appDataThumbnailPath))
              {
                  Directory.CreateDirectory(appDataThumbnailPath);
              }
              string outputPath = Path.Combine(appDataThumbnailPath,fileName);
              long quality = 100;
              encParams.Param[0] = new EncoderParameter(Encoder.Quality,quality);
              thumb.Save(outputPath,jpgInfo,encParams);
          }
       }
 }

这里的文件是HttpPostedFileBase对象,它有输入图像,outputPath是缩略图的目标文件.通过以下过程,您将获得缩略图.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读