class PublicMethod { /// <summary> /// 读取图片到byte[] /// </summary> /// <param name="pb"></param> /// <returns></returns> public byte[] readImagetoByte(PictureBox pb) { byte[] photoByte = null; if (pb.Image != null) { using (MemoryStream ms = new MemoryStream()) { Bitmap bmp = new Bitmap(pb.Image); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png); photoByte = new byte[ms.Length]; ms.Position = 0; ms.Read(photoByte, 0, Convert.ToInt32(ms.Length)); bmp.Dispose(); } } return photoByte; } /// <summary> /// 读取指定目录下的图片到byte[] /// </summary> /// <param name="strFile"></param> /// <returns></returns> public byte[] getBytesByImagePath(string strFile) { byte[] photo_byte = null; using (FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.Read)) { using (BinaryReader br = new BinaryReader(fs)) { photo_byte = br.ReadBytes((int)fs.Length); } } return photo_byte; } /// <summary> /// 从byte[]读取图片 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public Image getImageByBytes(byte[] bytes) { Image photo = null; using (MemoryStream ms = new MemoryStream(bytes)) { ms.Write(bytes, 0, bytes.Length); photo = Image.FromStream(ms, true); } return photo; } }
#region 将图片转换成字节数组 /// <summary> /// 将图片转换成字节数组 /// </summary> /// <param name="OpenF"></param> /// <param name="pb"></param> public void Read_ImageToByte(OpenFileDialog OpenF, PictureBox pb) { OpenF.Filter = "*.jpg|*.jpg|*.bmp|*.bmp";//指定OpenFileDialog控件打开的文件格式 if (OpenF.ShowDialog(this) == DialogResult.OK)//如果打开了图片文件 { try { pb.Image = System.Drawing.Image.FromFile(OpenF.FileName);//将图片文件存入到PictureBox控件中 string Picpath = OpenF.FileName.ToString(); FileStream fs = new FileStream(Picpath, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); imgBytesIn = br.ReadBytes((int)fs.Length); } catch { MessageBox.Show("您选择的图片不能被读取或文件类型不对!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning); pb.Image = null; } } } #endregion
#region 将图片存储到数据库中 /// <summary> /// 以二进制的形式将图片存储到数据库中. /// </summary> /// <param name="MID">职工编号</param> /// <param name="p">图片的二进制形式</param> public void SaveImage(string MID, byte[] p) { MyDataClass.Con_Open(); StringBuilder SqlStr = new StringBuilder(); SqlStr.Append("update tb_Staffbasic Set Photo=@Photo where ID=" + MID); SqlCommand cmd = new SqlCommand(SqlStr.ToString(), DataClass.MyMeans.My_con); cmd.Parameters.Add("@Photo", SqlDbType.Binary).Value = p; cmd.ExecuteNonQuery(); MyDataClass.Con_Close(); } #endregion