How to automatically generate resized images and HTML markup for the picture element?

时间:2019-01-07 13:10:23

标签: html css node.js cloudinary responsive-images

I'm trying to automate the build process for resizing images and generating HTML markup for these generated pictures. The problem is that I can't figure out how to do the latter part.

I've used the plugin gulp-responsive for resizing as many images as I want. Though, It is not a health workflow, as I would still have to hard code the HTML <picture> for each of them.

Besides that, I've read about Cloudinary's API which resizes and art direct the images (a better approach than the Gulp plugin one). The problem is that after reading the API docs for Node.js I couldn't see how to automatically generate HTML markup (just like in this site) or even download the generated images.

2 个答案:

答案 0 :(得分:1)

您可以通过API或UI在Cloudinary中上传资源。如果您使用API​​,则将获得带有可在HTML中使用的资源URL的JSON响应。像这样:https://cloudinary.com/documentation/image_upload_api_reference#upload_method(在示例响应下阅读)

如果您使用媒体库UI上传资源:https://cloudinary.com/console/media_library/folders/all/,则在打开图像(缩略图右上方的“编辑”图标)或图像上有一个小图钉后,您将看到URL。您可以单击缩略图,它会自动复制图像URL。

答案 1 :(得分:0)

由于我的Google搜索缺乏答案,难以进行的编码实验以及在阅读了一些文章之后,我想到自动为调整大小的图像生成标记可能不是最佳选择。

问题是:也许最好使用浏览器开发人员工具记录我应该在特定断点处使用的图像分辨率,然后对标记进行硬编码。这种方法可以避免天真地自动提高带有断点的分辨率,例如:

<picture>
  <source srcset="./doge-280w.png" 
          media="(max-width: 310px)">

  <source srcset="./doge-472w.png" 
          media="(max-width: 500px)">

  <source srcset="./doge-626w.png" 
          media="(max-width: 575px)">

  <img src="./doge-1000w.png"
       alt="">
</picture>

虽然上面生成的标记可能适用于某些图像,但不适用于那些在较高的断点处需要较小分辨率的图像。

  

如果图像在较高的断点处变小,则使用上述自动生成的标记将不必要地为用户提供更大的文件,从而破坏了响应图像的概念。

因此,手动记笔记使我们能够检测到此类图像并向用户提供最佳图像尺寸。