c# - 使用 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 处理程序来加载图像,但性能要差得多!
解决方案
推荐阅读
- .net-core - 查看 F# 项目 (fsproj) 的 dotnet 构建的编译器调用
- javascript - 当 if-else 满足条件时停止执行
- amazon-web-services - AWS redshift-data API:调用 DescribeStatement 操作时发生错误 (ResourceNotFoundException):查询不存在
- django - 如何显示用户网址头像
- python - 如何将信息从剧本传递到另一个剧本?
- node.js - 是否可以使用 MEVN 堆栈在某个日期前 x 小时向用户发送电子邮件提醒?
- android - how to post request message pack with okhttp3
- azure-active-directory - 使用R包AzureAuth获取的token查询数据
- ruby-on-rails - 如何在 Rails Admin 的显示和列表操作中使用关联集合的范围
- reactjs - React 测试库设置 window=undefined