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,一经查实,立即删除!

相关文章

react(95)--外部定义变量

export const oneTab [{ name: 所有, code: },{ name: 草稿, code: 15973725291430011977912 },{ name: 已上架, code: 15973725579180011047799 },{ name: 已下架, code: 15973725862620011529122 }, ];

无钱生活的日子

无钱生活的日子——代腾飞 2007年9月5日 于成都无钱生活的日子心中的梦想俨然成为了一句空话无钱生活的日子每日计划着怎样不受饥饿的摧残而饱受尴尬无钱生活的日子就算是兄弟朋友也会给你奚落笑话无钱生活的日子我甚至不能尽孝回乡看我重病在床的妈心中只能增添一份惆怅的牵…

react(96)--switch做判断

list: (text, row) > {const list [];switch (row.status) {case COURSE_STATUS_UPSHEFF:list.push({ name: 查看详情, onClick: this.handleDetail });list.push({ name: 下架, onClick: this.handleUporDownsheff });break;case COURSE_STATUS_DOWNSHEFF:list.push({ nam…

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]<…

react(97)--分支切换

# 1.查看所有分支 > git branch -a# 2.查看当前使用分支(结果列表中前面标*号的表示当前使用分支) > git branch# 3.切换分支 > git checkout 分支名

DataProcess-语义分割数据集中将原始数据划分为73比例

语义分割数据集中将原始数据划分为73比例 我们下载公开数据集的时候&#xff0c;经常所有的图片是在一起的&#xff0c;如果我们需要进行实验的话还是需要按照73的比例将数据集划分为训练集和测试集&#xff0c;这里我准备了一个脚本&#xff0c;大家只需要传入分割之后保存的…

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

对一个二维矩阵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;可以最…

手机软件测试资料

手机知识的介绍和测试基础&#xff0c;以及手机相关的介绍&#xff0c;最后是对手机软件测试工程师素质讲解&#xff0c;比较详细&#xff0c;非常值得初学者一看.资料下载请点击此处转载于:https://blog.51cto.com/218686/41416

参考文献的自动修改

写论文&#xff0c;参考文献的修改很麻烦&#xff0c;删除一个&#xff0c;添加一个&#xff0c;就需要改一长串数字。怎么办呢。本人推荐一种简单方法&#xff1a;尾注法 方法如下&#xff08;以 Word2003为例&#xff09;&#xff1a; 1&#xff0e;光标移到要插入参考文献…

原生和h5桥接

//桥接 function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(window.WebViewJavascriptBridge) } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback) } window.WVJBCallbacks [callback] let W…

AOI的工作原理

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

常用数学特殊符号,复制到word中使用

正 负 根 号 √ 因 为 ∵ 所 以 ∴ 大於或等於 ≥ 少於或等於 ≤ 大约等於 ≈ 不等於 ≠ 全 等 ≡ 垂 直 ⊥ 角 度 ∠ 度 数 o 圆 形 ⊙十字圆 ⊕直角三角形 ⊿空 集 ? 交 集 ∩和 集 ∪无限大 ∞积分符号 ∫线积分符号 ∮ ----------------------------------------------…

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

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

HTTPS下导出excel失败解决办法

要在导出文件名前加HttpUtility.UrlEncode 如下例 Response.AddHeader("Content-Disposition", "attachment; filename" HttpUtility.UrlEncode(fileName) ".xls");转载于:https://www.cnblogs.com/xiayan/p/3699287.html

SHA-1算法的C语言实现(源码来自网络)

来自网络上的SHA&#xff0d;1算法&#xff0c;自己加了少量注释&#xff0c;方便以后需要的时候可以利用。 代码&#xff1a; /* sha1sum.c - print SHA-1 Message-Digest Algorithm * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc. * Copyright (…

移动端隐藏滚动条(最全面)

网上查的基本都是坑爹的&#xff0c;都没写全 html,body{//隐藏滚动条 height: 100vh; overflow-y: scroll; &::-webkit-scrollbar { display: none; } } 需要设置高度&#xff0c;还要设置哪个方向的滚动scrol&#xff0c;一个都不能少