1

I'm developing an app that grabs the HTML from a webpage and looks at images, within the HTML, that can be compressed and resized.

I can do the first part no problem in node, using Sharp here:

https://www.npmjs.com/package/sharp

I can, of course, resize the same image here too. I just don't know what dimensions to use. I don't want a tiny image to scale up and so on.

Can I somehow detect the size of the image on screen using the HTML I got to begin with?

Thanks in advance.

EDIT:

Sorry for any confusion. I need to know how big the image is being displayed on the page. So, the image may be 400x400 but the css could limit it to 200x200.

If I have a large image (1000x1000) but it's only being shown on screen at 500x500, I'd know it's a great candidate for resizing.

I'm just not sure how I can resize based on it's css dimensions.

A Lower
  • 61
  • 1
  • 8

2 Answers2

1

I think in Sharp there's a metadata function that lets you access image metadata, e.g. format, width, height, etc.

Example:

const image = sharp(inputJpg);

image.metadata().then(function(metadata) {
    // print image width and height
    console.log({
        width: metadata.width,
        height: metadata.height
    });
});
Horace Lee
  • 146
  • 6
  • Thanks for the help. Are you aware of anything that helps with my edit above? Sorry for any confusion. – A Lower Aug 03 '18 at 07:17
  • Thanks for clarifying. Do you want to get the rendered image dimensions from the actual live webpage, or from the HTML source code that you've grabbed? – Horace Lee Aug 03 '18 at 07:58
  • It's much easier if you do it from the actual live webpage because you can just use `img.clientWidth` and `img.clientHeight` on the image element to detect its rendered dimensions ([see here](https://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript)). It might be more difficult to do it from the source code because some images might have dynamic dimensions - for example if someone used `width: 50%` then the image size would change depending on the browser window size. – Horace Lee Aug 03 '18 at 07:58
  • Thanks, Horace. Makes sense. – A Lower Aug 03 '18 at 08:15
-1

In Sharp library,

You can get dimension from this document: http://sharp.dimens.io/en/stable/search.html?q=dimension

Hope it will help you.

const sharpImage = sharp('test/test.jpg');
image.metadata().then(function(metadata) {
    console.log(metadata);
});
kiran malvi
  • 1,058
  • 10
  • 21
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/20485425) – eisbehr Aug 03 '18 at 07:41
  • Edited my answer @eisbehr – kiran malvi Aug 03 '18 at 07:54