1.将图片转为字节流
public byte[] SaveImage(String path)//输入图片路径
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
BinaryReader br = new BinaryReader(fs);
byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中
return imgBytesIn;
}
2.将图片上传到数据库的Blob字段
private void UpLoadEanPic()
{
string picFile = "";
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;//该值确定是否可以选择多个文件
dialog.Title = "请选择需要存储到" + custCode + "中的EAN图片";
dialog.Filter = "图片文件(*.jpg,*.gif,*.bmp,*.png)|*.jpg;*.gif;*.bmp;*.png";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
picFile = dialog.FileName;
}
else
{
return;
}
byte[] picBytes = SaveImage(picFile);
string sqlInsertPic = string.Format(@"update cust_code_info set
ean_pic=:picBytes
where cust_code=:custCode");
OracleParameter op1 = new OracleParameter("picBytes", OracleType.Blob);
op1.Value = picBytes;
OracleParameter op2 = new OracleParameter("custCode", OracleType.VarChar);
op2.Value = custCode;
IDataParameter[] parameters = new IDataParameter[]{op1,op2};
int sqlRe = 0;
try
{
sqlRe = DBManager.DBHelp.Instance().ExecuteSql(sqlInsertPic, parameters);
}
catch(Exception ex)
{
MessageBox.Show("上传失败!"+ex.Message);
return;
}
if (sqlRe == 0)
{
MessageBox.Show("上传失败!请检查数据并重试!");
return;
}
else
{
MessageBox.Show("上传成功!");
btn_query_Click(null, null);
}
}
3.将blob字段转为image,即下载图片
private void btn_DownLoadEanPic_Click(object sender, EventArgs e)
{
string custCode = dataGridView1.CurrentRow.Cells["客户料号"].Value.ToString();
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "请选择文件路径";
if (dialog.ShowDialog() == DialogResult.OK)
{
string foldPath = dialog.SelectedPath;
string sqlGetEanPic = string.Format(@"SELECT
ean_pic
FROM
cust_code_info where cust_code='{0}'", custCode);
object reader = DBManager.DBHelp.Instance().GetDataSingle(sqlGetEanPic);
if (reader == Convert.DBNull)
{
MessageBox.Show("未上传EAN图片,请检查!");
return;
}
byte[] bytes = (byte[])reader;//读到的内容转化成字节流
System.IO.MemoryStream ms = new MemoryStream(bytes);//创建流
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);//从流中创建image对象
string format = GetImageFormat(img);
if (string.IsNullOrEmpty(format))
{
MessageBox.Show("文件格式已经损坏,请重新上传!");
return;
}
img.Save(foldPath + "\" + custCode + "图片" + format);//将image对象保存成图片存入指定位置
MessageBox.Show("保存成功!");
}
else
{
return;
}
}
4.获取image图片格式
private string GetImageFormat(Image _img)
{
string format;
if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
{
format = ".jpg";
return format;
}
if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
{
format = ".gif";
return format;
}
if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
{
format = ".png";
return format;
}
if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
{
format = ".bmp";
return format;
}
format = string.Empty;
return format;
}
不断积累!