// Name: Image to Base64 Markdown // Description: Convert image URL to Base64 Markdown & copy to clipboard // Author: johnlindquist import '@johnlindquist/kit' import type { AxiosResponse } from 'axios' /** * Converts an image from a URL to Base64 Markdown and copies it to the clipboard. */ try { // Prompt for the image URL const imageUrl: string = await arg('Enter the image URL') // Fetch the image data as ArrayBuffer const response: AxiosResponse<ArrayBuffer> = await get(imageUrl, { responseType: 'arraybuffer' }) if (!response.data) { throw new Error(`Failed to fetch image from URL: ${imageUrl}`); } const imageBuffer: Buffer = Buffer.from(response.data) // Convert to Base64 const base64Image: string = imageBuffer.toString('base64') /** * Determines the image type based on the buffer's magic number. * @param buffer The image buffer. * @returns The image type (png, jpg, gif) or 'png' as default. */ function getImageType(buffer: Buffer): string { const hex = buffer.toString('hex').toUpperCase() if (hex.startsWith('89504E47')) return 'png' if (hex.startsWith('FFD8FF')) return 'jpg' if (hex.startsWith('474946')) return 'gif' return 'png' // Default to png } const imageType: string = getImageType(imageBuffer) const base64String: string = `data:image/${imageType};base64,${base64Image}` // Prompt for alt text const altText: string = await arg('Enter alt text for the image') // Create Markdown format const markdown: string = `` // Copy to clipboard await clipboard.writeText(markdown) // Display confirmation await div( md(` # Image Converted to Base64 Markdown ## Copied to clipboard! <img src="${base64String}" alt="${altText}" class="w-64 h-64 object-cover" /> `) ) } catch (error) { console.error(`An error occurred: ${error.message}`); await div(md(`## Error: Failed to convert image\n\n${error.message}`)); }