简体   繁体   中英

How can I add an image in my database sqlite using dbContext WPF c#?

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();
    }
}

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();
}

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM