saving png image to the database

Anjali Agarwal 1,366 Reputation points
2023-03-24T01:13:31.4566667+00:00

I am trying to save a .png image to the database. I have a field in database called sign with type varbinary(max) and I have following in the Model:

public partial class EmployeeInfo

{

public int EmployeeInfoId { get; set; }

public byte[]? Sign { get; set; }

}

below is my view:

 <div class="form-group row">
         <div class="col">
                        <canvas width="500" height="400" id="signature"
                                style="border:1px solid black"></canvas><br>
                        <button type="button" id="accept"
                                class="btn btn-primary">
                            Accept signature
                        </button>
                        <br>
          </div><br />
         <input type="hidden" asp-for="SignatureDataUrl">
       </div>

SignaturedataURL is already getting saved in the database as you can see:

User's image

I want to save a .png image to the database. I have the following code in my controller:

string path = Path.GetTempPath();

        if (!String.IsNullOrWhiteSpace(employeeInfo.SignatureDataUrl))

        {

            var base64Signature = employeeInfo.SignatureDataUrl.Split(",")[1];

            var binarySignature = Convert.FromBase64String(base64Signature);

            System.IO.File.WriteAllBytes(@path + "\\Signature.png", binarySignature);

        }

Instead of saving Signature.png to this path, I want to save signature.png to the database field Sign[]. How can I save the .png to the database field "sign".

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,165 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,248 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,036 Reputation points
    2023-03-28T07:33:12.42+00:00

    See my article for saving an image to a database, there are three different versions, using EF Core, Dapper or SqlClient. Source code is done in Windows Forms but all the database code is in classes suitable for ASP.NET Core.

    Sample for EF Core

    using WorkingWithSqlServerImages.Data;
    using WorkingWithSqlServerImages.Models;
    
    namespace WorkingWithSqlServerImages.Classes;
    
    /// <summary>
    /// Operations performed by EF Core
    /// </summary>
    internal class EntityOperations
    {
        public static (PhotoContainer container, bool success) ReadImage(int identifier)
        {
            var photoContainer = new PhotoContainer() { Id = identifier };
            using var context = new Context();
    
            var item = context.Pictures1.FirstOrDefault(item => item.Id == identifier);
    
            if (item is null)
            {
                return (null, false);
            }
    
            var imageData = item.Photo;
    
            using (var ms = new MemoryStream(imageData, 0, imageData.Length))
            {
                ms.Write(imageData, 0, imageData.Length);
                photoContainer.Picture = Image.FromStream(ms, true);
            }
    
            return (photoContainer, true);
    
        }
    
        public static void InsertImage(byte[] imageBytes)
        {
    
            using var context = new Context();
    
            var photoContainer = new Pictures() { Photo = imageBytes };
            context.Add(photoContainer);
            context.SaveChanges();
    
        }
    }
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. 高阶懵逼 5 Reputation points
    2023-03-24T05:00:55.78+00:00

    hello friend.

    save binary to db may can

         
          byte[] byData=File.ReadAllBytes('abc.png')
          string str = "insert into EmployeeInfo (EmployeeInfoId,Sign) values('myId',@file)";
          SqlCommand mycomm = new SqlCommand(str, myconn);
          mycomm.Parameters.Add("@file", SqlDbType.Binary, byData.Length);
          mycomm.Parameters["@file"].Value = byData;
    

    more info you can read https://www.codeproject.com/Articles/32216/How-to-store-and-fetch-binary-data-into-a-file-str and https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/filestream-data

    good luck

    1 person found this answer helpful.
    0 comments No comments

  2. Tiny Wang-MSFT 1,571 Reputation points Microsoft Vendor
    2023-03-24T05:18:51.31+00:00

    Hi Anjali, we usually recommend saving images/files to a file server, or in like Azure Storage Blob in the cloud, then store the file path in the database.

    For small files, we can also store file into database by converting the file stream to a byte array like code below.

    using (var memoryStream = new MemoryStream())
        {
            await FileUpload.FormFile.CopyToAsync(memoryStream);
    
            // Upload the file if less than 2 MB
            if (memoryStream.Length < 2097152)
            {
                var file = new AppFile()
                {
                    Content = memoryStream.ToArray()
                };
    
                _dbContext.File.Add(file);
    
                await _dbContext.SaveChangesAsync();
            }
            else
            {
                ModelState.AddModelError("File", "The file is too large.");
            }
        }
    
    

    I also found a way using ef core to store byte array into database. In your scenario, you had field Sign in your table, let's assume you had another property named SignName. Using ef core, then you need to have a model and use it to store data like below.

    public class SignData
    {
        public string SignName { get; set; }
        public byte[] Sign { get; set; }
    }
    
    var binarySignature = Convert.FromBase64String(base64Signature);
    SignData sign = new SignData{
    	SignName = "sign1",
    	Sign = binarySignature
    }
    _dbContext.SignData.Add(sign);
    
    1 person found this answer helpful.
    0 comments No comments