Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thumbnail creation of uploaded image

I want to upload multiple images and save it to a folder in my application and also thumbnails of the same images in a folder called Thumbnail. I uploaded and saved my images successfully in the Images folder. I want to save its thumbnail too.

In View

<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" />

In controller

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, 0, newWidth, newHeight);
                thumbGraph.DrawImage(image, imageRectangle);
                thumbnailImg.Save(targetPath,image.RawFormat);
            } }}

On executing this an error occurs in thumbnailImg.Save(targetPath,image.RawFormat); A generic error occurred in GDI+. Can any one pls help me to solve this??

like image 610
neetz Avatar asked Jun 05 '13 09:06

neetz


People also ask

What is thumbnail of an image?

A thumbnail is a small image representation of a larger image, usually intended to make it easier and faster to look at or manage a group of larger images. Graphic designers and photographers typically use this term.

How do I make an image a thumbnail in HTML?

Use the border property to create thumbnail images. Wrap an anchor around the image to use it as a link. Hover over the image and click on it to see the effect.


1 Answers

I have an alternative way of creating thumbnails from image while upload which is as follows :

Add the following directives in your using namespace :

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

Add the following code in your controller action for creating thumbnails

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);
          }
       }
 }

Here the file is HttpPostedFileBase object which has the input image , outputPath is the destination file for thumbnail. By the following process you will have your thumbnails.

like image 133
Shalin Jirawla Avatar answered Sep 19 '22 05:09

Shalin Jirawla