首页 > 解决方案 > 使用 URI 编码动态创建图像 在 Web 窗体应用程序中使用延迟加载异步创建

问题描述

我正在使用数据 URI 编码(无 HttpHandler)在 Web 窗体应用程序中动态创建许多图像。图像是从数据库加载的,我正在使用同位素和延迟加载进行过滤。我在页面加载中使用异步任务来获取数据并加载到图像控件中。我还创建了缩略图并应用了图像压缩。无论如何,页面加载非常缓慢。在加载所有内容之前,我有一个白页。我是否正确处理了异步方法?这不应该首先允许在页面上显示其他内容吗?

页面加载方法

RegisterAsyncTask(new PageAsyncTask(LoadImages));

加载图像方法:

    public Task LoadImages()
    {
        //Get Data from DB
        DataTable dtImages = GetData();
        int id = 0;
        foreach (DataRow row in dtImages.Rows)
        {
            id = Convert.ToInt32(row["FILE_ID"].ToString());
            var category = row["CATEGORY"].ToString();
            Byte[] bytes = ((Byte[])row["THUMBNAIL_CONTENT"]);
            
            //Method to create the content on the page:
            CreateDiv(id, bytes);
        }
        return Task.FromResult(0);
    }
    

创建 HTML 通用控件的方法:

    public void CreateDiv(int imageID, byte[] fileBytes)
    {
        System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
        image.ID = "Image" + imageID.ToString() + "";
        if (imageID != 0)
        {
        //My animated gif:
            image.ImageUrl = "images/loader.gif"; ;
        }
        image.Attributes.Add("class", "img-fluid lazy");
        //The actual thumbnail:
        image.Attributes.Add("data-src", GetImage(fileBytes));
        image.Visible = true;
        PlaceHoldersDiv.Controls.Add(image);
    }
    

返回图片 URI 的方法:

    public string GetImage(object img)
    {
        return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
    }
    

延迟加载脚本:

document.addEventListener("DOMContentLoaded", function () {
    var lazyloadImages = document.querySelectorAll("img.lazy");
    var lazyloadThrottleTimeout;

    function lazyload() {
        if (lazyloadThrottleTimeout) {
            clearTimeout(lazyloadThrottleTimeout);
        }

        lazyloadThrottleTimeout = setTimeout(function () {
            var scrollTop = window.pageYOffset;
            lazyloadImages.forEach(function (img) {
                if (img.offsetTop < (window.innerHeight + scrollTop)) {
                    img.src = img.dataset.src;
                    img.classList.remove('lazy');
                }
            });
            if (lazyloadImages.length == 0) {
                document.removeEventListener("scroll", lazyload);
                window.removeEventListener("resize", lazyload);
                window.removeEventListener("orientationChange", lazyload);
            }
        }, 20);
    }

    document.addEventListener("scroll", lazyload);
    window.addEventListener("resize", lazyload);
    window.addEventListener("orientationChange", lazyload);
});

仅供参考,我尝试使用 Http 处理程序来加载图像,但性能要差得多!

标签: c#asp.netasynchronouswebformslazy-loading

解决方案


推荐阅读