使用懒加载优化系统消耗

This commit is contained in:
Kakune55 2024-04-11 20:10:02 +08:00
parent 7a5dde7169
commit b950ae8b76
4 changed files with 51 additions and 50 deletions

View File

@ -59,6 +59,7 @@ def raedZip(bookid: str, index: int):
# 读取图片数据 # 读取图片数据
image_data = zip_ref.read(image_filename) image_data = zip_ref.read(image_filename)
zip_ref.close()
return image_data, image_filename return image_data, image_filename
except zipfile.BadZipFile: # 异常处理 except zipfile.BadZipFile: # 异常处理
@ -74,6 +75,7 @@ def thumbnail(input,size=(400,800)):
im.thumbnail(size) im.thumbnail(size)
output_io = io.BytesIO() output_io = io.BytesIO()
im.save(output_io,format='WEBP') im.save(output_io,format='WEBP')
im.close()
output_io.seek(0) output_io.seek(0)
return output_io return output_io
@ -83,6 +85,7 @@ def imageToWebP(input):
im = im.convert('RGB') im = im.convert('RGB')
output_io = io.BytesIO() output_io = io.BytesIO()
im.save(output_io,format='WEBP') im.save(output_io,format='WEBP')
im.close()
output_io.seek(0) output_io.seek(0)
return output_io return output_io

12
main.py
View File

@ -1,4 +1,4 @@
import configparser, os import configparser, gc
import db, file import db, file
from flask import * from flask import *
@ -68,16 +68,17 @@ def img(bookid, index): # 图片接口
return abort(404) return abort(404)
# 设置响应类型为图片 # 设置响应类型为图片
data, filename = file.raedZip(bookid,index) data, filename = file.raedZip(bookid,index)
if isinstance(data, str):
abort(404)
if request.args.get("mini") == "yes": if request.args.get("mini") == "yes":
data = file.thumbnail(data) data = file.thumbnail(data)
else: else:
data = file.imageToWebP(data) data = file.imageToWebP(data)
if isinstance(data, str):
abort(404)
response = make_response(data) #读取文件 response = make_response(data) #读取文件
del data del data
response.headers.set('Content-Type', 'image/Webp') response.headers.set('Content-Type', 'image/Webp')
response.headers.set('Content-Disposition', 'inline', filename=filename) response.headers.set('Content-Disposition', 'inline', filename=filename)
gc.collect()
return response return response
@ -85,7 +86,10 @@ def img(bookid, index): # 图片接口
def book(bookid): # 接口 def book(bookid): # 接口
if request.cookies.get("islogin") is None: if request.cookies.get("islogin") is None:
return abort(403) return abort(403)
return render_template("view.html",data = bookid) data = db.searchByid(bookid)
if data == "":
return abort(404)
return render_template("view.html",id = bookid , index = range(1,data[0][3]))
@app.route("/view/<bookid>") @app.route("/view/<bookid>")

BIN
static/loading.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

View File

@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
@ -23,56 +24,49 @@
height: auto; height: auto;
margin-bottom: 20px; margin-bottom: 20px;
} }
img {
display: block;
width: 100%;
min-height: 100px;
margin-top: 10px;
}
</style> </style>
</head> </head>
<body> <body>
<div id="comic-container"></div> {% for i in index %}
<img data-src="/api/img/{{ id }}/{{ i }}" loading="lazy" alt="{{ i }}" class="imgs">
{% endfor %}
<div style="display:flex;justify-content: center; align-items:center;">
<img src="/static/loading.gif" id="loadingGIF">
</div>
<script>
var imgs = document.querySelectorAll('.imgs');
<script> //offsetTop是元素与offsetParent的距离循环获取直到页面顶部
document.addEventListener('DOMContentLoaded', function () { function getTop(e) {
const comicId = getComicIdFromURL(); var T = e.offsetTop;
if (comicId) { while (e = e.offsetParent) {
displayComic(comicId); T += e.offsetTop;
} else { }
console.error('No comic ID found in URL'); return T;
}
});
// 从当前URL中获取漫画ID
function getComicIdFromURL() {
const urlParts = window.location.pathname.split('/');
return urlParts[2]; // 第三部分是漫画ID
}
// 显示漫画
function displayComic(comicId) {
let currentImageIndex = 1;
const comicContainer = document.getElementById('comic-container');
function loadNextImage() {
const imageUrl = `/api/img/${comicId}/${currentImageIndex}`;
fetch(imageUrl)
.then(response => {
if (response.ok) {
const img = document.createElement('img');
img.src = imageUrl;
img.classList.add('comic-image');
comicContainer.appendChild(img);
currentImageIndex++;
// 添加延迟,以控制加载速度
setTimeout(loadNextImage, 500);
} else {
console.error('Error loading image:', response.statusText);
}
})
.catch(error => {
console.error('Error loading image:', error);
});
} }
// 加载第一张图片 function lazyLoad(imgs) {
loadNextImage(); var H = document.documentElement.clientHeight;//获取可视区域高度
} var S = document.documentElement.scrollTop || document.body.scrollTop;
</script> for (var i = 0; i < imgs.length; i++) {
if (H + S > getTop(imgs[i])) {
imgs[i].src = imgs[i].getAttribute('data-src');
}
}
}
window.onload = window.onscroll = function () { //onscroll()在滚动条滚动的时候触发
lazyLoad(imgs);
}
</script>
</body> </body>
</html>
</html>