简体   繁体   English

从远程服务器获取时的图像压缩

[英]Image Compression when fetching from remote server

I have a JavaScript client application that uses another organization's APIs to fetch data. 我有一个JavaScript客户端应用程序,该应用程序使用另一个组织的API来获取数据。 Now there's lots of images those url are sent via the API. 现在,有许多图像这些URL是通过API发送的。

However the images are too large, ie, bulky in size around 1MB each. 但是,图像太大,即每个图像大约1MB。 If I put the image url in img tag, then the page slows when loading up as there are hundreds of images needs to be shown at page render. 如果将图像URL放在img标签中,则加载时页面会变慢,因为页面渲染时需要显示数百张图像。

Is there any way to compress the image at client end, cause my API are providers have just said no to send compressed image urls. 有什么办法可以在客户端压缩图像,因为我的API提供商只是说不发送压缩图像的URL。

The approach of this kind of problem usually involves lazy loading of images. 这类问题的解决方法通常涉及图像的延迟加载。 The approach could be: 该方法可以是:

  • Load only the images that are in the frame of your view, wait to load the next images until scroll reaches them 仅加载视图框架中的图像,等待加载下一张图像,直到滚动到达它们为止
  • Load image on demand (on click, hover and so on) 按需加载图像(单击,悬停等)

Although you can compress images client side, this will not avoid to download them from the server (100 img = 100MB in your case) 尽管您可以在客户端压缩图像,但这不会避免从服务器下载图像(在您的情况下为100 img = 100MB)

There are a lot of npm packages that lazy load components (and thus images) for you, like this 有很多npm软件包可以为您延迟加载组件(因此也可以加载图像),就像这样

I agree with Mosè Raguzzini's answer 我同意MosèRaguzzini的回答

Compressing the image in the front-end is not always suggested. 并非总是建议在前端压缩图像。

You should compress/ optimize the images before sending to the client side. 在发送到客户端之前,您应该压缩/优化图像。 The page is slow since its taking time to get the content from API only. 该页面很慢,因为它花费时间仅从API获取内容。 I assume that you are not using showing the image using data:/ as you have mentioned you are using URL in the image tag. 我假设您没有使用data:/来显示图像,就像您提到的那样,您正在image标签中使用URL。

You could do the following as well. 您也可以执行以下操作。

  1. Even though the other organizations API is not able to compress it you can create some back-end API which will do it for you or there are third-party tools available as well. 即使其他组织的API无法对其进行压缩,您也可以创建一些后端API来为您做到这一点,或者也可以使用第三方工具。
  2. Load image when its required (Lazy load) Please refer this URL for more info https://stackoverflow.com/search?q=Lazy+loading+images+javascript 必要时加载图片(延迟加载)。有关更多信息,请参考此URL https://stackoverflow.com/search?q=Lazy+loading+images+javascript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM