0

I want to add an image to the database in an image column in byte form I am using SQLite to save my database data and WPF Application using dbContext c# to write my code

can anyone help me please?

private void ChooseImageButtonClick(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

    dlg.Filter = "Choose Image(*.JPG;*.PNG;*.GIF)|*.jpg;*.png;*.gif";

    if (dlg.ShowDialog() == true)
    {
        string FileName = dlg.FileName.ToString();
        BitmapImage bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.UriSource = new Uri(FileName);
        bitmap.EndInit();
        ImageBox.Source = bitmap;
    }
}

private void savebtnClick(object sender, RoutedEventArgs e)
{
    using (DatabaseContext dbContext = new DatabaseContext())
    {
            Person p = new Person
            {
                Id = int.Parse(Idtextbox.Text),
                Name = Nametextbox.Text,
                Image = image
            };
        dbContext.Person.Add(p);
        dbContext.SaveChanges();
        RefreshList();
    }
}

2 Answers 2

2

Just convert BitmapImage to byte array first

byte[] image;

JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;

using (MemoryStream ms = new MemoryStream())
{
    encoder.Frames.Add(BitmapFrame.Create((BitmapSource)ImageBox.Source));
    encoder.Save(ms);
    image = ms.ToArray();
}
encoder = null;

And in your database context - add

using (DatabaseContext dbContext = new DatabaseContext())
        {
            Part part = new Part();
            part.Id = int.Parse(TextBoxID.Text);
            part.Name = TextBoxName.Text;
            part.Image = image;
            dbContext.Part.Add(part);
            dbContext.SaveChanges();
            RefreshPartsList();
        }}

To convert byte array back to BitmapImage :

byte[] imageData = part.Image; // that you get from db
if (imageData == null || imageData.Length == 0) 
   {
   //Show error msg or return here;
   return;
   }

var image = new BitmapImage();

 using (var ms = new System.IO.MemoryStream(imageData))
{
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad; 
    image.StreamSource = ms;
    image.EndInit();
    image.Freeze();
}
Sign up to request clarification or add additional context in comments.

5 Comments

a question please ... now how can I load this image from the database and save it to a hard drive?
Updated answer, so you know how to convert byte array back to bitmap image. There are a lot of ways to save that bitmap image as file afterwards.
can you help me please how to merge your last convert Code (byte to BitmapImage ) in a save button to save the image directly from database to a special folder. I tried a lot but did not get a result . i created a SaveFileDialog
BitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(image)); using (var fileStream = new System.IO.FileStream(SaveFileDialog.Filename, System.IO.FileMode.Create)) { encoder.Save(fileStream); }
-1

Add Property in 'Part' class

public byte[] ImageCol { get; set; }

Then from "OpenFileDialog" create Image from selected file. For Example

OpenFileDialog openFileDialog = new OpenFileDialog
        {
            Filter = "Image Files(*.BMP;*.JPG;*.JPEG;*.GIF;*.PNG)|*.BMP;*.JPG;*.JPEG;*.GIF;*.PNG",
            InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        };
        if (openFileDialog.ShowDialog()==DialogResult.OK)
        {
            var imageFromFile = System.Drawing.Image.FromFile(openFileDialog.FileName);
            part.ImageCol = imageFromFile.ConvertBitmapImagetoBytes();
        }

Convert BitMap to byte[]

public static byte[] ConvertBitmapImagetoBytes(this Image image)
    {
        MemoryStream ms = new MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        return ms.ToArray();
    }

5 Comments

That's not WPF, but WinForms. The method name ConvertBitmapImagetoByte with BitmapImage is at least misleading, if not wrong at all.
Fine. Still this is not the way you do it in WPF.
That said, in your sample it makes no sense to create a bitmap at all. You only want to get the image bytes from a file, so part.ImageCol = File.ReadAllBytes(openFileDialog.FileName); should be sufficient.
Ok, but in my example, i was further using bitmap object. So i convert it to bitmap first :)
Maybe, but you are completely ignoring the fact that OP already has a WPF BitmapImage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.