插入: //单击选择添加的 private void pic_Click(object sender, EventArgs e)
{ dlgFilter = "JPG|jpg|BMP|bmp|PNG|png";
if (dlgShowDialog() == SystemWindowsFormsDialogResultOK)
{
picImage = ImageFromFile(dlgFileName);
txtFilePath = dlgFileName;
}
} public byte[] picData; public string txtFilePath = ""; 添加确定按钮代码: f (txtFilePath != "")
{
try
{
FileStream fs = new FileStream(txtFilePath, FileModeOpen, FileAccessRead);
int len = ConvertToInt32(fsLength);
b = new byte[len];
fsRead(b, 0, len);
fsClose();
}
catch
{
b = null;
}
} SqlConnection conn = new SqlConnection(strConn);
connOpen(); SqllCommand cmdInsert = new SqlCommand();
cmdInsertConnection = conn;
cmdInsertCommandText =插入语句; cmdInsertParametersAdd("@照片", SqlDbTypeImage); if (txtFilePath == "")
{
cmdInsertParameters["@照片"]Value = DBNullValue;
}
else
{
cmdInsertParameters["@照片"]Value = b;
}
cmdInsertExecuteNonQuery();
connClose();获取: public byte[] picData; SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmdConnection = conn;
cmdCommandText = "select from 联系人 where 编号=" + IDToString();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet(); sdaFill(ds); if (dsTables[0]RowsCount == 1)
{
if (dsTables[0]Rows[0]["照片"] == DBNullValue)
{ //pic为picturebox控件
picImage = PhoneBoookPropertiesResourcesDeskShade;//为空的话给个默认
}
else
{
byte[] b = (byte[])(dsTables[0]Rows[0]["照片"]);
picImage = ImageFromStream(new MemoryStream(b));
picData = b;
}
}
下面我们将示例一个文件读取存储至数据库并从数据库中读取信息并显示的案例:
1、首先读取硬盘上的某一具体文件,读取模式设置为readBinary方式:
<cffile
action
=
"readBinary"
file
=
"temp
directory
here#fileserverFile#"
variable
=
"test">
2、将读取出来的二进制内容存储至数据库中(注:数据库字段需设置成能存储类型的字段,如blob类型):
<cfquery
datasource
=
"datasource">
insert
into
imageTest
values
(<cfqueryparam
cfsqltype="cf_sql_blob"
value="#test#">)
</cfquery>
通过1、2两个步骤,我们轻松实现了读取文件并存储至数据库的 *** 作过程。
3、从数据库中读取信息,该文件可命名为dispImagecfm:
<!---
在此需特别注意enablecfoutputonly的压缩空白功能,如果不对该页面进行空白压缩,很可能会造成无法显示的问题
--->
<cfprocessingdirective
suppressWhiteSpace="yes">
<cfsetting
enablecfoutputonly="yes">
<!---
读取相应的信息
--->
<cfquery
datasource
=
"datasource">
select
image
from
imageTest
where
variable
here#
</cfquery>
<!---
设置浏览器输出的格式,我们将它设置为的JPG类型,用户可根据实际情况改动类型设置
--->
<cfcontent
type="image/jpg">
<!---
输出
--->
<cfoutput>#toString(imageTestimage)#</cfoutput>
</cfprocessingdirective>
<cfabort>
4、显示内容,调用dispImagecfm页面:
<img
src
=
"dispImagecfmid=your
variable
here">
通过3、4两个步骤,我们也很容易的就完成了从数据库中读取信息并在页面显示的功能。
总结:实际上,除了文件可以如此处理,其它的文件也能通过类似方式进行处理,可将任意文件类型存储至数据库,只是文件大小的原因以及数据库存储读取速度性能限制,我们基本上还是不建议将文件存储至数据库,毕竟硬盘读取要快得多。
private void button1_Click(object sender, EventArgs e)
{
Stream ms;
byte[] picbyte;
OpenFileDialog selectPic = new OpenFileDialog();
if (selectPicShowDialog() == DialogResultOK)
{
if ((ms = selectPicOpenFile()) != null)
{
picbyte = new byte[msLength];
msPosition = 0;
msRead(picbyte, 0, ConvertToInt32(msLength));
SqlConnection conn = new SqlConnection();
connConnectionString = sqlconn;
string strsql = "insert into Pic values(@Image)";
SqlCommand cmd = new SqlCommand(strsql,conn);
cmdParametersAdd("@Image", SqlDbTypeVarBinary);
cmdParameters[0]Value = picbyte;
try
{
connOpen();
cmdExecuteNonQuery();
}
catch(Exception ex)
{
throw ex;
}
connClose();
}
}
MessageBoxShow("OK");
}
这个是在WinForm中保存的例子,点击保存按钮后,d出选择对话框,然后把转化为二进制保存在数据库中
你可以根据你的情况适当修改下就可以使用
下面有一段代码,在我一个项目里抽出来的,没有完全T出来,你应该看得懂了:
Stream ms;
byte[] picbyte;
OpenFileDialog ofdSelectPic = new OpenFileDialog();
ofdSelectPicDefaultExt = "bmp;jpg;jpeg;gif;png;";
ofdSelectPicFilter = "jpg,gif,bmp,png,jpeg|jpg;gif;bmp;png;jpeg";
if (ofdSelectPicShowDialog() == DialogResultOK)
{
if ((ms = ofdSelectPicOpenFile()) != null)
{
string filepath = ofdSelectPicFileName;
string extension = PathGetExtension(filepath);
if (extension == "jpg" || extension == "gif" || extension == "bmp" || extension == "jpeg" || extension == "png")
{
if (SelectImageIndex == 1)
{
picSignatureImage = ImageFromFile(filepath);
}
else if (SelectImageIndex == 2)
{
picphotoid1Image = ImageFromFile(filepath);
}
else if (SelectImageIndex == 3)
{
picphoto2Image = ImageFromFile(filepath);
}
picbyte = new byte[msLength];
msPosition = 0;
msRead(picbyte, 0, ConvertToInt32(msLength));
msClose();
return picbyte;
}
else
{
MessageBoxShow("you can only select the image type file!");
return null;
}
}
else
{
return null;
}
}
那个SQL数据库里字段设置成image或者binary都行。
首先在SQL Server中建立一个存储的数库表,ImageData Column为图象二进制数据储存字段,ImageContentType Column为图象文件类型记录字段,
ImageDescription Column为储蓄图象文件说明字段,ImageSize Column为储存图象文件长度字段,结构如下:
CREATE TABLE [dbo][ImageStore] (
[ImageID] [int] IDENTITY (1, 1) NOT NULL ,
[ImageData] [image] NULL ,
[ImageContentType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[ImageDescription] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
[ImageSize] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 向数据库中存入:using System;
using SystemCollections;
using SystemComponentModel;
using SystemData;
using SystemDrawing;
using SystemWeb;
using SystemWebSessionState;
using SystemWebUI;
using SystemWebUIWebControls;
using SystemWebUIHtmlControls;
using SystemIO;
using SystemDataSqlClient;namespace UpLoadFile
{
/// <summary>
/// Summary description for UpLoadImage
/// </summary>
public class UpLoadImage : SystemWebUIPage
{
protected SystemWebUIWebControlsButton btnUpload;
protected SystemWebUIWebControlsLabel txtMessage;
protected SystemWebUIWebControlsTextBox txtDescription;
protected SystemWebUIHtmlControlsHtmlTable Table1;
protected SystemWebUIHtmlControlsHtmlInputFile UP_FILE;//HtmlControl、WebControls控件对象
protected Int32 FileLength = 0;
private void Page_Load(object sender, SystemEventArgs e)
{
// Put user code to initialize the page here
if(!PageIsPostBack)
{
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASPNET Web Form Designer
//
InitializeComponent();
baseOnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor
/// </summary>
private void InitializeComponent()
{
thisbtnUploadClick += new SystemEventHandler(thisbtnUpload_Click);
thisLoad += new SystemEventHandler(thisPage_Load); }
#endregion private void btnUpload_Click(object sender, SystemEventArgs e)
{
>
字段:
1id 自增长
2img ole对象
详细实现代码:
defaultaspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Defaultaspxcs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 10 Transitional//EN" ">
//获取数据库里的代码(省略)
object ob = dataTableRows[0][""];
byte[] buff = ob as byte[];
if (ob == null)
{
//报错
return;
}
MemoryStream ms = new MemoryStream(buff, 0, buffLength, true);
Bitmap bt = BitmapFromStream(ms) as Bitmap;
if (bt == null)
{
//数据格式错误,请检查是否是
return;
}
msFlush();
msClose();
//把bt显示出来,比如 pictureBoxImage = bt;
以上就是关于C#WinForm中,用于将图片以二进制存入sql数据库中,并将图片从数据库中取出,显示在PictureBox控件中。全部的内容,包括:C#WinForm中,用于将图片以二进制存入sql数据库中,并将图片从数据库中取出,显示在PictureBox控件中。、怎样读取数据库中存储的二进制图片文件、将图片转换为二进制文件保存到数据库等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)