简体   繁体   中英

asp.net mvc on upload make thumb image

On image upload I want to make copy of that image save with different name and resize dimensions.

[HttpPost]
public ActionResult Create(HttpPostedFileBase photo)
{
    string path =  System.Configuration.ConfigurationManager.AppSettings["propertyPhotoPath"].ToString(); 
    if ((photo != null) && (photo.ContentLength > 0))
    {
        var fileName = Path.GetFileName(photo.FileName);
        var pathToSaveOnHdd = Path.Combine(Server.MapPath(path), fileName);
        string dbPhotoPath = string.Format("{0}{1}", path, fileName);
    }
... 
//        to do: make image copy, change dimensions
}

To copy a file you could use the File.Copy method. To resize an image, there are many techniques including GDI+, WIC, WPF (here's an example in a similar post ) or a NuGet such as ImageResizer .

You can convert the uploaded file into byte from the ActionController and change the size of stream as shown below

Byte[] image1 = new Byte[photo.ContentLength - 1]; HttpPostedFileBase file = photo.PostedFile; file.InputStream.Read(image1, 0, file.ContentLength - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(image1);

and you can use the graphic class to redraw the image with the desired size as shown below System.Drawing.Image image = Image.FromStream(ms);

Graphic graphic = Graphics.FromImage(image); graphic.DrawImage(image, 0, 0, image.Width, image.Height);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM