如何在 Windows Form Application with Dapper 中直接从 PictureBox 保存图像而不使用 Dapper 的存储过程?

How to save the image directly from PictureBox without stored procedure with Dapper in Windows Form Application with Dapper?

之前用存储过程把pic保存到db,现在想不用存储过程保存 可以直接从 PictureBox?

保存吗
private void buttonsave_Click(object sender, EventArgs e)
{
    Categoryentity categoryentity = new Categoryentity();
    categoryentity.CategoryName = texboxcatname.Text;
    categoryentity.Description = textBoxcatdesc.Text;
    categoryentity.Picture = pictureBox1.Image;
    Dbclass dbclass = new Dbclass();

    long result = dbclass.insertcategory(categoryentity);
    if (result > 0)
    {
        MessageBox.Show("inserted");
    }
    else
    {
        MessageBox.Show("failed");
    }
}

private void buttonuploadpic_Click(object sender, EventArgs e)
{
    //string imagelocation = "";
    //try
    //{
    OpenFileDialog fdialog = new OpenFileDialog();
    fdialog.Filter = "jpg files(*.jpg)|*.jpg| PNG files(*.png)|*.png| All Files(*.*)|*.*";

    if (fdialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        imagelocation = fdialog.FileName.ToString();
        pictureBox1.ImageLocation = imagelocation;
    }
}

实体class

using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper.Contrib.Extensions;

namespace Northwind.Entities
{
    [Table ("Categories")]
  public   class Categoryentity
    {

        public int CategoryID { get; set; }

        public string CategoryName { get; set; }

        public string Description { get; set; }

        public string Pic { get; set; }

        public Image Picture { get; set; }

插入fn

 public class Dbclass
    {
       
        public long insertcategory(Categoryentity categoryentity)
        {
            using (var connection = DBLayer.ConnectionFactory())
            {
                long id = connection.Insert<Categoryentity>(categoryentity);
                return id;

            }
        }

我可以上传图片,但我不知道如何正确插入。但是我在使用存储过程的时候,插入成功了

上一个存储过程

byte[] images = null;
FileStream fileStream = new FileStream(imagelocation, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
images = binaryReader.ReadBytes((int)fileStream.Length);

Dbclass dbclass = new Dbclass();

string maincon = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(maincon);

sqlcon.Open();
string query = "insert into Categories(CategoryName,Description,Picture) Values ('" + texboxcatname.Text + "','" + textBoxcatdesc.Text + "',@images)";

SqlCommand sqlCommand = new SqlCommand(query, sqlcon);
sqlCommand.Parameters.Add(new SqlParameter("@images", images));
int N = sqlCommand.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("saved");

您可以使用 https://www.nuget.org/packages/Dapper.Contrib/.

然后使用下面的代码插入记录

Categoryentity obj = new Categoryentity ();
...
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
    conn.Open();
    return conn.Insert(obj) ;
}

直接将picturebox图片插入数据table,从数据table中读取图片到picturebox,可以参考下面的代码试试

using Dapper.Contrib.Extensions;
using System;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace insertimage
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Add();
            MessageBox.Show("saved");
        }
        internal void Add()
        {
            string constr = @"constr";
            SqlConnection con = new SqlConnection(constr);
            string sqlinsert = "insert into  [dbo].[Category] ([Id],[Name],[Picture]) values (@Id,@Name,@Picture) ";
            con.Open();
            SqlCommand cmd = new SqlCommand(sqlinsert, con);
            byte[] b;
            Image img = pictureBox1.Image;
            using (MemoryStream mStream = new MemoryStream())
            {
                img.Save(mStream, img.RawFormat);
                b = mStream.ToArray();
            }
            cmd.Parameters.AddWithValue("@Id", texboxcatid.Text);
            cmd.Parameters.AddWithValue("@Name", textBoxcatdesc.Text);
            cmd.Parameters.AddWithValue("@Picture", b);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string constr = @"constr";
            SqlConnection con = new SqlConnection(constr);
            string sql = "select * from  [dbo].[Category]";
            con.Open();
            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataReader reader = cmd.ExecuteReader();
            byte[] by = null;
            while (reader.Read())
            {
                by = (byte[])reader[2];
            }
            Image img = byteArrayToImage(by);
            pictureBox2.Image = img;
        }
        public Image byteArrayToImage(byte[] bytesArr)
        {
            using (MemoryStream memstr = new MemoryStream(bytesArr))
            {
                Image img = Image.FromStream(memstr);
                return img;
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fdialog = new OpenFileDialog();
            fdialog.Filter = "jpg files(*.jpg)|*.jpg| PNG files(*.png)|*.png| All Files(*.*)|*.*";

            if (fdialog.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(fdialog.FileName, FileMode.Open, FileAccess.Read);
                Image im = Image.FromStream(fs);
                pictureBox1.Image = im;
            }
        }
    }
    [Table("Category")]
    public class Category
    {
        [Key]
        public int Id { get; set; }

        public string Name { get; set; }

        public Image Picture { get; set; }
    }
}

结果:

我们可以使用这段代码从图片框中插入图片

在此之前将实体 class 上的图像类型声明为 byte[]。

按钮保存操作

 private void buttonSavemp_Click(object sender, EventArgs e)
        {
 empentity.PhotoPath = textBoxphotopath.Text;

            Image image = pictureBoxphoto.Image;
            byte[] data;
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                data = ms.ToArray();
            }

            empentity.Photo = data;
     Dbclass dbclass = new Dbclass();
            long result = dbclass.insertpicture(empentity);

            if (result > 0)
            {
                MessageBox.Show("inserted succesfully");
            }
            else
            {
                MessageBox.Show("insertion failed");
            }

我们可以使用下面的代码获取图片

 System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
                Image image = (Image)imageConverter.ConvertFrom(employeentity.Photo);
                pictureBoxphoto.Image = image;