我在将图像转换为 Base64 字符串并将其作为字符串保存在数据库中时遇到问题,但它什么也不返回。Base64Text 是全局变量,变量也不为空我用按钮测试它来填充文本框,它只是保存为“”到数据库中。
这是数据库中表的模型
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
public double ProductPrice { get; set; }
public int ProductAmount { get; set; }
public string ProductImage { get; set; } // Used for storing image string
public int userID { get; set; }
}
// Here is image converter
private void btnAddImage_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image Files(*.BMP;*.JPG;*.PNG;*.JPEG)|*.BMP;*.JPG;*.PNG;*.JPEG" +
"|All files(*.*)|*.*";
dialog.CheckFileExists = true;
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
var image = new Bitmap(dialog.FileName);
pictureBoxProductImage.Show();
pictureBoxProductImage.Image = (Image)image;
byte[] imageArray = System.IO.File.ReadAllBytes(dialog.FileName);
base64Text = Convert.ToBase64String(imageArray);
}
}
// Here is saving image using Entity framework
private void btnAddProduct_Click(object sender, EventArgs e)
{
string imagePath = base64Text;
if (txtBoxProductName.Text == null || txtBoxProductPrice.Text == null || txtBoxProductQuantity.Text == null || imagePath == null || imagePath == "")
{
MessageBox.Show("Please fill required information!", "", MessageBoxButtons.OK);
}
else
{
model.ProductName = txtBoxProductName.Text;
model.ProductPrice = Convert.ToDouble(txtBoxProductPrice.Text);
model.ProductAmount = Convert.ToInt32(txtBoxProductQuantity.Text);
model.ProductImage = imagePath;
model.userID = id;
using (var context = new ProductContext())
{
context.Products.Add(model);
context.SaveChanges();
}
MessageBox.Show("Product sucesffuly added to database!", "", MessageBoxButtons.OK);
Clear();
}
}