使用 JavaScript,我可以将图像保存为它们的 CSS 缩略图大小吗?



也许是一个奇怪的用例,但假设以下代码,其中image1.jpg是1920x1080:

<a href="http://example.com/dir/photos/image1.jpg" target="_blank">
<img src="http://example.com/dir/photos/image1.jpg">
</a>

如您所见,图像在页面上完整加载;但是,上面未显示的是用于将该图像显示为页面上的缩略图(例如,480 x 270(的CSS。

是的,这是一种非常未经优化的做法。

我遇到的问题是,客户端在多个页面上发生了数百次这样的事件。我正在尝试快速创建图像的缩略图版本,完全按照页面上的大小。有些图像比其他图像更宽/更高,并且图像/文件夹名称到处都是,因此从渲染页面创建每个图像的缩略图是我想要完成的任务。

理想情况下,我正在考虑使用 JS(或 jQuery,如果有人知道任何特定方法(来定位所有图像(无论需要发生什么(最终创建和下载/保存缩略图作为其 CSS 大小的页面表示。

我希望这个问题是有意义的。如果需要,我很乐意澄清更多。感谢您提供的任何帮助!

以下代码从页面中获取所有图像,并将它们缩放到用于呈现的有效 CSS 大小,然后执行下载。 它的工作方式如下:

  1. 生成空画布元素
  2. 生成图像,并在其中加载原始图像元素源
  3. 使用原始图像大小在画布中转储新图像的内容。
  4. 将画布的内容转储回原始图像元素
  5. 执行 download(( 函数(仅适用于 chrome(

function scaleToElementSize(img){
return new Promise( (resolve,reject)=>{
// create an empty canvas and assign to it
// the rendered proportions of the provided image 
let c = document.createElement('canvas');
c.height = img.height;
c.width = img.width ;
const ctx = c.getContext("2d");
// create an image element, and load the source
// image in it
let i = new Image();
i.setAttribute('crossOrigin', 'anonymous');
i.src = img.src;
// when image is loaded, copy its contenta scaled     
// into the canvas, dump the resulting scaled
// image back, to the original image, and download
i.onload = ()=>{
ctx.drawImage(i, 0, 0, c.width, c.height); 
img.setAttribute('filename', img.src);
img.onload = null;
img.src =  c.toDataURL("image/png");
resolve();
}
});
}
function download(img){
var link = document.createElement('a');
link.download = img.getAttribute('filename');
link.href = img.src.replace("image/png", "image/octet-stream");;
link.click();
}
document.querySelectorAll('img').forEach( img=>{
img.onload= function(){ 
scaleToElementSize(img)
.then( ()=> download(img) )
}
})
<img src="https://placekitten.com/200/286?a.jpg" width="100">
<img src="https://placekitten.com/200/139?b.jpg" width="200">
<img src="https://placekitten.com/408/287?c.jpg" width="110">

最新更新