在 WPF 中 ImageBox.Source == null 时无法保存 SQLİte

Can't Save SQLİte while ImageBox.Source == null in WPF

我正在尝试将我的数据保存到 sqlite,而且我的数据有照片。 我想保存带照片或不带照片的数据。 当我添加照片时,我可以将它保存到 sqlite。但是当 imagebox.Source 为空时,它给出错误:

'Operation is not valid due to the current state of the object.'

它在 :

中显示错误
public byte[] BitmapSourceToByteArray(BitmapSource image)
{
    using (var stream = new MemoryStream())
    {
        var encoder = new PngBitmapEncoder(); // or some other encoder
        encoder.Frames.Add(BitmapFrame.Create(image));
        encoder.Save(stream);
        return stream.ToArray();
    }
}

这是我的代码:

    private void SaveButton_OnClick(object sender, RoutedEventArgs e)
    {
            BitmapImage image = new BitmapImage();

            if (ImageBox.Source != null)
            {
                image.BeginInit();
                image.UriSource = new Uri(filephoto.FileName);
                image.EndInit();
                ImageBox.Source = image;
            }

            helper.DataSave("CompanyData", CInfo, image);
       }

在助手 class、DataSave 中;

    public bool DataSave(string TableName, CustomerInfo CInfox, BitmapImage obj) // Save to DataBase
    {
        //try
        //{
            ConOpen();
            string query = $"Insert Into {TableName} (Company, Product, Product_No, Product_Size, Photo) Values (@company, @product, @pno, @psize, @photo)";
            SQLiteCommand komut = new SQLiteCommand(query, connection);

            SQLiteParameter param1 = new SQLiteParameter("@company", DbType.String);
            SQLiteParameter param2 = new SQLiteParameter("@product", DbType.String);
            SQLiteParameter param3 = new SQLiteParameter("@pno",     DbType.String);
            SQLiteParameter param4 = new SQLiteParameter("@psize",   DbType.String);
            SQLiteParameter param5 = new SQLiteParameter("@photo",   DbType.Binary);

            param1.Value = CInfox.Customer;
            param2.Value = CInfox.Product;
            param3.Value = CInfox.ProductNo;
            param4.Value = CInfox.ProductSize;
            param5.Value = BitmapSourceToByteArray(obj);


            komut.Parameters.Add(param1);
            komut.Parameters.Add(param2);
            komut.Parameters.Add(param3);
            komut.Parameters.Add(param4);
            komut.Parameters.Add(param5);

            komut.ExecuteNonQuery();
            MessageBox.Show("Saved Succesfully!");
            ConClose();
            return true;
    }

由于您的数据库将接受空值,您可能需要重构:

    public bool DataSave(string TableName, CustomerInfo CInfox, BitmapImage obj) // Save to DataBase
{
    try
    {
        ConOpen();
        string query = $"Insert Into {TableName} (Company, Product, Product_No, Product_Size) Values (@company, @product, @pno, @psize)";
        SQLiteCommand komut = new SQLiteCommand(query, connection);

        SQLiteParameter param1 = new SQLiteParameter("@company", DbType.String);
        SQLiteParameter param2 = new SQLiteParameter("@product", DbType.String);
        SQLiteParameter param3 = new SQLiteParameter("@pno",     DbType.String);
        SQLiteParameter param4 = new SQLiteParameter("@psize",   DbType.String);

        param1.Value = CInfox.Customer;
        param2.Value = CInfox.Product;
        param3.Value = CInfox.ProductNo;
        param4.Value = CInfox.ProductSize;

        komut.Parameters.Add(param1);
        komut.Parameters.Add(param2);
        komut.Parameters.Add(param3);
        komut.Parameters.Add(param4);

        if(obj is not null) // if(obj != null) for older C# versions
        {
            string query = $"Insert Into {TableName} (Company, Product, Product_No, Product_Size, Photo) Values (@company, @product, @pno, @psize, @photo)";
            SQLiteParameter param5 = new SQLiteParameter("@photo",   DbType.Binary);
            param5.Value = BitmapSourceToByteArray(obj);
            komut.Parameters.Add(param5);
        }

        komut.ExecuteNonQuery();
        MessageBox.Show("Saved Succesfully!");

   }
   catch(Exception)
   {
        // Handle exceptions here or let it bubble up to caller (You should use transactions)
   }
   finally
   {
        ConClose();
   }
        return true;
}

附加信息。图片转换助手

    internal static class SignatureImageConversion
{
    public static BitmapImage ConvertFileToBitmap(this string path)
    {
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        image.UriSource = new Uri(path);
        image.EndInit();
        return image; 
    }

    public static BitmapImage ConvertFileStreamToBitmap(this byte[] stream)
    {
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        image.StreamSource = new MemoryStream(stream);
        image.EndInit();
        return image; 
    }

    public static byte[] ConvertImageToByteArray(this BitmapImage image)
    {
        byte[] data = null; 
        JpegBitmapEncoder jpencoder = new JpegBitmapEncoder();
        jpencoder.Frames.Add(BitmapFrame.Create(image));
        using (MemoryStream ms = new MemoryStream())
        {
            jpencoder.Save(ms);
            data = ms.ToArray();
        }
        return data;
    }
}

最大大小有限制,默认为1000,如果要发布要反序列化的大数据,则需要增加它。

<appSettings>
  <add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
</appSettings>

Setting this attribute to too large a number can pose a security risk.