当前位置:文档之家› c#二进制图片存储与读取

c#二进制图片存储与读取

.NET二进制图片存储与读取的常见方法有以下几种:

.NET二进制图片存储:以二进制的形式存储图片时,要把数据库中的字段设置为Image数据类型(SQL Server),存储的数据是Byte[].

1.参数是图片路径:返回Byte[]类型:


1.public byte[] GetPictureData(string imagepath)
2. {
3. //根据图片文件的路径使用文件流打开,并保存为byte[]
4. FileStream fs = new FileStream(imagepath, FileMode.Open);
5. byte[] byData = new byte[fs.Length];
6. fs.Read(byData, 0, byData.Length);
7. fs.Close();
8. return byData;
9. }
10.


2.参数类型是Image对象,返回Byte[]类型:


 1.public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
2. {
3. //将Image转换成流数据,并保存为byte[]
4. MemoryStream mstream = new MemoryStream();
5. imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
6. byte[] byData = new Byte[mstream.Length];
7. mstream.Position = 0;
8. mstream.Read(byData, 0, byData.Length);
9. mstream.Close();
10. return byData;
11. }


好了,这样通过上面的方法就可以把图片转换成Byte[]对象,然后就把这个对象保存到数据库中去就实现了把图片的二进制格式保存到数据库中去了。下面我就谈谈如何把数据库中的图片读取出来,实际上这是一个相反的过程。

.NET二进制图片读取:把相应的字段转换成Byte[]即:Byte[] bt=(Byte[])XXXX

1.参数是Byte[]类型,返回值是Image对象:


1.public System.Drawing.Image ReturnPhoto(byte[] streamByte)
2. {
3. System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
4. System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
5. return img;
6. }


2.参数是Byte[] 类型,没有返回值,这是针对https://www.doczj.com/doc/223876471.html,中把图片从输出到网页上(Response.BinaryWrite)


1.public void WritePhoto(byte[] streamByte)
2. {
3. // Response.ContentType 的默认值为默认值为“text/html”
4. Response.ContentType = "image/GIF";
5. //图片输出的类型有: image/GIF image/JPEG
6. Response.BinaryWrite(streamByte);
7. }


补充:

针对Response.ContentType的值,除了针对图片的类型外,还有其他的类型:


1.Response.ContentType = "application/msword";
2. Response.ContentType = "application/x-shockwave-flash";
3. Response.ContentType = "application/vnd.ms-excel";


另外可以针对不同的格式,用不同的输出类型以适合不同的类型:


1.switch (dataread("document_type"))
2. {
3. case "doc":
4. Response.ContentType = "application/msword";
5. case "swf":
6. R

esponse.ContentType = "application/x-shockwave-flash";
7. case "xls":
8. Response.ContentType = "application/vnd.ms-excel";
9. case "gif":
10. Response.ContentType = "image/gif";
11. case "Jpg":
12. Response.ContentType = "image/jpeg";
13. }





protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
Stream mystream = FileUpload1.PostedFile.InputStream;//FileUpload1是上传控件..
int length = FileUpload1.PostedFile.ContentLength;

byte[] bytes = new byte[length];
mystream.Read(bytes, 0, length);
mystream.Close();
string conn = "server=(local);database=Image;Uid=sa;Pwd=123456 ";
SqlConnection myconn = new SqlConnection(conn);
myconn.Open();
string str= "insert into image (img) values( ' " + bytes + " ') ";
SqlCommand mycomm = new SqlCommand(str, myconn);
mycomm.ExecuteNonQuery();
myconn.Close();
}
}
上面把图片存入数据库...
下面是把图片从数据库中读出来...
protected void Button2_Click(object sender, EventArgs e)
{
string imgtype = FileUpload1.PostedFile.ContentType;
string conn = "server=(local);database=Image;Uid=sa;Pwd=123456 ";
string str= "select img from image where ID=5 ";
SqlConnection myconn = new SqlConnection(conn);
myconn.Open();
//SqlDataAdapter myda = new SqlDataAdapter(str, conn);
//DataSet myds =new DataSet();
//myda.Fill(myds);
SqlCommand mycom = new SqlCommand(str, myconn);
SqlDataReader mydr = mycom.ExecuteReader();
if (mydr.Read())
{
Response.ContentType = imgtype;
Response.BinaryWrite((byte[])mydr[ "img "]);
}
else
{

Response.Write( "没有从数据库中读取图片 ");
}
myconn.Close();
}



一、发生的背景

在开发新项目中使用了新的语言开发C#和新的技术方案WEB Service,但是在新项目中,一些旧的模块需要继续使用,一般是采用C或C++或Delphi编写的,如何利用旧模块对于开发人员来说,有三种可用方法供选择:第一、将C或C++函数用C#彻底改写一遍,这样整个项目代码比较统一,维护也方便一些。但是尽管微软以及某些书籍说,C#和C++如何接近,但是改写起来还是很痛苦的事情,特别是C++里的指针和内存操作;第二、将C或C++函数封装成COM,在C#中调用COM比较方便,只是在封装时需要处理C或C++类型和COM类型之间的转换,也有一些麻烦,另外COM还需要注册,注册次数多了又可能导致混乱;第三、将C或C++函数封装成动态链接库,封装的过程简单,工作量不大。因此我决定采用加载动态链接库的方法实现,于是产生了在C#中如何调用自定义的动态链接库问题,我在网上搜索相关主题,发现一篇调用系统API的文章,但是没有说明如何解决此问题,在MSDN上也没有相关详细说明。基于此,我决定自己从简单出发,逐步试验,看看能

否达到自己的目标。

(说明一点:我这里改写为什么很怕麻烦,我改写的代码是变长加密算法函数,代码有600多行,对算法本身不熟悉,算法中指针和内存操作太多,要想保证算法正确,最可行的方法就是少动代码,否则只要有一点点差错,就不能肯定算法与以前兼容)



二、技术实现

下面看看如何逐步实现动态库的加载,类型的匹配:



动态链接库函数导出的定义,这个不需要多说,大家参考下面宏定义即可:

#define LIBEXPORT_API extern "C" __declspec(dllexport)



第一步,我先从简单的调用出发,定义了一个简单的函数,该函数仅仅实现一个整数加法求和:

LIBEXPORT_API int mySum(int a,int b){ return a+b;}



C#定义导入定义:

public class RefComm

{

[DllImport("LibEncrypt.dll", EntryPoint=" mySum ",CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)] public static extern int mySum (int a,int b);

}



在C#中调用测试:

int iSum= RefComm. mySum(2,3);

运行查看结果iSum为5,调用正确。第一步试验完成,说明在C#中能够调用自定义的动态链接库函数。



第二步,我定义了字符串操作的函数(简单起见,还是采用前面的函数名),返回结果为字符串:

LIBEXPORT_API char *mySum(char *a,char *b){sprintf(b,”%s”,a) return a;}



C#定义导入定义:

public class RefComm

{

[DllImport("LibEncrypt.dll", EntryPoint=" mySum ",CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)] public static extern string mySum (string a, string b);

}



在C#中调用测试:

string strDest=””;

string strTmp= RefComm. mySum(“12345”, strDest);

运行查看结果strTmp为“12345”,但是strDest为空。



我修改动态链接库实现,返回结果为串b:

LIBEXPORT_API char *mySum(char *a,char *b){sprintf(b,”%s”,a) return b;}



修改C#导入定义,将串b修改为ref方式:

public class RefComm

{

[DllImport("LibEncrypt.dll", EntryPoint=" mySum ",CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)] public static extern string mySum (string a, ref string b);

}

在C#中再调用测试:

string strDest=””;

string strTmp= RefComm. mySum(“12345”, ref strDest);

运行查看结果strTmp和strDest均不对,含不可见字符。



再修改C#导入定义,将CharSet从Auto修改为Ansi:

public class RefComm

{

[DllImport("LibEncrypt.dll", EntryPoint=" mySum ",CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)] public static extern string mySum (string a, string b);

}

在C#中再调用测试:

string strDest=””;

string strTmp= RefComm. mySum(“12345”, ref strDest);

运行查看结果strTmp为“12345”,但是串strDest没有赋值。第二步实现函数返回串,但是

在函数出口参数中没能进行输出。



再次修改C#导入定义,将串b修改为引用(ref):

public class RefComm

{

[DllImport("LibEncrypt.dll", EntryPoint=" mySum ",CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)] public static extern string mySum (string a, ref string b);

}

运行时调用失败,不能继续执行。



第三步,修改动态链接库实现,将b修改为双重指针:

LIBEXPORT_API char *mySum(char *a,char **b){sprintf((*b),”%s”,a) return *b;}



C#导入定义:

public class RefComm

{

[DllImport("LibEncrypt.dll", EntryPoint=" mySum ",CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)] public static extern string mySum (string a, ref string b);

}



在C#中调用测试:

string strDest=””;

string strTmp= RefComm. mySum(“12345”, ref strDest);

运行查看结果strTmp和strDest均为“12345”,调用正确。第三步实现了函数出口参数正确输出结果。



第四步,修改动态链接库实现,实现整数参数的输出:

LIBEXPORT_API int mySum(int a,int b,int *c){ *c=a+b; return *c;}



C#导入的定义:

public class RefComm

{

[DllImport("LibEncrypt.dll", EntryPoint=" mySum ",CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)] public static extern int mySum (int a, int b,ref int c);

}



在C#中调用测试:

int c=0;

int iSum= RefComm. mySum(2,3, ref c);

运行查看结果iSum 和c均为5,调用正确。



经过以上几个步骤的试验,基本掌握了如何定义动态库函数以及如何在C#定义导入,有此基础,很快我实现了变长加密函数在C#中的调用,至此目标实现。



三、结论

在C#中,调用C++编写动态链接库函数,如果需要出口参数输出,则需要使用指针,对于字符串,则需要使用双重指针,对于C#的导入定义,则需要使用引用(ref)定义。

对于函数返回值,C#导入定义和C++动态库函数申明定义需要保持一致,否则会出现函数调用失败。

定义导入时,一定注意CharSet和CallingConvention参数,否则导致调用失败或结果异常。

运行时,动态链接库放在C#程序的目录下即可,我这里是一个C#的动态链接库,两个动态链接库就在同一个目录下运行。


相关主题
文本预览
相关文档 最新文档