使用Javascript懒加载图像

Lazy load images with Javascript

本文关键字:图像 加载 Javascript 使用      更新时间:2023-12-19

我有一个面向最终用户的应用程序,用户可以在其中上传图像。当用户上传大量图像时,我的应用程序会变慢。

我们在一个模块中也使用了Angular JS Lazy加载图像,该模块生成不同大小的图像。https://github.com/afklm/ng-lazy-image

并根据设备和图像大小,准备图像。

现在我想用简单的javascript代码/process/技术做同样的事情。

有人能给我指路吗?

我可能有点跑题了,但我想说,最好提供一个调整大小的图像版本,这对客户端和;服务器

有很多库可以调整图像的大小,或者只使用本地php函数。

我更喜欢的程序是:->上传图片->保存图片->调整图片大小;用新的尺寸名称保存->然后取决于用户的选择,您向他们发送准确的图像

示例:

上传Image1.jpg(1000x1000像素)

-> gets Saved to '/images/Image1.jpg'
-> User request a (let's say) 200x200 size of that image
-> The script will resize to 200x200 and save it as Image1_200x200.jpg 
(which will have the real file size of 200x200, 
so the server will send the 200x200 image and not the 1000x1000 (original image)

这样你可以节省很多钱,更快地提供图像,然后你可以考虑懒惰地加载折叠下面的图像。

我个人使用WideImage,还有Zebra_Image。

WideImage我使用的代码是(带缓存的)

/* Merge, to get full path */ 
    $fullpath = $Path . $Filename;
    if (!file_exists($cache_dir)) {
        $old = umask(0);
        mkdir($cache_dir . DS, 0775);
        umask($old);
    }

    /* cache file */
    $cache = $cache_dir . DS . $Filename;
 /* Create Cache */
       if (!file_exists($cache) || $recreate === true)
        WideImage::load($fullpath)->resize($Width, $Height, 'outside')->crop(
                'center', 'center', $Width, $Height)->saveToFile($cache, $Quality);

    /* Return Cache filepath */
    return $cache;

$cache是我调整大小后保存的文件。

这在某种程度上脱离了主题,但我认为这会有所帮助。

干杯!