import '@johnlindquist/kit'
import type { AxiosResponse } from 'axios'
try {
const imageUrl: string = await arg('Enter the image URL')
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)
const base64Image: string = imageBuffer.toString('base64')
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'
}
const imageType: string = getImageType(imageBuffer)
const base64String: string = `data:image/${imageType};base64,${base64Image}`
const altText: string = await arg('Enter alt text for the image')
const markdown: string = ``
await clipboard.writeText(markdown)
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}`));
}