SQLserver用Image格式储存图片

前言

最近项目更新一个新需求,要求把图片储存在SQLserver中,而不是储存在本地磁盘。很好,又有新东西可以学了。

正文

一、建表

这里大概建几个字段演示一下

CREATE TABLE [dbo].[ImageFile](
	[Id] [UNIQUEIDENTIFIER] NOT NULL,
	[Name] [NVARCHAR](200) NULL,--文件名
	[Type] [NVARCHAR](50) NULL,--文件类型
	[Image] [IMAGE] NULL--文件
)

二、插入数据

一般写入数据在后端结合业务,这里只写一个控制台测试


        /// <summary>
        /// 插入图片
        /// </summary>
        /// <param name="filePath">图片文件夹路径</param>
public void ImportImage(string filePath)
        {
            string conn = "server=.;database=Test;Uid=sa;Pwd=1;";
            using (SqlConnection myconn = new SqlConnection(conn))
            {
                myconn.Open();
                using (SqlCommand mycomm = new SqlCommand())
                {
                    foreach (FileInfo item in dir.GetFiles("*.jpg"))//循环读取文件夹内的jpg文件
                    {
                        var pic = getJpgSize(item.FullName);
                        string str = string.Format("insert into ImageFile (ImageFileId,Name,Type,Image) values('{0}','{1}','{2}',@file)", Guid.NewGuid().ToString(), Path.GetFileNameWithoutExtension(item.FullName), item.Extension.Substring(1));//插入数据
                        mycomm.CommandText = str;
                        mycomm.Connection = myconn;
                        FileStream fs = new FileStream(item.FullName, FileMode.Open);
                        BinaryReader br = new BinaryReader(fs);
                        Byte[] byData = br.ReadBytes((int)fs.Length);
                        fs.Close();
                        mycomm.Parameters.Add("@file", SqlDbType.Binary, byData.Length);
                        mycomm.Parameters["@file"].Value = byData;
                        mycomm.ExecuteNonQuery();
                        mycomm.Parameters.Clear();
                    }
                }
            }
        }

三、读取文件

这一步根据不同的ORM框架来获取,可用 byte[] 对象承接图片

四、前端显示

1、这里默认是 png 格式,可根据实际情况写别的格式,jpg和png格式两个可以互换,只是记得png图片如果有透明区域转jpg后会变为白色,具体的大家可以试试
2、base64直接使用宽高默认为0,所以图片在 onload 时获取图片宽高
前端页面:

<img src="data:image/png;base64,这里写你的Base64代码" onload="imageLoad(this)" />

脚本:

// 获取图片真实高度
    function imageLoad(_this) {
        var imageSrc = $(_this).attr("src");
        var img = new Image();
        img.src = imageSrc;
        // 如果图片被缓存,则直接返回缓存数据
        if (img.complete) {
            var width = img.width > img.height ? 550 : 310;
            var height = img.height / img.width * width;
            $(_this).css("width", width + "px")
            $(_this).css("height", height + "px")
        } else {
            img.onload = function () {
                var width = img.width > img.height ? 550 : 310;
                var height = img.height / img.width * width;
                $(_this).css("width", width + "px")
                $(_this).css("height", height + "px")
            }
        }
    }

五、图片放大

如果需要对图片进行放大,但是项目内的插件没有带这个功能,可以使用下面的方法

image增加单击事件:

<img onclick="imgEnlarge(this)" src="data:image/png;base64,这里写你的Base64代码" onload="imageLoad(this)" />

前端页面增加一个div:

<div id="imgEnlargeDiv" style="display: none; text-align: center;position: fixed;z-index: 1000;top: 0;left: 0;width: 100%;height: 100%;background-color: rgba(255,255,255,.9);">
    <img id="bigimg" style="height: 90%;width: auto;border: 0px;margin: auto;position: absolute;top: 0;bottom: 0;left: 0;right: 0;" src="" />
</div>

脚本:

$(function () {
        $("#imgEnlargeDiv").click(function () {//再次点击淡出消失弹出层    
            $(this).fadeOut("fast");
        });
    });

    function imgShow(outerdiv, bigimg, _this) {
        var src = _this.attr("src");//获取当前点击的pimg元素中的src属性    
        $(bigimg).attr("src", src);//设置#bigimg元素的src属性
        $(outerdiv).fadeIn("fast");  //图片放大的div快速淡入显示层
    }

    function imgEnlarge(_this) {
        imgShow("#imgEnlargeDiv", "#bigimg", $(_this));
        $("img[type ='showImg']").mouseover(function () {
            $(this).css("cursor", "pointer");//鼠标移动到图片,鼠标箭头变为手势
        });
        $("img[type ='showImg']").click(function () {
            var _this = $(this);//将当前的pimg元素作为_this传入函数    
            imgShow("#imgEnlargeDiv", "#bigimg", _this);
        });
    }

最后

这些东西很多都是利用网上有的,只是个人感觉都比较零散,所以整理出来给大家参考,也是给我自己做一份笔记。
同时感谢那些乐于分享的人!

posted @ 2020-03-10 17:12  Murphy丶悦  阅读(4718)  评论(0编辑  收藏  举报