winform中的picturebox控件显示和保存byte[]图片
winform中的picturebox控件显示和保存byte[]图片
完全是靠查百度“文心一言”来弄出来的,先把代码片段记下来,以后说不定什么时候会用到
窗体加载时picturebox控件显示从数据库中取出的byte[]图片
byte[] imageBytes = book?.BookCover; // 使用MemoryStream来读取byte[]中的数据 using (MemoryStream ms = new MemoryStream(imageBytes)) { // 从MemoryStream中加载Image Image image = Image.FromStream(ms); // 将Image对象赋值给PictureBox的Image属性 pictureBox1.Image = image; // (可选)设置PictureBox的SizeMode以适应图片 pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; }
点击按钮选择图片后显示在picturebox控件中:
private void btnOpenImage_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Image Files (*.jpg, *.jpeg, *.png, *.gif) | *.jpg; *.jpeg; *.png; *.gif"; if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; pictureBox1.Image = Image.FromFile(filePath); pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; // 或者其他你想要的显示模式 } }
保存时从picturebox控件中取出byte[]图片,再存到数据库中
byte[] imageBytes = null; // 检查PictureBox中是否有图片 if (pictureBox1.Image != null) { // 创建一个MemoryStream对象 using (MemoryStream memoryStream = new MemoryStream()) { // 将图片保存到MemoryStream中,这里假设你想要保存为JPEG格式 pictureBox1.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); // 将MemoryStream的位置设置为开始位置,以便读取数据 memoryStream.Position = 0; // 读取MemoryStream中的数据到byte数组中 imageBytes = memoryStream.ToArray(); // 现在你可以使用imageBytes数组了,比如保存到文件或发送到服务器等 // ... // 示例:将byte[]数组保存为文件 // File.WriteAllBytes("path_to_save_image.jpg", imageBytes); } } else { // 处理PictureBox中没有图片的情况 MessageBox.Show("PictureBox中没有图片"); }
撸码:复制、粘贴,拿起键盘就是“干”!!!
分类:
C# / Winform
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2018-06-04 百度地图-多个坐标点显示