1

How can i create database using EF with info and picture as column in db? Also I need to upload image into local db. I started building app with Microsoft's tutorial where you upload "movie". https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/start-mvc?tabs=aspnetcore2x How can i show some photo from db even hardcoded like in example like this (SeedData.cs)?

2 Answers2

3

Your Image Model Class :

        public class YourImageModel
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
            public byte[] Image { get; set; }
         }

In the Controller :

public async Task<IActionResult> UploadImage(YourImageModel yourImageModel, IFormFile imageToBeUploaded)
                {
                    if (!ModelState.IsValid)
                    {
                        return View(yourImageModel);
                    }

                   if (imageToBeUploaded != null)
                   {
                      using (var memoryStream = new MemoryStream())
                      {
                        await imageToBeUploaded.CopyToAsync(memoryStream);
                        var imageToBeUploadedByteArray = memoryStream.ToArray();
                        yourImageModel.Image= imageToBeUploadedByteArray ;
                      }
                    }

                    _dbContext.YourImageModel.Add(yourImageModel)
                    await _dbContext.SaveChangesAsync();
                    return View();
                }
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
0

your question is very broad but I will attempt to answer the main points. for creating a table to store the image you need an entity like:

public class ImageEntity
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string ImageInfo { get; set; }
        public byte[] Image { get; set; }
    }

to upload your image you need to convert it to a byte[] first then it is the same as adding any object to a table once its in the right format. to convert the to a byte[] you can use something like

public byte[] BitmapToByteArray(Bitmap image)
    {
        //converts bitmap to byteArray
        byte[] byteArray;
        using (MemoryStream memoryStream = new MemoryStream())
        {
            image.Compress(Bitmap.CompressFormat.Png, 0, memoryStream);
            byteArray = memoryStream.ToArray();
        }
        return byteArray;
    }
Kevin
  • 2,258
  • 1
  • 32
  • 40