1

I am trying to resize an image that will be uploaded through a file input before saving it to the directed folder. I tried many possible way but i still cant get it. Please do help me!

View

@using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
     <input type="file" name="file" id="btnFileUpload" class="zone" runat="server"/>
}

Ajax

$('#btnFileUpload').fileupload({
                    url: '@Url.Action("UploadFile")',
                    dataType: 'json',
                    disableImageResize: /Android(?!.*Chrome)|Opera/
                        .test(window.navigator && navigator.userAgent),
},
            success: function (e, data) {
                //window.location.reload();
                console.log("Done");
                console.log(e);
});

controller

[HttpPost]  
        public ActionResult UploadFile(HttpPostedFileBase file)  
        {
            string _FileName = "";
            string _path = "";
         try  
            {
               if (file.ContentLength > 0)  
                {
                    _FileName = Path.GetFileName(DateTime.Now.ToBinary() + "-" + file.FileName);
                    _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);

                    file.SaveAs(_path);


                    imageUrls = "/UploadedFiles/" + _FileName;
                }
                System.Diagnostics.Debug.WriteLine("File Uploaded Successfully!!");

                return Json(imageUrls);
            }  
            catch
            {
                ViewBag.Message = "File upload failed!!";
                System.Diagnostics.Debug.WriteLine("File upload failed!!");
                return Json(ViewBag.Message);  
            }  
        }

 

lel
  • 327
  • 7
  • 26

2 Answers2

1

Here The Implementation of Your scenario

i think this will work

[HttpPost]
        public ActionResult UploadFile (HttpPostedFileBase file) {

            string _FileName = "";
            string _path = "";
            try {
                if (file.ContentLength > 0) {
                    _FileName = Path.GetFileName (DateTime.Now.ToBinary () + "-" + file.FileName);
                    _path = Path.Combine (Server.MapPath ("~/UploadedFiles"), _FileName);
                    byte[] fileData = null;
                    using (var binaryReader = new BinaryReader (file.InputStream)) {
                        fileData = binaryReader.ReadBytes (file.ContentLength);
                    }

                    HandleImageUpload (fileData, _path);

                    imageUrls = "/UploadedFiles/" + _FileName;
                }
                System.Diagnostics.Debug.WriteLine ("File Uploaded Successfully!!");

                return Json (imageUrls);
            } catch {
                ViewBag.Message = "File upload failed!!";
                System.Diagnostics.Debug.WriteLine ("File upload failed!!");
                return Json (ViewBag.Message);
            }
        }

        private Image RezizeImage (Image img, int maxWidth, int maxHeight) {
            if (img.Height < maxHeight && img.Width < maxWidth) return img;
            using (img) {
                Double xRatio = (double) img.Width / maxWidth;
                Double yRatio = (double) img.Height / maxHeight;
                Double ratio = Math.Max (xRatio, yRatio);
                int nnx = (int) Math.Floor (img.Width / ratio);
                int nny = (int) Math.Floor (img.Height / ratio);
                Bitmap cpy = new Bitmap (nnx, nny, PixelFormat.Format32bppArgb);
                using (Graphics gr = Graphics.FromImage (cpy)) {
                    gr.Clear (Color.Transparent);

                    // This is said to give best quality when resizing images
                    gr.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    gr.DrawImage (img,
                        new Rectangle (0, 0, nnx, nny),
                        new Rectangle (0, 0, img.Width, img.Height),
                        GraphicsUnit.Pixel);
                }
                return cpy;
            }

        }

        private MemoryStream BytearrayToStream (byte[] arr) {
            return new MemoryStream (arr, 0, arr.Length);
        }

        private void HandleImageUpload (byte[] binaryImage, string path) {
            Image img = RezizeImage (Image.FromStream (BytearrayToStream (binaryImage)), 103, 32);
            img.Save (path, System.Drawing.Imaging.ImageFormat.jpg);
        }

resize Code taken from this thread

Jagadeesh Govindaraj
  • 6,977
  • 6
  • 32
  • 52
0

There are many great libraries for this task that handle everything you need.

I personally use ImageProcessor. And I know a ton more exist with same or even better quality. If you want I can help you use it but the documentation should be enough.

--Edit--

This is a sample code to use ImageProcessor see if it helps:

var imageFactory = new ImageFactory(true);
imageFactory.Load(inputStream).Resize(
    new ResizeLayer(new Size(128, 128), ResizeMode.Max)).
    Save(path);

Also don't forget to install the required nuget package :)

Emad
  • 3,809
  • 3
  • 32
  • 44
  • i tried that too but apparently, i can't seem to use ImageProcessor. – lel Aug 31 '17 at 06:46
  • Ok now tell me what the problem was. You don't know how to use it or you did and got error or something? – Emad Aug 31 '17 at 06:47
  • erm there is no lib for image processor as well or image resizer – lel Aug 31 '17 at 06:48
  • I didn't understand what `there is no lib for ...` means but see the edit. – Emad Aug 31 '17 at 06:56
  • oh I paste the codes in and they cannot find what is ImageFactory, ResizeMode and path... – lel Aug 31 '17 at 06:59
  • Right click the project, select `Manage nuget packages` search for ImageProcessor. Click install. Add `using ImageProcessor;` and `using ImageProcessor.Imaging;` to the file where you paste my code. – Emad Aug 31 '17 at 07:04
  • ImageProcessor is external third party library.you need to accept the terms and condtions to use the library.http://www.apache.org/licenses/LICENSE-2.0 – Jagadeesh Govindaraj Aug 31 '17 at 07:09
  • Yes there are other libraries with different licences – Emad Aug 31 '17 at 07:16
  • After i run the codes there still error though. But it's okay now i found other answer but thank you for you time @Emad – lel Aug 31 '17 at 07:53