-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetImages.js
96 lines (75 loc) · 2.73 KB
/
getImages.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const { S3Client, ListObjectsV2Command, GetObjectCommand } = require("@aws-sdk/client-s3");
const { getSignedUrl } = require("@aws-sdk/s3-request-presigner");
const sharp = require('sharp');
const fs = require('fs').promises;
// Configure the S3 client
const s3Client = new S3Client({
region: "us-east-1", // replace with your region
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_ACCESS_KEY_SECRET,
},
});
const bucketName = "meegan-farrell-art-bucket"; // replace with your bucket name
async function getImageDimensions(imageBuffer) {
const metadata = await sharp(imageBuffer).metadata();
return { width: metadata.width, height: metadata.height };
}
function parseImageName(input) {
const filename = input.split('/').pop();
const withoutFileExtension = filename.replace(/\.[^/.]+$/, "");
return withoutFileExtension;
}
function parseTitle(input) {
const filename = input.split('/').pop();
const withoutFileExtension = filename.replace(/\.[^/.]+$/, "");
if (!/^\d{2}/.test(withoutFileExtension)) {
return "";
}
// Remove leading digits
const withoutDigits = withoutFileExtension.replace(/^\d+/, '');
// Add space before capital letters, trim, and escape any existing quotes
const parsed = withoutDigits.replace(/([A-Z])/g, ' $1').trim().replace(/"/g, '\\"');
// Return the result wrapped in quotes
return `"${parsed}"`;
}
async function getImagesMetadata() {
const command = new ListObjectsV2Command({
Bucket: bucketName,
});
const data = await s3Client.send(command);
const images = [];
for (const object of data.Contents) {
if (object.Key.match(/\.(jpg|jpeg|png|gif)$/i)) {
const getObjectCommand = new GetObjectCommand({
Bucket: bucketName,
Key: object.Key,
});
const url = await getSignedUrl(s3Client, getObjectCommand, { expiresIn: 3600 });
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
const { width, height } = await getImageDimensions(buffer);
images.push({
original: `https://${bucketName}.s3.amazonaws.com/${object.Key}`,
src: `https://${bucketName}.s3.amazonaws.com/${object.Key}`,
alt: parseImageName(object.Key),
title: parseTitle(object.Key),
width,
height,
});
}
}
return images;
}
async function main() {
try {
console.log("Fetching image metadata...");
const images = await getImagesMetadata();
await fs.writeFile('imagesMetadata.json', JSON.stringify(images, null, 2));
console.log('Image metadata has been saved to imagesMetadata.json');
} catch (error) {
console.error('Error:', error);
}
}
main();