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


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

    //向数据库中以二进制的形式存储图片
    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;
    }

  • 相关阅读:
    sys.exc_info()方法:获取异常信息
    tempfile模块:生成临时文件和临时目录
    fnmatch模块:用于文件名的匹配
    pathlib模块用法详解
    linecache模块 随机读取文件指定行
    fileinput模块:逐行读取多个文件
    asyncio异步IO--协程(Coroutine)与任务(Task)详解
    Python中协程异步IO(asyncio)详解
    删除某个时间段之前的文件
    Mac入门--如何使用brew安装多个PHP版本
  • 原文地址:https://www.cnblogs.com/yachao1120/p/6420536.html
Copyright © 2020-2023  润新知