首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c#将图片存储到数据库

c#将图片存储到数据库
EN

Stack Overflow用户
提问于 2011-05-11 16:03:50
回答 1查看 956关注 0票数 1

我无法将图片插入database.This是我的示例代码。我可以从我的计算机中选择图像并显示在图片box.Once中。我尝试将图片框中显示的图像存储到数据库中,它显示对象引用未设置为对象的实例。

这是我的示例代码。

代码语言:javascript
复制
          namespace picutre_storage
     {
        public partial class Form1 : Form
        {
         public Form1()
      {
        InitializeComponent();
       }

    private void button2_Click(object sender, EventArgs e)
    {
        try
        {

            SqlConnection con = new SqlConnection
                           (@"User ID=sa;Password=password123;Initial Catalog=picuture;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
            //I have used a table named "tblUsers" and fill the fields
            SqlCommand cmd = new SqlCommand("INSERT INTO BLOBTest (BLOBData) VALUES (@BLOBData)", con);

            //Save image from PictureBox into MemoryStream object.
            MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms,ImageFormat.Bmp);

            //Read from MemoryStream into Byte array.
            Byte[] bytBLOBData = new Byte[ms.Length];
            ms.Position = 0;
            ms.Read(bytBLOBData, 0, Convert.ToInt32(ms.Length));

            //Create parameter for insert statement that contains image.
            SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary,            bytBLOBData.Length, ParameterDirection.Input, false,
                            0, 0, null, DataRowVersion.Current, bytBLOBData);
            cmd.Parameters.Add(prm);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
        catch (Exception ex)
        { MessageBox.Show(""+ex); } 
    }

      private void button3_Click(object sender, EventArgs e)
       {
        try
        {
            //Getting The Image From The System
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
            if (open.ShowDialog() == DialogResult.OK)
            {
                pictureBox2.Image = new Bitmap(open.FileName);
            }
        }
        catch (Exception)
        {
            throw new ApplicationException("Failed loading image");
        }
    }

2.在图片box.Thank中显示图片之前,有任何方法可以检查图片的大小

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-05-11 16:50:37

在我看到的东西上,你将一个文件保存为bmp格式,最初图片以jpeg或tiff格式存在,所以记录被正确插入,但图片引用的是bmp格式类型,它不存在。我想你可以做这样的事情。

当你得到图片以任何你想要的格式,然后创建一个缩略图为这张图片存储在一个不同的文件夹中* jpg (像我的Pictures\Thumbnails)__.*

  • Get图片的扩展名,在创建期间用jpg替换这在Thumbnail.

  • Store database.

  • Retrieve中的缩略图在框中)。你想要的。

如果你想知道如何创建缩略图(将文件保存为JPG格式),那么非常欢迎。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5961071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档