Upload Image, and Create a Thumb of the same Asp.Net Mvc Image?

Asked

Viewed 282 times

2

I have a class called image, where I have two attributes, UrlDaImagem, and UrlDoThumb, I can save the image, normal only I would like to create a Thumb for that same image, without having to do a new upload.

Class:

public class Imagem
{
    [Key]
    public int ImagemId { get; set; }
    public string UrlDaImagem { get; set; }
    public string Thumb { get; set; }
}

Controller:

public ActionResult Create(Produto produto, 
                           List<int> IdCategoria, 
                           HttpPostedFileBase Arquivo)
{
    if (ModelState.IsValid)
    {
        #region Salvar Imagem
        Imagem img = new Imagem();
        string nomeDoArquivo = Path.GetFileNameWithoutExtension(Arquivo.FileName);
        string extensao = Path.GetExtension(Arquivo.FileName);
        nomeDoArquivo = nomeDoArquivo + DateTime.Now.ToString("yymmssffff") + extensao;

        img.UrlDaImagem = "~/Imagens/Produtos/" + nomeDoArquivo;
        using (var db = new Contexto())
        {
            db.ImagemDb.Add(img);
            db.SaveChanges();
            var id = img.ImagemId;
            produto.ImagemId = id;
        }
        nomeDoArquivo = Path.Combine(Server.MapPath("~/Imagens/Produtos/"),nomeDoArquivo);
        Arquivo.SaveAs(nomeDoArquivo);
        #endregion

        db.ProdutoDb.Add(produto);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

I wanted to save the original image, and create a thumb, save the thumb, and add the path of thumb at the bank

  • And what exactly is your doubt?

  • My doubt is how to create a Thumb, with the image that is already coming in Httppostfilebase, ie with only this image, I want to save it normal, and create a Thumb, to save in a folder, and only the path in the bank.

1 answer

3


Create a method with the following code referring to the question: https://stackoverflow.com/questions/27921/what-is-the-best-way-to-create-a-thumbnail-using-asp-net

using ( Image bigImage = new Bitmap( filename ) )
{
   int height = bigImage.Height / 10;
   int width = bigImage.Width / 10;
   using ( Image smallImage = image.GetThumbnailImage( width, 
                                                       height,
                                                       new 
   Image.GetThumbnailImageAbort(Abort), IntPtr.Zero) )
   {
      smallImage.Save("thumbnail.jpg", ImageFormat.Jpeg);
   }
}

where the filename is the file saved on disk.

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.