C# 点击按钮然后读取picturebox的内容为字节数组如果没有则是null 保存到sql的image字段
以下是一个示例代码,演示如何点击按钮并将PictureBox的内容保存为字节数组,并将其保存到SQL的image字段中:
// 假设pictureBox1是你的PictureBox控件
private void button1_Click(object sender, EventArgs e)
{
// 检查PictureBox是否有图像
if (pictureBox1.Image == null)
{
// 如果没有图像,设置字节数组为null
byte[] imageBytes = null;
}
else
{
// 如果有图像,将图像转换为字节数组
using (MemoryStream ms = new MemoryStream())
{
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
// 将字节数组保存到SQL的image字段
SaveToDatabase(imageBytes);
}
}
}
private void SaveToDatabase(byte[] imageBytes)
{
// 在此处编写保存到SQL的代码
// 假设你使用的是SQL Server数据库
string connectionString = "YourConnectionString";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO YourTableName (ImageColumn) VALUES (@Image)";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Image", imageBytes);
command.ExecuteNonQuery();
}
}
}
请根据你的实际情况修改代码中的数据库连接字符串和插入语句
原文地址: https://www.cveoy.top/t/topic/irSo 著作权归作者所有。请勿转载和采集!