"C# 读取 PictureBox 图片为字节数组并保存到 SQL 数据库"\n\n本文演示如何使用 C# 读取 PictureBox 的图片为字节数组,并在图片存在的情况下将其保存到 SQL 数据库的 image 字段中。\n\n\ncsharp\n// 读取 PictureBox 的图片为字节数组\nbyte[] imageBytes = null;\nif (pictureBox.Image != null)\n{\n using (MemoryStream ms = new MemoryStream())\n {\n pictureBox.Image.Save(ms, ImageFormat.Jpeg); // 可根据实际情况选择图片格式\n imageBytes = ms.ToArray();\n }\n}\n\n// 将字节数组保存到 SQL 数据库的 image 字段中\nstring connectionString = \"YourConnectionString\";\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\n connection.Open();\n \n SqlCommand command = new SqlCommand(\"INSERT INTO YourTable (ImageColumn) VALUES (@Image)\", connection);\n command.Parameters.AddWithValue(@\"Image\", imageBytes ?? (object)DBNull.Value);\n \n command.ExecuteNonQuery();\n}\n\n\n在上述代码中,首先判断 PictureBox 的 Image 属性是否为 null,如果不为 null,则将图片保存为字节数组。然后使用 SqlConnection 连接到 SQL 数据库,并创建一个 SqlCommand 对象来执行插入操作。通过参数化查询,将字节数组作为参数传递给 SQL 语句中的 image 字段。最后调用 ExecuteNonQuery 方法来执行插入操作。\n\n请注意,上述代码中的 "YourConnectionString" 和 "YourTable" 需要根据实际情况进行替换。

C# 读取 PictureBox 图片为字节数组并保存到 SQL 数据库

原文地址: https://www.cveoy.top/t/topic/p9r4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录