resize an image and then save to mysql

Asked

Viewed 179 times

1

From a form I want to resize an image only after and then save in mysql, or take an image already saved in mysql and resize it and then update the record. I really appreciate it if someone can help me.

* the table in mysql *

CREATE TABLE `imagemedias` (
  `id` int(11) NOT NULL,
  `imagem` mediumblob,
  `ImagemMimeType` varchar(20) DEFAULT NULL
)

*here is the class *

namespace rsi.Entities
{
    public class ImageMedia : Auxiliar
    {
        public int Id { get; set; }       
        public byte[] Imagem { get; set; }
        public string ImagemMimeType { get; set; }        
    }
}

* here is the form *

<form action="/backend/Images/imagem" method="post" name="form" id="form1" accept-charset="utf-8" enctype="multipart/form-data">
    <input type="file" name="__file"  id="__file" accept="image/*">
    <input type="submit">
</form>

*here is the controller *

[HttpPost]
public ActionResult imagem(HttpPostedFileBase file)
{
    if (file != null)
    {
        ImageMedia imagem = new ImageMedia();
        imagem.Imagem = new byte[file.ContentLength];
        imagem.ImagemMimeType = file.ContentType;
        file.InputStream.Read(imagem.Imagem, 0, file.ContentLength);

        return RedirectToAction("Exibir", new { imagem.Id });
    }

    return null;
}

1 answer

0

There’s a package for that, but I guess it’s not what you want. There’s another way to do it that’s simpler, using WebImage, but the quality is lower.

Example:

using System.Web.Helpers;

[HttpPost]
public ActionResult imagem(HttpPostedFileBase file)
{
    if (file != null)
    {
        ImageMedia imagem = new ImageMedia();
        imagem.Imagem = new byte[file.ContentLength];
        imagem.ImagemMimeType = file.ContentType;
        file.InputStream.Read(imagem.Imagem, 0, file.ContentLength);

        WebImage webimg = new WebImage(file.InputStream);
        webimg.Resize(100, 100); // Mude pro que você precisar
        // Escreva o resto da lógica para salvar aqui

        return RedirectToAction("Exibir", new { imagem.Id });
    }

    return View(); // Aquele null estava bem errado.
}

To get a stream:

var stream = new MemoryStream(webimg.GetBytes());
  • Thanks for the reply! I even used Webimage to resize the image, but then I don’t know how to save the result of this resizing in mysql, because Webimage doesn’t have the properties of Httppostedfilebase that I use to save to mysq (for example, "Inputstream.Read").

  • 1

    There is. See my edition.

  • Hello Gypsy, many thanks for your attention, but I confess that I could not save the resulting "stream" in mysql database, I believe I need to transform the resized image again in Httppostedfilebase, but I do not know how to do.

  • @Lucas Create another question explaining what you are doing to save to database.

Browser other questions tagged

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