Skip to content

Instantly share code, notes, and snippets.

@dtbaker
Created November 28, 2019 01:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dtbaker/a3fdbf20676928de56d466574ade9203 to your computer and use it in GitHub Desktop.
Save dtbaker/a3fdbf20676928de56d466574ade9203 to your computer and use it in GitHub Desktop.
Extract Images from Figma to S3
// This takes an array of images (from getFigmaImageIds) and exports them to S3.
const exportImagesFromFigma = async ({figmaImages, figmaExportScale = 1}) => {
const figmaFileId = await getSecretConfiguration('figma_file_id')
const figmaApiKey = await getSecretConfiguration('figma_api_key')
const exportedImages = []
const imageIdsToExport = figmaImages.map(image => image.imageId)
console.log(`Rendering image from https://api.figma.com .... `)
const figmaImageExportRequest = await fetch(`https://api.figma.com/v1/images/${figmaFileId}?ids=${imageIdsToExport.join(',')}&scale=${figmaExportScale}`, {
method: "get",
headers: {
"X-Figma-Token": figmaApiKey,
"Content-type": "application/json",
"Accept": "application/json",
"Accept-Charset": "utf-8"
}
})
const figmaImageExportResponse = await figmaImageExportRequest.json()
// If we try to download the image too quickly we've found it sometimes doesn't exist yet.
// So we wait a little bit just to ensure our exported image is ready for download before proceeding.
await sleep(2000)
for (const figmaImage of figmaImages) {
const tmpFilename = `/tmp/figma-${figmaImage.imageId}`
const downloadedBytes = await download(figmaImageExportResponse.images[figmaImage.imageId], tmpFilename)
const fileContents = fs.readFileSync(tmpFilename)
// Resise the image into:
// - x100 high PNG
// - x500 high PNG
// - x1000 high PNG
console.log('Generating thumbnails based on ' + fileContents.length)
const thumbnails = []
const thumbnailsPromise = []
// Some code here to create thumbnails from the obtained image data
// thumbnailsPromise.push( ......
console.log("waiting on thumbs to resize...")
await Promise.all(thumbnailsPromise).catch(console.error)
// Get the width and height of the downloaded image.
const dimensions = sizeOf(tmpFilename);
exportedImages.push({
itemId: figmaImage.itemId,
imageName: figmaImage.imageName,
imageId: figmaImage.imageId,
tmpFilename,
width: dimensions.width,
height: dimensions.height,
thumbnails,
})
}
return exportedImages
}
// This returns an array of matching figma image IDs that we can later use for exporting to S3.
const getFigmaImageIds = async ({itemId}) => {
const figmaFileId = await getSecretConfiguration('figma_file_id')
const figmaApiKey = await getSecretConfiguration('figma_api_key')
const imageIdsFromFigma = []
// This gets the entire figma JSON blog for the `Mixkit Art` figma board. It's big!
// We need this so we can loop through the pages and check the "name" of each page to find the one matching our itemId
console.log('Obtaining the full figma page output....')
const figmaApiRequest = await fetch(`https://api.figma.com/v1/files/${figmaFileId}`, {
method: "get",
headers: {
"X-Figma-Token": figmaApiKey,
"Content-type": "application/json",
"Accept": "application/json",
"Accept-Charset": "utf-8"
}
})
const figmaApiResponse = await figmaApiRequest.json()
// Now we use .find() to find which child page matches our provided item ID
const thisItemInFigma = figmaApiResponse.document.children.find(figmaPage => parseInt(figmaPage.name, 10) === itemId)
if (thisItemInFigma) {
console.log('Found the matching page in Figma for this item ID!')
// Now we loop through the child images of this page in Figma. These are all named correctly based on the variant.
for (const image of thisItemInFigma.children) {
if (
image.name === 'original' ||
image.name === 'square' ||
image.name === 'smartphone wallpaper' ||
image.name === 'desktop wallpaper' ||
image.name === 'colour'
) {
console.log(`Found ${image.name} image to export`)
imageIdsFromFigma.push({
itemId: itemId,
imageName: image.name.replace(/ /,'-'),
imageId: image.id,
})
}
}
}
return imageIdsFromFigma
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment