0

I am trying to save an image into my database using the following method

        public string ImageToBase64(Image image, ImageFormat format)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            // Convert Image to byte[]
            image.Save(ms, format);
            byte[] imageBytes = ms.ToArray();

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

public Image Base64ToImage(string base64String)
    {
        // Convert Base64 String to byte[]
        byte[] imageBytes = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

        // Convert byte[] to Image
        ms.Write(imageBytes, 0, imageBytes.Length);
        Image image = Image.FromStream(ms, true);
        return image;
    }

I am saving it into the follow object,

public class MediaImage
{
    [Key]
    public Guid Id { get; set; }
    [Column(TypeName = "varchar(MAX)")]
    public string Image { get; set; }
    public string ContentType { get; set; }
}

When I step through it the Base64ToImage is working (I am able to copy/paste the string back into the image).

However when I save the MediaImage object to the database the Image field is NULL even though it had a value prior to saving into the database.

As far as I can see there is no exception being thrown. I am not sure if my data type is incorrect?

devfunkd
  • 3,164
  • 12
  • 45
  • 73

2 Answers2

0

Depending on the size of your images/version of MSSQL you should select your data type from the Binary Strings list ... https://msdn.microsoft.com/en-GB/library/ms187752.aspx

But! before you do that ... read this because sometimes storing images in the DB is not the best option ... https://stackoverflow.com/a/5613926/5040941

Community
  • 1
  • 1
0

The issue was I had used the wrong data type, changing it to a byte array solved it for me. Found the answer on this SO question, it's not marked as the answer but looking the answer Cosmin Onea provided I was able to figure it out.

How to store images using Entity Framework Code First CTP 5?

public class Product
{
    public int Id { get; private set; }

    public string Name { get; set; }

    public byte[] ProductImage { get; set; }
}

That is pretty much it. If you don't map the property the convention is it maps to a varbinary(max). If you have an image column in the database already just add [Column(TypeName = "image")] on the ProductImage property or if you prefer code mapping add this to your OnModelCreating override in the context class:

modelBuilder.Entity<Product>().Property(p => p.Image).HasColumnType("image");
Community
  • 1
  • 1
devfunkd
  • 3,164
  • 12
  • 45
  • 73