预加载照片擦除图库的图像



所以我有一个图像数组,我想使用 Photoswipe 加载到图库中,但我在预定义图像宽度和高度时遇到问题。具体来说,我认为我需要预加载图像

这是我的JS来呈现页面,在这里我定义幻灯片并列出为ejs页面使用的局部变量:

    var sizeOf = require('image-size');
    var url = require('url');
    var http = require('http');
    var slideshow = [];
    for(var i = 0; i < listing.listing_images.length; i++) {
        var image = listing.listing_images[i];
        var width, height = 0;
        var imgUrl = image.url;
        var options = url.parse(imgUrl);
        http.get(options, function (response) {
            var chunks = [];
            response.on('data', function (chunk) {
                chunks.push(chunk);
            }).on('end', function() {
                var buffer = Buffer.concat(chunks);
                **height = sizeOf(buffer).height;
                width = sizeOf(buffer).width;**
            });
        });
        var item = {
            src: image.url,
            h: height,
            w: width
        };
        slideshow.push(item);
    }
    res.render('example.ejs', {
        listing: listing,
        slides: slideshow
    });

这是 ejs 页面中的脚本:

<% var slides = locals.slides %>
<script>
$('document').ready(function() {
    var pswpElement = document.querySelectorAll('.pswp')[0];
    // build items array using slideshow variable 
    var items = <%- JSON.stringify(slides) %>;
    console.log(items);
    // grab image
    if (items.length > 0) {
        // define options (if needed)
        var options = {
            // optionName: 'option value'
            // for example:
            index: 0 // start at first slide
        };
        // Initializes and opens PhotoSwipe
        var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
        gallery.init();
    }
</script>

基本上发生的事情是 photowipe

项目的数组被很好地传递,但在 photowipe 初始化并触发 img 加载之前,宽度和高度不会设置。因此,图像不会显示,因为它们的高度和宽度尚未设置。

有没有办法触发幻灯片阵列中图像的加载,以便在传递到 Photowipe 之前设置宽度和高度?我也尝试过看看我是否可以将它们最初设置为 0,然后稍后尝试更新高度和宽度并尝试强制 photowipe 重新加载,但 photowipe 无法识别图像的新高度/宽度。

抱歉,如果其中有任何不清楚/与 ejs 废话混淆,请随时问任何事情,我很乐意澄清。

谢谢

最终利用 API 解决了这个问题:

gallery.listen('gettingData', function(index, item) {
        // index - index of a slide that was loaded
        // item - slide object
        var img = new Image();
        img.src = item.src;
        item.h = img.height;
        item.w = img.width;
    });
    gallery.invalidateCurrItems();
// updates the content of slides
    gallery.updateSize(true);

如果有人碰巧正在阅读本文,并且有一种更好的方法可以在不创建新的 img 的情况下读取图像大小,或者优化它,我希望得到建议。 :)

最新更新