blog-details

Hàm Resize hình ảnh sử dụng .NET C# và MVC

public bool SaveResizeImage(Image img, int width, string path)
        {
            try
            {
                // lấy chiều rộng và chiều cao ban đầu của ảnh
                int originalW = img.Width;
                int originalH = img.Height;
                // lấy chiều rộng và chiều cao mới tương ứng với chiều rộng truyền vào của ảnh (nó sẽ giúp ảnh của chúng ta sau khi resize vần giứ được độ cân đối của tấm ảnh
                int resizedW = width;
                int resizedH = (originalH * resizedW) / originalW;
                Bitmap b = new Bitmap(resizedW, resizedH);
                Graphics g = Graphics.FromImage((Image)b);
                g.InterpolationMode = InterpolationMode.Bicubic;    // Specify here
                g.DrawImage(img, 0, 0, resizedW, resizedH);
                g.Dispose();
                b.Save(path);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }

        }

Giải thích các tham số

Ở hàm trên chúng ta cần truyền vào các tham số:

  • img : Tham số này có kiểu dữ liệu System.Drawing.Image là hình ảnh truyền vào để resize
  • width: Kích thước chiều rộng cần để resize hình ảnh, chiều cao của hình sẽ được tự động tính để đảm bảo tỉ lệ của bức ảnh sau khi resize chính xác.
  • path: Đường dẫn lưu hình ảnh sau khi resize.

Code demo Upload và Resize hình ảnh ASP.NET C# MVC.

1. Tạo View để hiển thị Form Upload

Để sử dụng hàm resize các bạn thực hiện như sau, ở đây mình lấy demo sử dụng MVC 4 với View Razor.

Đầu tiên tạo Một Controller tại Controller/HomeController.cs với nội dung sau.

System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Atcsmart.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            ViewBag.Error = TempData["e"] == null ? "" : TempData["e"].ToString();
            ViewBag.Files = TempData["file"] ==null ? new List<string>() : (List<string>)TempData["file"];
            return View();
        }

    }
}

Controller này có chức năng nhận request và trả về trang chứa form Upload của chúng ta.

Tiếp theo mình tạo Một View /Views/Home/Index.cshtml như sau với mã HTML tạo một form upload hình:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Demo upload và resize hình ảnh</title>
</head>
<body>
    <h1>Upload và Resize hình ảnh</h1>
    @if (!string.IsNullOrEmpty(ViewBag.Error)) { 
        <div>
            @Html.Raw(ViewBag.Error)
        </div>
    }
    @if (ViewBag.Files!=null) { 
        <ul>
            @foreach (var file in ViewBag.Files) { 
                <li>@Html.Raw(file)</li>
            }
        </ul>
    }
    <div>
        @using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
        { 
            <p>Chọn file upload: <input type="file" name="file"/></p>
            <p>Kích thước cần resize: @Html.TextBox("size", "", new  { @type="number", min="10"})</p>
            <p><button type="submit">Upload và resize hình</button></p>
        }
    </div>
</body>
</html>

Ta sẽ được một form như sau:

resize-hinh-asp-mvc

2. Tạo Controller xử lý upload Resize hình ảnh.

Các bạn tạo một controller để xử lý upload tại Controller/FileController.cs như sau:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Atcsmart.Controllers
{
    public class FileController : Controller
    {
        //
        // GET: /File/
        [HttpPost]
        public ActionResult Upload(FormCollection fc)
        {

            string size = fc["size"];
            int sizeResize = 200;
            if (!string.IsNullOrEmpty(size)) {
                int.TryParse(size, out sizeResize);
            }
            
            List<string> fileNames = new List<string>();
            try
            {
                // Duyệt qua các file được gởi lên phía client
                foreach (string fileName in Request.Files)
                {
                    //Lấy ra file trong list các file gởi lên
                    HttpPostedFileBase file = Request.Files[fileName];
                    //Save file content goes here

                    if (file != null && file.ContentLength > 0)
                    {
                        //Định nghĩa đường dẫn lưu file trên server
                        //ở đây mình lưu tại đường dẫn yourdomain.com/Uploads/
                        var originalDirectory = new DirectoryInfo(string.Format("{0}Uploads\\", Server.MapPath(@"\")));
                        //Lưu trữ hình ảnh theo từng tháng trong năm
                        string pathString = System.IO.Path.Combine(originalDirectory.ToString(), DateTime.Now.ToString("yyyy-MM"));
                        bool isExists = System.IO.Directory.Exists(pathString);
                        if (!isExists) System.IO.Directory.CreateDirectory(pathString);
                        var path = string.Format("{0}\\{1}", pathString, file.FileName);
                        string newFileName = file.FileName;
                        //lấy đường dẫn lưu file sau khi kiểm tra tên file trên server có tồn tại hay không
                        var newPath = GetNewPathForDupes(path, ref newFileName);
                        string serverPath = string.Format("/{0}/{1}/{2}", "Uploads", DateTime.Now.ToString("yyyy-MM"), newFileName);
                        //Lưu hình ảnh Resize từ file sử dụng file.InputStream
                        SaveResizeImage(Image.FromStream(file.InputStream), sizeResize, newPath);
                        fileNames.Add("LocalPath: "+newPath + "<br/>ServerPath: "+serverPath);
                    }
                }
            }
            catch (Exception ex)
            {
                TempData["e"] = ex.Message;
            }
            TempData["file"] = fileNames;
            return RedirectToAction("Index","Home");
            
        }
        //Hàm resize hình ảnh

        public bool SaveResizeImage(Image img, int width, string path)
        {
            try
            {
                // lấy chiều rộng và chiều cao ban đầu của ảnh
                int originalW = img.Width;
                int originalH = img.Height;
                // lấy chiều rộng và chiều cao mới tương ứng với chiều rộng truyền vào của ảnh (nó sẽ giúp ảnh của chúng ta sau khi resize vần giứ được độ cân đối của tấm ảnh
                int resizedW = width;
                int resizedH = (originalH * resizedW) / originalW;
                Bitmap b = new Bitmap(resizedW, resizedH);
                Graphics g = Graphics.FromImage((Image)b);
                g.InterpolationMode = InterpolationMode.Bicubic;    // Specify here
                g.DrawImage(img, 0, 0, resizedW, resizedH);
                g.Dispose();
                b.Save(path);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }

        }
        private string GetNewPathForDupes(string path, ref string fn)
        {
            string directory = Path.GetDirectoryName(path);
            string filename = Path.GetFileNameWithoutExtension(path);
            string extension = Path.GetExtension(path);
            int counter = 1;
            string newFullPath = path;
            string new_file_name = filename + extension;
            while (System.IO.File.Exists(newFullPath))
            {
                string newFilename = string.Format("{0}({1}){2}", filename, counter, extension);
                new_file_name = newFilename;
                newFullPath = Path.Combine(directory, newFilename);
                counter++;
            };
            fn = new_file_name;
            return newFullPath;
        }

    }
}

Bây giờ các bạn có thể chạy và kiểm tra chức năng upload và resize hình ảnh.

Chúc các bạn thành công !

Free Down Ads –  Tải về

Đánh giá bài viết