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();
    }
}
MaFa
  • 15
  • 5

2 Answers2

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();
}
Vytautas Plečkaitis
  • 851
  • 1
  • 13
  • 19
  • a question please ... now how can I load this image from the database and save it to a hard drive? – MaFa Jul 03 '19 at 09:06
  • 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. – Vytautas Plečkaitis Jul 03 '19 at 10:41
  • Sample here https://stackoverflow.com/questions/35804375/how-do-i-save-a-bitmapimage-from-memory-into-a-file-in-wpf-c – Vytautas Plečkaitis Jul 03 '19 at 10:49
  • 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 – MaFa Jul 05 '19 at 08:52
  • 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); } – Vytautas Plečkaitis Jul 05 '19 at 10:16
-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();
    }
Colonel Software
  • 1,401
  • 1
  • 11
  • 16
  • That's not WPF, but WinForms. The method name `ConvertBitmapImagetoByte` with `BitmapImage` is at least misleading, if not wrong at all. – Clemens Jul 03 '19 at 07:57
  • Fine. Still this is not the way you do it in WPF. – Clemens Jul 03 '19 at 07:59
  • 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. – Clemens Jul 03 '19 at 08:01
  • Ok, but in my example, i was further using bitmap object. So i convert it to bitmap first :) – Colonel Software Jul 03 '19 at 08:03
  • 1
    Maybe, but you are completely ignoring the fact that OP already has a WPF `BitmapImage`. – Clemens Jul 03 '19 at 08:04