Storing and Retrieving Images from SQL Server using Microsoft .NET

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:

    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.
      this.openFileDialog1.ShowDialog(this);
      string strFn=this.openFileDialog1.FileName;
    2. By using FileInfo class, I retrieved the file size:
      FileInfo fiImage=new FileInfo(strFn);
    3. Declare an array of that size.
      this.m_lImageFileLength=fiImage.Length;
      m_barrImg=new byte[Convert.ToInt32(this.m_lImageFileLength)];
    4. By using FileStream object, I filled the byte array.
      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

    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.
      this.sqlCommand1.CommandText= "INSERT INTO tblImgData(ID,Name,Picture)" + " values(@ID,@Name,@Picture)";
    2. Create parameters.
      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.
      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.
      int iresult=this.sqlCommand1.ExecuteNonQuery();

    Complete Save Image 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.
    SqlCommand cmdSelect = new SqlCommand("select Picture" + " from tblImgData where ID=@ID", this.sqlConnection1);
  2. Create parameter for the query.
    cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
  3. Provide value to the parameter.
    cmdSelect.Parameters["@ID"].Value=this.editID.Text;
  4. Open database connection and execute “ExecuteScalar” because we want only “IMAGE” column data back.
    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.
    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.
    pictureBox1.Image=Image.FromFile(strfn);

Complete Image Retrieving 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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/407835.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

flot绘制折线图

<!--请先确保你有jquery.js 和 jquery.flot.min.js--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns"http://www.w3.org/1999/xhtm…

在dos下运行.exe程序(C++)

说明&#xff1a;在Dos下运行.exe程序(C) 先看C源文件&#xff1a; #include<iostream>using namespace std; void main(int argc, char * argv[]){ cout<<"argc "<<argc<<endl; for(int i 0; i < argc; i) cout<<argv[i]<…

提取二维矩阵中分块后指定的块

对一个二维矩阵I(NN)进行分块(块大小为nn),并提取其中第ii块中的元素 % 对二维矩阵I进行[n n]分块&#xff0c;取其中第ii块中的元素function x getBlock(I, n, ii) N size(I, 1); n1 N / n; n2 n * n; [a, b] ind2sub([n1 n1], ii); p (b-1) * n * (n1 *…

重构 改善既有代码的设计:代码的坏

以下内容来自<<重构 改善既有代码的设计>> 一、什么是重构 所谓重构(Refactoring)是这样一个过程&#xff1a;在不改变代码外在行为的前提下&#xff0c;对代码做出修改以改进程序的内部结构。重构是一种经千锤百炼形成的有条不紊的程序整理方法&#xff0c;可以最…

AOI的工作原理

以上为AOI目前可以检测到的缺陷GF 转载于:https://blog.51cto.com/fangz/41656

使用LINQ解除SQL注入安全问题

在开发人员承受越来越多的安全责任之时&#xff0c;许多开发人员了解到的第一个Web应用安全漏洞&#xff0c;是一个被称为“SQL注入”的极危险的命令注入形式。命令注入的原始的形式本是指这样一种漏洞&#xff1a;***者通过提供一个正常使用者意料之外的输入&#xff0c;改变你…

漫画兔善搞2007-等待爱玛马士基号的垃圾

转自&#xff1a;[url]http://blog.sina.com.cn/s/blog_4992fa8b010007f5.html[/url]英国对华倾泻垃圾废物 中国进口商进口为获利益[url]http://www.sina.com.cn[/url] 2007年01月12日 21:49 CCTV《经济信息联播》英国的天空电视台近日报道&#xff0c;素有“欧洲垃圾箱”之称的…

cocos2dx CCLayerColor和CCLayerColor

在cocos2dx中&#xff0c;默认的CCLayer背景是黑色的&#xff0c;有些时候需要特殊的Layer&#xff0c;所以cocos2dx中提供了这两种LayerCCLayerColor是可以改变背景色的Layer&#xff0c;示例如下&#xff1a;CCSize size __winSize;CCLayerColor* layer CCLayerColor::crea…

[转]经典的C语言著作,“C语言四书五经”

http://blog.chinaunix.net/u/22520/showart_308803.html 经典的C语言著作&#xff0c;“C语言四书五经”一、The C Programming Language C程序设计语言&#xff08;第2版新版&#xff09; 原出版社&#xff1a; Prentice Hall PTR 作者&#xff1a; [美]Brian W.Kernighan,De…

INI文件读写--VC6.0

新建一个dialog based MFC Windows Application,命名为&#xff1a;d, 界面为&#xff1a; 为按钮Read和Write添加单击事件&#xff0c;并自定义一个函数GetIniFileName()用来取得ini文件的路径&#xff0c;主要函数代码如下&#xff1a;// read data from config file void CD…

SQL SERVER2000教程-第二章-创建和管理数据库 第六节 压缩数据库

有时&#xff0c;人们可能为预期有一定程度活动的数据库分配了太多的空间&#xff0c;当意识到分配了太多空间时&#xff0c;可能决定压缩分配的空间大小。SQLSERVER提供三种可以压缩数据库大小的方法&#xff0c;autoshrink数据库选项&#xff0c;“企业管理器”和“数据库一致…

C#下实现在线升级

//这是一个webserviceprivateAppUpdate.UpdateServ UpdateSvr;privatevoidbutton1_Click(objectsender, System.EventArgs e){ if(LinkWebServices()true){this.label1.Text&quot;连接服务器. PASS&quot;;if(CheckVer()true){this.label2.Text&quot;检查最新版本并…

客户端版本和服务器版本上传软件

FileZilla是一个免费开源的FTP软件&#xff0c;分为客户端版本和服务器版本&#xff0c;具备所有的FTP软件功能。可控性、有条理的界面和管理多站点的简化方式使得Filezilla客户端版成为一个方便高效的FTP客户端工具&#xff0c;而FileZilla Server则是一个小巧并且可靠的支持F…

一个Ext2+SWFUpload做的图片上传对话框

一个Ext2SWFUpload做的图片上传对话框的例程我们先看看对话框的布局&#xff1a; 布局就是在一个窗口里内嵌一个表格控件&#xff0c;窗口的底部工具条带一个进度条&#xff0c;表格的顶部工具条带几个操作按钮和一个下来选择框&#xff0c;底部工具条作为一个信息显示区域显示…

单交换机VLAN 配置和结果验证(51cto-o8)

1. 实验线路连接图使用Cisco Packet Tracer5.3 构建拓扑结构图 2. 实验内容(1) 按图配置各台计算机IP 地址。(2) 参阅教材中内容&#xff0c;完成单交换机上的VLAN 配置&#xff0c;配置要求如图 所示&#xff0c;使用show vlan 指令查看VLAN的配置情况&#xff0c;并使用Ping …