Image (BITMAP) for String

Asked

Viewed 133 times

-1

I have never worked with anything like this and would like to insert an image into a database and for what I saw the best way is to transform an image into a string, I have searched and found some ways but I was blocked. And the only way I have to store images is in a folder outside the database, but then as I intend to do a gallery has no way to filter the images through Cartype.

Inserir imagem (View)

Controller

Model

Insert

public ActionResult Insert(Cars cars, HttpPostedFileBase photo)
    {
        string directory = @"~\Images";


        if (ModelState.IsValid)
        {

            int recordsCreated = CreateCar(
                         cars.Brand,
                         cars.Model,
                         cars.CarType,
                         cars.PlateDate,
                         cars.Image);
        }
        if (photo != null && photo.ContentLength > 0)
        {

            var fileName = Path.GetFileName(photo.FileName);
            photo.SaveAs(Path.Combine(directory, fileName));
            return RedirectToAction("../Rent/Gallery");
        }
        return View();


    }
  • 4

    Talk buddy, all right? Welcome to SOPT! When asking a question here on the site, prefer to post your code instead of making the images available. This way we can help you more efficiently and your question will be evaluated more positively. Refactor your question by placing your codes and just leave the images of the screens if it’s really relevant to the question, okay? Hug!

  • Use a MemoryStream to create a byte[] from the image and then save this byte[] in the database as a blob.

1 answer

0


You can try converting to a Base64 string, in this case try this :

using (Image image = Image.FromFile(Path))
{
    using (MemoryStream m = new MemoryStream())
    {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        return base64String;
    }
}

Browser other questions tagged

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