zoukankan      html  css  js  c++  java
  • 个人完成版---向数据库中以二进制方式存储图片---以及从数据库中读取二进制图片并转化为图片存储本地硬盘

    第一 向数据库中存二进制的图片数据

    //向数据库中以二进制的形式存储图片
    try
    {
    //获取当前图片的路径
    string FilePath = Server.MapPath("//hsPDFFiles/") + "zyh.jpg";
    //将制定路径的图片添加到FileStream类中
    FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
    //通过FileStream对象实例化BinaryReader对象
    BinaryReader br = new BinaryReader(fs);
    //通过BinaryReader类对象的ReadBytes()方法将FileStream类对象转化为二进制数组
    byte[] imgBytesIn = br.ReadBytes((int)(fs.Length));

    br.Close();//记得要关闭br
    fs.Close();//还有fs

    //第二步
    //将图片添加到数据库中
    string sql = string.Format(@"INSERT INTO dbo.cuProcedureImage( icuProcedureid ,sCaption ,Img ,iImgSize ,sRemark ,bDefalt ,dCreateDate ,sCreator)
    VALUES(1474, '用于做上传图片的测试',@imgBytesIn, 0, '', 1, GETDATE(),'cttsoft')");
    SqlParameter[] param = new SqlParameter[] { new SqlParameter("@imgBytesIn", imgBytesIn) };
    int cMount = 0;
    cMount = db.GetValueBySqlAsInteger(sql, param);

    //DBHelper.GetExecuteQuery(sql, param);
    }
    catch (Exception e)
    {
    throw e;
    }

    第二 从数据库取图片数据

    ---------------------------------------------------------------------------------------------------------------------------------------

    //从数据库取出一张图片 并显示出来
    if (!System.IO.Directory.Exists(Server.MapPath("//hsPDFFiles")))
    {
    Directory.CreateDirectory(Server.MapPath("//hsPDFFiles"));
    }
    string NewGuid = Guid.NewGuid().ToString();
    string FileName = NewGuid + ".jpg";
    //图片展示路径
    string ImgShowPath = "../hsPDFFiles/" + FileName;

    //实际存储路径
    string PhysiclSavePath = string.Empty;

    //实际存储路径--物理路径
    PhysiclSavePath = "" + Server.MapPath("//hsPDFFiles/") + FileName;

    PhysiclSavePath = PhysiclSavePath.Replace(@"", @"\");


    string ssql = string.Format(@"SELECT TOP 1 Img FROM cuProcedureImage (NOLOCK) ORDER BY dCreateDate DESC");

    DataTable dt = db.ExecuteDataTable(ssql, null);

    if (dt.Rows.Count == 0)
    {
    db = null;
    return View();
    }
    byte[] bytes = dt.Rows[0][0] as byte[];
    try
    {
    FileStream fs = new FileStream(PhysiclSavePath, FileMode.Append, FileAccess.Write);
    BinaryWriter bw = new BinaryWriter(fs);
    bw.Write(bytes, 0, bytes.Length);
    bw.Close();
    fs.Close();
    db = null;
    }
    catch (Exception ex)
    {
    db = null;
    throw ex;
    }

  • 相关阅读:
    JDBC五数据源和数据池(web基础学习笔记十一)
    JDBC四(web基础学习笔记十)
    JDBC三(web基础学习笔记九)
    JDBC二查询(web基础学习笔记八)
    JDBC一(web基础学习笔记七)
    HTML二(基本标签)
    Java从零开始学八(循环结构)
    如何合理地估算线程池大小?(转载)
    Java 8 Documentation Download
    Redis集群
  • 原文地址:https://www.cnblogs.com/yachao1120/p/6420536.html
Copyright © 2011-2022 走看看