#region 图片转二进制&二进制转图片
/// <summary>
/// 二进制转换为图片文件存储到指定文件夹
/// </summary>
/// <param name="by">二进制值</param>
/// <param name="path">存储路径</param>
public static void BinaryToFile(byte[] by,string path)
{
//你要先将图片读到一个文件夹内
MemoryStream ms = new MemoryStream((Byte[])by);//by二进制值
Bitmap img = new Bitmap(ms);
//string filepath = HttpContext.Current.Server.MapPath("../API/");
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] filecount = dir.GetFiles();
int i = filecount.Length;
//string imagename = filepath + (i + 1) + ".jpg";
string imagename = path + (i + 1) + ".jpg";
img.Save(imagename);
ms.Close();
ms.Dispose();
}
/// <summary>
/// 指定文件转换为二进制
/// </summary>
/// <param name="path">指定路径文件</param>
/// <returns></returns>
public static byte[] FileToBinary(string path)
{
//string path = Server.MapPath("../images/add.png");
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
BinaryReader br = new BinaryReader(fs);
byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中
fs.Close();
fs.Dispose();
return imgBytesIn;
#region 指定图片文件二进制方式存入数据库
//StringBuilder sb=new StringBuilder();
//sb.Append("INSERT INTO [t_SignIn]([EmployeeID],[ClientID],[Img],[SignInTime]) ");
//sb.Append("VALUES(0,0,@img,GETDATE()) ");
//using (SqlConnection con = new SqlConnection(Config.SqlConnStr))
//{
// SqlCommand com = new SqlCommand(sb.ToString(),con);
// com.Parameters.Add("@img",SqlDbType.Binary).Value=imgBytesIn;
// con.Open();
// com.ExecuteNonQuery();
//};
#endregion
}
/// <summary>
/// 将二进制转换为图片输出到页面。可使用这两种方式输出
///1.<asp:Image ID="Image2" src="/WebService/WebForm1.aspx" οnclick="this.src=this.src+'?'" runat="server" ToolTip="点击刷新验证码" ImageAlign="AbsMiddle" CssClass="imgYzm"></asp:Image>
///2.<img src="/WebService/WebForm1.aspx" />
/// </summary>
/// <param name="binaryVal">二进制值</param>
public static void ReadBinaryOutput(byte[] binaryVal)
{
#region 从数据库读取二进制输出图片
//byte[] img = null;
//using (SqlDataReader sdr = Config.ConnSql().GetDataReader(CommandType.Text, "SELECT img FROM dbo.t_SignIn WHERE SignInID=14", null))
//{
// if (sdr.Read())
// {
// img = (byte[])sdr.GetValue(0);
// }
//}
#endregion
System.IO.MemoryStream ms = new System.IO.MemoryStream();
http.Current.Response.Clear();
http.Current.Response.ContentType = "image/Png";
http.Current.Response.BinaryWrite(binaryVal);
ms.Close();
ms.Dispose();
http.Current.Response.End();
}
#endregion