UNPKG

image-genv3

Version:

AI-powered image generation package to create stunning visuals from text prompts.

80 lines (66 loc) 2.93 kB
import fs from 'fs'; import fetch from 'node-fetch'; import sharp from 'sharp'; // Generate a random seed for unique image generation const generateRandomSeed = () => Math.floor(Math.random() * 1000000); // Main function to generate, download, and crop an image based on a text prompt async function generateImage({ prompt } = {}) { try { if (!prompt) { throw new Error('Prompt is required to generate an image.'); } // Hardcoded values for API request const model = 'flux'; const requestedWidth = 1024; const requestedHeight = 1024; const seed = generateRandomSeed(); // Construct the image URL const imageUrl = `https://pollinations.ai/p/${encodeURIComponent(prompt)}?width=${requestedWidth}&height=${requestedHeight}&seed=${seed}&model=${model}`; // Fetch the image from the URL const response = await fetch(imageUrl); if (!response.ok) { throw new Error(`Failed to fetch image: ${response.statusText}`); } // Read the response as an ArrayBuffer const arrayBuffer = await response.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); // Get actual image dimensions const metadata = await sharp(buffer).metadata(); const width = metadata.width; const height = metadata.height; // Ensure the image is large enough to crop 50 pixels from the bottom if (height < 50) { throw new Error(`Input image height (${height}px) is too small to crop 50px from the bottom`); } // Generate a unique filename based on timestamp and seed const timestamp = Date.now(); const finalImagePath = `./image-${timestamp}-${seed}.png`; // Crop 50 pixels from the bottom const croppedBuffer = await sharp(buffer) .extract({ left: 0, top: 0, width: width, height: height - 50 // Remove 50px from the bottom }) .png() // Ensure output is PNG .toBuffer(); // Verify the output image dimensions const croppedMetadata = await sharp(croppedBuffer).metadata(); if (croppedMetadata.width !== width || croppedMetadata.height !== height - 50) { throw new Error(`Output image dimensions (${croppedMetadata.width}x${croppedMetadata.height}) do not match expected (${width}x${height - 50})`); } // Write the cropped buffer to the final file fs.writeFileSync(finalImagePath, croppedBuffer); // Return the path to the cropped image console.log(`Image generated, cropped 50px from bottom, and saved as ${finalImagePath} (${width}x${height - 50})`); return { imagePath: finalImagePath, success: true, seed }; } catch (error) { console.error('Error generating image:', error.message); return { success: false, error: error.message }; } } // Export the function for use in other modules export default { response: generateImage, };