Storing and Retrieving Images from SQL Server using Microsoft .NET

原文 Storing and Retrieving Images from SQL Server using Microsoft .NET

  • Download source - 19.6 Kb

Introduction

This article is about storing and retrieving images from database in Microsoft .NET using C#.

Tools Used

  • SQL Server 2000
  • Microsoft .NET Version 1.1
  • C# (Windows Forms based application)

Storing Images

  1. Create a table in a SQL Server 2000 database which has at least one field of type IMAGE.

    Here is the script I used:

     Collapse| Copy Code
    CREATE TABLE [dbo].[tblImgData] ([ID] [int] NOT NULL ,[Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[Picture] [image] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  2. Actually IMAGE field is just holding the reference to the page containing the binary data so we have to convert our image into bytes.
    1. I used a file open dialog box to locate the file.

       Collapse| Copy Code
      this.openFileDialog1.ShowDialog(this);
      string strFn=this.openFileDialog1.FileName;
    2. By using FileInfo class, I retrieved the file size:
       Collapse| Copy Code
      FileInfo fiImage=new FileInfo(strFn);
    3. Declare an array of that size.
       Collapse| Copy Code
      this.m_lImageFileLength=fiImage.Length;
      m_barrImg=new byte[Convert.ToInt32(this.m_lImageFileLength)];
    4. By using FileStream object, I filled the byte array.
       Collapse| Copy Code
      FileStream fs=new FileStream(strFn,FileMode.Open, FileAccess.Read,FileShare.Read);
      int iBytesRead=fs.Read(m_barrImg,0,Convert.ToInt32(this.m_lImageFileLength));
      fs.Close();

    Complete Load Image Code

     Collapse| Copy Code
    protected void LoadImage()
    {try{this.openFileDialog1.ShowDialog(this);string strFn=this.openFileDialog1.FileName;this.pictureBox1.Image=Image.FromFile(strFn);FileInfo fiImage=new FileInfo(strFn);this.m_lImageFileLength=fiImage.Length;FileStream fs=new FileStream(strFn,FileMode.Open, FileAccess.Read,FileShare.Read);m_barrImg=new byte[Convert.ToInt32(this.m_lImageFileLength)];int iBytesRead = fs.Read(m_barrImg,0, Convert.ToInt32(this.m_lImageFileLength));fs.Close();}catch(Exception ex){MessageBox.Show(ex.Message);}
    }
  3. Saving byte array data to database.
    1. Create command text to insert record.

       Collapse| Copy Code
      this.sqlCommand1.CommandText= "INSERT INTO tblImgData(ID,Name,Picture)" + " values(@ID,@Name,@Picture)";
    2. Create parameters.
       Collapse| Copy Code
      this.sqlCommand1.Parameters.Add("@ID",System.Data.SqlDbType.Int, 4);
      this.sqlCommand1.Parameters.Add("@Name", System.Data.SqlDbType.VarChar, 50);this.sqlCommand1.Parameters.Add("@Picture", System.Data.SqlDbType.Image);

      Notice “@Picture” has “SqlDbType.Image” because it is of IMAGE type Field.

    3. Provide the value to the parameters.
       Collapse| Copy Code
      this.sqlCommand1.Parameters["@ID"].Value=this.editID.Text;
      this.sqlCommand1.Parameters["@Name"].Value=this.editName.Text;this.sqlCommand1.Parameters["@Picture"].Value=this.m_barrImg;

      this.m_barrImg” is a byte array which we filled in the previous step.

    4. Now execute non-query for saving the record to the database.
       Collapse| Copy Code
      int iresult=this.sqlCommand1.ExecuteNonQuery();

    Complete Save Image Code

     Collapse| Copy Code
    private void btnSave_Click(object sender, System.EventArgs e)
    {try{this.sqlConnection1.Open();if (sqlCommand1.Parameters.Count ==0 ){this.sqlCommand1.CommandText="INSERT INTO tblImgData(ID," + " Name,Picture) values(@ID,@Name,@Picture)";this.sqlCommand1.Parameters.Add("@ID", System.Data.SqlDbType.Int,4);this.sqlCommand1.Parameters.Add("@Name", System.Data.SqlDbType.VarChar,50);this.sqlCommand1.Parameters.Add("@Picture", System.Data.SqlDbType.Image);}this.sqlCommand1.Parameters["@ID"].Value=this.editID.Text;this.sqlCommand1.Parameters["@Name"].Value=this.editName.Text;this.sqlCommand1.Parameters["@Picture"].Value=this.m_barrImg;int iresult=this.sqlCommand1.ExecuteNonQuery();MessageBox.Show(Convert.ToString(iresult));}catch(Exception ex){MessageBox.Show(ex.Message);}finally{this.sqlConnection1.Close();}
    }

Retrieving Image

Retrieving images from the database is the exact reverse process of saving images to the database.

  1. First create command text to retrieve record.

     Collapse| Copy Code
    SqlCommand cmdSelect = new SqlCommand("select Picture" + " from tblImgData where ID=@ID", this.sqlConnection1);
  2. Create parameter for the query.
     Collapse| Copy Code
    cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
  3. Provide value to the parameter.
     Collapse| Copy Code
    cmdSelect.Parameters["@ID"].Value=this.editID.Text;
  4. Open database connection and execute “ExecuteScalar” because we want only “IMAGE” column data back.
     Collapse| Copy Code
    byte[] barrImg=(byte[])cmdSelect.ExecuteScalar();

    As the execute scalar returns data of “Object” data type, we cast it to byte array.

  5. Save this data to a temporary file.
     Collapse| Copy Code
    string strfn=Convert.ToString(DateTime.Now.ToFileTime());
    FileStream fs=new FileStream(strfn,FileMode.CreateNew,FileAccess.Write);
    fs.Write(barrImg,0,barrImg.Length);
    fs.Flush();
    fs.Close();
  6. And display the image anywhere you want to display.
     Collapse| Copy Code
    pictureBox1.Image=Image.FromFile(strfn);

Complete Image Retrieving Code

 Collapse| Copy Code
private void btnLoad_Click(object sender, System.EventArgs e)
{try{SqlCommand cmdSelect=new SqlCommand("select Picture" + " from tblImgData where ID=@ID",this.sqlConnection1);cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);cmdSelect.Parameters["@ID"].Value=this.editID.Text;this.sqlConnection1.Open();byte[] barrImg=(byte[])cmdSelect.ExecuteScalar();string strfn=Convert.ToString(DateTime.Now.ToFileTime());FileStream fs=new FileStream(strfn, FileMode.CreateNew, FileAccess.Write);fs.Write(barrImg,0,barrImg.Length);fs.Flush();fs.Close();pictureBox1.Image=Image.FromFile(strfn);}catch(Exception ex){MessageBox.Show(ex.Message);}finally{this.sqlConnection1.Close();}
}

Bibliography

  • Retrieving Images from SQL Server in ASP.NET
  • Images, Thumbnails, SQL Server, and ASP.NET - Level 200

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

posted on 2014-04-23 23:05 NET未来之路 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/3684213.html

Storing and Retrieving Images from SQL Server using Microsoft .NET相关推荐

  1. 15支持哪些数据库版本 tfs_版本和支持的功能 - SQL Server 2016 | Microsoft Docs

    SQL Server 2016 的各版本和支持的功能Editions and supported features of SQL Server 2016 07/22/2020 本文内容 适用于:App ...

  2. 微软ODBC服务器驱动,解决安装SQL Server时[Microsoft][ODBC 驱动程序管理器] 未发现数据源的问题...

    在Windows Server 2003 上安装 MS SQL Server 2000 时,最后阶段安装程序在配置服务器时,出现"[Microsoft][ODBC 驱动程序管理器] 未发现数 ...

  3. SQL Server中的空间SQL数据类型

    空间数据类型 (Spatial data type) SQL server furnishes us with the geometry and geography SQL data types fo ...

  4. SQL Server数据类型概述

    In this article, we will give an overview of various SQL Server data types. 在本文中,我们将概述各种SQL Server数据 ...

  5. SQL Server中的计算列概述

    In this article, we will explore computed columns in SQL Server and their configurations. 在本文中,我们将探讨 ...

  6. sql2012 ssrs_您必须在SQL Server Reporting Services(SSRS)中记录的十件事

    sql2012 ssrs Documentation is never fun. I curse having to do it and I curse the person who didn't d ...

  7. 如何使用SQL Server Reporting Services创建图像分类系统

    介绍 (Introduction) With Christmas just around the corner, in today's "get together" I thoug ...

  8. 使用SQL Server数据库支持SharePoint的5条技巧

    SharePoint入门 (The SharePoint primer) If you are reading this, odds are you already work with SharePo ...

  9. 如何在Windows Azure VM上的SQL Server和Windows Azure SQL Database两者中做出选择

    作者信息:本篇文章是由SQL Server Cloud Infrastructure Team的 Madhan Arumugam 和 Guy Bowerman共同著作. 简介 把SQL 数据托管在哪里 ...

最新文章

  1. php适合做后台吗,php是否适合做后台长驻程序
  2. 一文应用 AOP | 最全选型考量 + 边剖析经典开源库边实践,美滋滋
  3. python 利用pyttsx3文字转语音
  4. R-3.1.1 编译安装2
  5. php获取访问者ip地址汇总,php获取访问者IP地址汇总_PHP
  6. [kuangbin带你飞]专题四 最短路练习
  7. 使用kali破解win7密码
  8. 护腰暖腹的好伙伴,让腰部远离寒风侵袭
  9. OCR营业执照识别助力工商信息智能注册
  10. Win10系统提示过期,三条命令帮你搞定
  11. 居中问题(水平居中和垂直居中)
  12. 【路科验证008】DVT 软件使用指导
  13. 64匹马8个跑道需要多少轮才能选出最快的四匹
  14. 初赛De各种各样的知识点
  15. 神奇太阳能电池:自动跟着太阳走
  16. Navicat 连接 Linux的mysql(远程登录)
  17. 《漫画傅里叶解析》笔记(6)
  18. 浅谈Java三层架构
  19. Python3爬取喜马拉雅页面音频文件
  20. 对阿,为什么大学程序设计老师不去外面公司当程序员?

热门文章

  1. fastjson反序列化漏洞原理及利用
  2. disruptor 介绍
  3. Feign Hystrix (HystrixCommonKey) 设置单独接口的超时时间和FallBack
  4. Weblogic 节点启动
  5. 不提拔你,就是因为你只想把工作做好
  6. Myeclipes连接Mysql数据库配置
  7. Qt第五课 无构造函数可以接受源类型,或构造函数重载决策不明确
  8. JQuery常用知识点汇总
  9. 【转】做好性能测试的6个关注点
  10. 持续集成工具FinalBuilder使用心得