-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import puppeteer from "puppeteer"; | ||
|
||
export async function getImageSize( | ||
selectors: { id: string; classes: string[] }, | ||
htmlPath: string, | ||
screenSizes: Record<string, number>, | ||
): Promise<Record<string, number>> { | ||
// Browser instance | ||
const browser = await puppeteer.launch({ | ||
headless: "new", | ||
args: ["--start-maximized"], | ||
}); | ||
|
||
// Page to load | ||
const page = await browser.newPage(); | ||
|
||
const nativeScreenSize = await page.evaluate(() => { | ||
return { | ||
height: window.screen.availHeight, | ||
}; | ||
}); | ||
|
||
const imageSizes: Record<string, number> = {}; | ||
|
||
for (const screenKey of Object.keys(screenSizes)) { | ||
// Setting specific width and height for viewport | ||
await page.setViewport({ | ||
width: screenSizes[screenKey], | ||
height: nativeScreenSize.height, | ||
}); | ||
|
||
// Navigate to the htmlPath | ||
await page.goto(htmlPath); | ||
|
||
const selector: string = selectors.id | ||
? selectors.id | ||
: selectors.classes | ||
? selectors.classes[0] | ||
: "img"; | ||
|
||
// Extract the size of the image | ||
const imageSize = await page.evaluate((selector) => { | ||
const img: any = document.querySelector(selector); | ||
|
||
return { | ||
width: img?.width, | ||
height: img?.height, | ||
}; | ||
}, selector); | ||
|
||
imageSizes[screenKey] = imageSize as any; | ||
} | ||
|
||
// Close the browser | ||
await browser.close(); | ||
|
||
return imageSizes; | ||
} |