存储图片:以二进制的形式存储图片时,要把数据库中的字段设置为Image数据类型(SQL Server),存储的数据是Byte[]
‘贰’ 在SQL Server中,共使用了3种数据类型来存储二进制数据,分别是______、______、
主要涉及 binary varbinary image 这三个字段类型吧
请仔细了解sqlserver 各种数据类型
sql二进制数据类型详解
如有疑问,及时沟通!
‘叁’ sqlserver 二进制数据存储问题
这种字段我记得只要给个byte数组就可以了,不用转移成binary
‘肆’ Sqlserver数据库存储的图片格式(二进制数据)怎么显示到页面
1.将图片以二进制存入数据库
//保存图片到数据库
protected void Button1_Click(object sender, EventArgs e)
{
//图片路径
string strPath = "~/photo/03.JPG";
string strPhotoPath = Server.MapPath(strPath);
//读取图片
FileStream fs = new System.IO.FileStream(strPhotoPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
//存入
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
string strComm = " INSERT INTO personPhoto(personName, personPhotoPath, personPhoto) ";
strComm += " VALUES('wangwu', '" + strPath + "', @photoBinary )";
SqlCommand myComm = new SqlCommand(strComm, myConn);
myComm.Parameters.Add("@photoBinary", SqlDbType.Binary,photo.Length);
myComm.Parameters["@photoBinary"].Value = photo;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
}
2.读取二进制图片在页面显示
//读取图片
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
string strComm = " SELECT personPhoto FROM personPhoto WHERE personName='wangwu' ";
SqlCommand myComm = new SqlCommand(strComm, myConn);
myConn.Open();
SqlDataReader dr = myComm.ExecuteReader();
while (dr.Read())
{
byte[] photo = (byte[])dr["personPhoto"];
this.Response.BinaryWrite(photo);
}
dr.Close();
myConn.Close();
或
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='11' ", myConn);
DataSet myds = new DataSet();
myConn.Open();
myda.Fill(myds);
myConn.Close();
byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"];
this.Response.BinaryWrite(photo);
3.设置Image控件显示从数据库中读出的二进制图片
---------------------------------------------
SqlConnection myConn = new SqlConnection("Data Source=192.168.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='11' ", myConn);
DataSet myds = new DataSet();
myConn.Open();
myda.Fill(myds);
myConn.Close();
byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"];
//图片路径
string strPath = "~/photo/wangwu.JPG";
string strPhotoPath = Server.MapPath(strPath);
//保存图片文件
BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate));
bw.Write(photo);
bw.Close();
3.显示图片
this.Image1.ImageUrl = strPath;
4.GridView中ImageField以URL方式显示图片
--------------------------
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="personName" HeaderText="姓名" />
<asp:ImageField DataImageUrlField="personPhotoPath"
HeaderText="图片">
</asp:ImageField>
</Columns>
</asp:GridView>
5.GridView显示读出的二进制图片
//样板列
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="personName" HeaderText="姓名" />
<asp:ImageField DataImageUrlField="personPhotoPath"
HeaderText="图片">
</asp:ImageField>
<asp:TemplateField HeaderText="图片">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex < 0)
return;
// System.ComponentModel.Container
string strPersonName = (string)DataBinder.Eval(e.Row.DataItem, "personName");
Image tmp_Image = (Image)e.Row.Cells[2].FindControl("Image1");
if (!System.Convert.IsDBNull(DataBinder.Eval(e.Row.DataItem, "personPhoto")))
{
//
byte[] photo = (byte[])DataBinder.Eval(e.Row.DataItem, "personPhoto");
//图片路径
string strPath = "~/photo/" + strPersonName.Trim() + ".JPG";
string strPhotoPath = Server.MapPath(strPath);
//保存图片文件
BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath, FileMode.OpenOrCreate));
bw.Write(photo);
bw.Close();
//显示图片
tmp_Image.ImageUrl = strPath;
}
}
‘伍’ sqlserver 数据库保存二进制数据流出错,大虾帮忙看下哪里有问题,没有分了,就这点分散了
转换C盘命令是:开始-运行-cmd-convert c:/fs:ntfs
非系统盘转换比较容易,直接右键格式化,选中NFS格式即可,或者用一般的格式转换软件都可以,一般不会造成不好影响。但系统盘(一般是C盘)就难度大了,重装系统是最好的办法,但你也可以试试Paragon Hard Disk Manager 这个软件,但强烈不建议转换系统盘,弄不好会出现莫名其妙的问题。所有盘转化前都最好要备份好你的重要资料!
‘陆’ sql sever中照片用什么数据类型
如果你把照片文件保存到数据库的话,那应该设置成image类型。
‘柒’ .NET中如何循环遍历一个文件夹中的图片并将图片以二进制的方式存入sqlserver数据库
publicvoidToImg(Imageimg,Stringname)//插入图片
{
#region上传文件办法
//FileStreamfs=newFileStream(Application.StartupPath+@"/gy.gif",FileMode.Open,FileAccess.Read);
//BinaryReaderbr=newBinaryReader(fs);
//byte[]photo=br.ReadBytes((int)fs.Length);
//br.Close();
//fs.Close();
#endregion
//把图片转换成二进制
MemoryStreamms=newMemoryStream();
img.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[]photo=ms.GetBuffer();
ms.Close();
//存储字段
OleDbCommandcmd=newOleDbCommand("INSERTINTO下单表(订票人,识别码)VALUES(@CategoryName,@Picture)",conn);
cmd.Parameters.Add("@CategoryName",OleDbType.VarChar,15).Value=name;
cmd.Parameters.Add("@Picture",OleDbType.Binary,photo.Length).Value=photo;
cmd.ExecuteNonQuery();
}
publicvoidPix(PictureBoxpx,Stringname)//显示图片
{
Stringsql="Select识别码from下单表where订票人='"+name+"'";
byte[]imagebytes=null;
OleDbCommandcom=newOleDbCommand(sql,conn);
OleDbDataReaderdr=com.ExecuteReader();
while(dr.Read())
{
imagebytes=(byte[])dr.GetValue(0);
}
MemoryStreamms=newMemoryStream(imagebytes);
Bitmapbmpt=newBitmap(ms);
px.Image=bmpt;
px.SizeMode=PictureBoxSizeMode.StretchImage;
}
这是数据库读取和存储图片的方法,至于遍历文件夹,你自己找下例子吧,我是个懒人,太无聊的事情不做
‘捌’ 怎么把图片文件在SQL server数据库中保存为二进制记录(注:不是用图片路径),最好有源代码。
首先在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 System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;namespace UpLoadFile
{
/// <summary>
/// Summary description for UpLoadImage.
/// </summary>
public class UpLoadImage : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnUpload;
protected System.Web.UI.WebControls.Label txtMessage;
protected System.Web.UI.WebControls.TextBox txtDescription;
protected System.Web.UI.HtmlControls.HtmlTable Table1;
protected System.Web.UI.HtmlControls.HtmlInputFile UP_FILE;//HtmlControl、WebControls控件对象
protected Int32 FileLength = 0;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!Page.IsPostBack)
{
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
this.Load += new System.EventHandler(this.Page_Load); }
#endregion private void btnUpload_Click(object sender, System.EventArgs e)
{
HttpPostedFile UpFile = this.UP_FILE.PostedFile; //HttpPostedFile对象,用于读取图象文件属性
FileLength = UpFile.ContentLength; //记录文件长度
try
{
if (FileLength == 0)
{ //文件长度为零时
txtMessage.Text = "<b>请你选择你要上传的文件</b>";
}
else
{
Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
Stream StreamObject = UpFile.InputStream; //建立数据流对像
//读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
StreamObject.Read(FileByteArray,0,FileLength);
//建立SQL Server链接
SqlConnection Con = new SqlConnection("uid=sa;pwd= ;initial catalog=EE;data source=127.0.0.1;Connect Timeout=90");
String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = UpFile.ContentType; //记录文件类型
//把其它单表数据记录上传
CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = txtDescription.Text;
//记录文件长度,读取时使用
CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = UpFile.ContentLength;
Con.Open();
CmdObj.ExecuteNonQuery();
Con.Close();
txtMessage.Text = "<p><b>OK!你已经成功上传你的图片</b>";//提示上传成功
}
}
catch (Exception ex)
{
txtMessage.Text = ex.Message.ToString();
}
} }
}
将数据库中的图片数据读出来显示:using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;namespace UpLoadFile
{
/// <summary>
/// Summary description for ReadImage.
/// </summary>
public class ReadImage : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!Page.IsPostBack)
{
string id = Request.QueryString["ImgID"]; //得到图片的ID if (id != ""&& id != null && id != string.Empty)
{
ShowImage( id);
}
}
} #region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load); }
#endregion public void ShowImage(string id)
{
int ImgID = Convert.ToInt32(id); //ImgID为图片ID
//建立数据库链接
SqlConnection Con = new SqlConnection("uid=sa;pwd= ;initial catalog=EE;data source=127.0.0.1;Connect Timeout=90");
String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID;
try
{
Con.Open();
SqlDataReader SqlReader = CmdObj.ExecuteReader();
SqlReader.Read();
Response.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型
//输出图象文件二进制数制
Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);
Response.End();
Con.Close();
}
catch
{
Response.Write("<script>alert('该图片不存在');</script>");
return;
} }
}
}
‘玖’ 现有一个sql数据库表如何读取二进制内容
二进制数据由十六进制数表示,可以使用binary、varbinary和image数据类型存储。
binary固定长度(最多为8K)的二进制数据类型。
binary[ ( n) ] 固定长度的 n个字节二进制数据。N必须从 1 到 8,000。存储空间大小为 n+4 字节。
varbinary可变长度(最多为8K)的二进制数据类型。
varbinary[ ( n) ]n个
字节变长二进制数据。n必须从 1 到 8,000。存储空间大小为实际输入数据长度 +4个字节,而不是
n个字节。输入的数据长度可能为 0 字节。在 SQL-92 中varbinary的同义词为binary
varying。image用来存储长度超过 8 KB 的可变长度的二进制数据。
除非数据长度超过 8KB,否则一般宜用 varbinary 类型来存储二进制数据。一般用来存放
Microsoft Word 文档、Microsoft Excel 电子表格、包含位图的图像、图形交换格式 (GIF) 文件和联合图像专家组 (JPEG)
文件。在 Image 数据类型中存储的数据是以位字符串存储的,不是由 SQL Server
解释的,必须由应用程序来解释。例如,应用程序可以使用BMP、TIEF、GIF 和 JPEG 格式把数据存储在 Image 数据类型中。参考下列C# 代码:
privatevoidPage_Load(objectsender,System.EventArgse)
{
//gettheimageidfromtheurl
stringImageId=Request.QueryString["img"];
//buildourquerystatement
stringsqlText="SELECTimg_data,img_contenttypeFROMImageWHEREimg_pk="+ImageId;
SqlConnectionconnection=newSqlConnection(ConfigurationSettings.AppSettings["DSN"].ToString());
SqlCommandcommand=newSqlCommand(sqlText,connection);
//
connection.Open();
SqlDataReaderdr=command.ExecuteReader();
if(dr.Read())//yupwefoundourimage
{
Response.ContentType=dr["img_contenttype"].ToString();
Response.BinaryWrite((byte[])dr["img_data"]);
}
connection.Close();
}
}
‘拾’ 如何将二进制数组存入sqlserver中,语句
--创建表
create table test(col varbinary(4000))
go
--创建存储过程
create procere sp_savaBinary(@binary varbinary(4000))
as
insert into test values(@binary)
go
--调用存储过程插入数据
declare @binary varbinary(4000)
set @binary = cast( '12sfasfasfasf ' as varbinary(4000))
exec sp_savaBinary @binary