{
  "name": "Image_gen",
  "nodes": [
    {
      "parameters": {
        "path": "image-generator",
        "formTitle": "AI Image Generator",
        "formDescription": "Generate beautiful images using AI",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Image Description",
              "fieldType": "textarea",
              "requiredField": true
            }
          ]
        },
        "responseMode": "responseNode",
        "options": {
          "ignoreBots": true
        }
      },
      "id": "b2fac489-5542-4e35-a01c-adbfb36a8efb",
      "name": "Form Trigger",
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2,
      "position": [
        -880,
        120
      ],
      "webhookId": "auto-generated"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "prompt_enhanced",
              "name": "enhanced_prompt",
              "value": "={{ $json['Image Description'] }}",
              "type": "string"
            },
            {
              "id": "image_size",
              "name": "image_size",
              "value": "={{ $json.size || '1024x1024' }}",
              "type": "string"
            },
            {
              "id": "image_quality",
              "name": "image_quality",
              "value": "={{ $json.quality || 'standard' }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "1b0e6560-2b64-4953-8c7b-152fa0ff032b",
      "name": "Prepare Request Data",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -660,
        120
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "enter_your_url_here",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "prompt",
              "value": "={{ $json.enhanced_prompt }}"
            },
            {
              "name": "model",
              "value": "dall-e-2"
            },
            {
              "name": "n",
              "value": "1"
            },
            {
              "name": "size",
              "value": "={{ $json.image_size }}"
            },
            {
              "name": "quality",
              "value": "={{ $json.image_quality }}"
            },
            {
              "name": "response_format",
              "value": "url"
            }
          ]
        },
        "options": {
          "timeout": 60000
        }
      },
      "id": "e87c8cb2-f987-4962-b7f4-d0dfb6f15ce8",
      "name": "Generate Image",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -440,
        120
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "Weo3N8CcoAB4aMA2",
          "name": "Header Auth account"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "success_condition",
              "leftValue": "={{ $json.data && $json.data.length > 0 }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equal"
              }
            },
            {
              "id": "956392c6-21bb-437b-a6e2-8a0149668682",
              "leftValue": "={{ $json.data[0].url }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              }
            },
            {
              "id": "f7d9748c-8d97-49ba-bb25-eba7b49d195a",
              "leftValue": "={{ $json.data[0].url }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "notExists",
                "singleValue": true
              }
            }
          ],
          "combinator": "or"
        },
        "options": {}
      },
      "id": "8abcc2bd-f4f6-458c-9172-2b068b35f19a",
      "name": "Check Success",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        -220,
        120
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "image_url",
              "name": "image_url",
              "value": "={{ $json.data[0].url }}",
              "type": "string"
            },
            {
              "id": "revised_prompt",
              "name": "revised_prompt",
              "value": "={{ $json.data[0].revised_prompt || 'N/A' }}",
              "type": "string"
            },
            {
              "id": "generation_timestamp",
              "name": "generation_timestamp",
              "value": "={{ new Date().toISOString() }}",
              "type": "string"
            },
            {
              "id": "status",
              "name": "status",
              "value": "success",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "2703d400-5f94-4f58-bc40-d3c97c2b921c",
      "name": "Extract Image URL",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        0,
        20
      ]
    },
    {
      "parameters": {
        "url": "={{ $json.image_url }}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file"
            }
          },
          "timeout": 30000
        }
      },
      "id": "31d4a415-dc45-460c-b73e-7bfd16c3f135",
      "name": "Download Image",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        220,
        20
      ]
    },
    {
      "parameters": {
        "jsCode": "// Helper function to format bytes\nfunction formatBytes(bytes, decimals = 2) {\n  if (bytes === 0) return '0 Bytes';\n  \n  const k = 1024;\n  const dm = decimals < 0 ? 0 : decimals;\n  const sizes = ['Bytes', 'KB', 'MB', 'GB'];\n  \n  const i = Math.floor(Math.log(bytes) / Math.log(k));\n  \n  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];\n}\n\n// Get image data and metadata safely\nlet imageBase64 = '';\nlet contentType = 'image/png';\nlet extractedData = {\n  image_url: 'Generated via OpenAI API',\n  original_prompt: 'AI Generated Image',\n  revised_prompt: 'AI Generated Image',\n  generation_timestamp: new Date().toISOString()\n};\n\ntry {\n  // Get binary data\n  if ($binary && $binary.data && $binary.data.data) {\n    imageBase64 = $binary.data.data;\n    contentType = $binary.data.mimeType || 'image/png';\n  }\n  \n  // Get data from previous nodes - use $input to get data from previous node\n  const inputData = $input.all();\n  \n  // Try to find the Extract Image URL node data\n  for (const item of inputData) {\n    if (item.json && item.json.image_url) {\n      extractedData = {\n        image_url: item.json.image_url || 'Generated via OpenAI API',\n        original_prompt: item.json.original_prompt || 'AI Generated Image',\n        revised_prompt: item.json.revised_prompt || 'AI Generated Image',\n        generation_timestamp: item.json.generation_timestamp || new Date().toISOString()\n      };\n      break;\n    }\n  }\n  \n} catch (error) {\n  console.log('Error accessing data:', error);\n  // Use default values already set above\n}\n\n// Create data URI for immediate display\nconst dataUri = imageBase64 ? `data:${contentType};base64,${imageBase64}` : '';\n\n// Safe string processing\nconst safeOriginalPrompt = (extractedData.original_prompt || 'AI Generated Image').toString();\nconst safeRevisedPrompt = (extractedData.revised_prompt || 'AI Generated Image').toString();\nconst safeImageUrl = (extractedData.image_url || 'Generated via OpenAI API').toString();\nconst safeContentType = (contentType || 'image/png').toString();\nconst fileExtension = safeContentType.includes('/') ? safeContentType.split('/')[1] : 'png';\n\n// Generate HTML for image display\nconst imageHtml = `\n<div style=\"max-width: 800px; margin: 20px auto; padding: 20px; font-family: Arial, sans-serif; background: #f9f9f9; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);\">\n  <h2 style=\"color: #333; text-align: center; margin-bottom: 20px;\">🎨 Generated Image</h2>\n  \n  <div style=\"text-align: center; margin-bottom: 20px;\">\n    ${dataUri ? \n      `<img src=\"${dataUri}\" alt=\"Generated Image\" style=\"max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.2);\" />` : \n      (safeImageUrl && safeImageUrl !== 'Generated via OpenAI API' ? \n        `<img src=\"${safeImageUrl}\" alt=\"Generated Image\" style=\"max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.2);\" crossorigin=\"anonymous\" />` : \n        '<p style=\"color: #666; font-style: italic;\">Image not available</p>'\n      )\n    }\n  </div>\n  \n  <div style=\"background: white; padding: 15px; border-radius: 8px; margin-top: 20px;\">\n    <h3 style=\"color: #555; margin-top: 0;\">📝 Prompt Details</h3>\n    <p><strong>Original Prompt:</strong> ${safeOriginalPrompt}</p>\n    <p><strong>Revised Prompt:</strong> ${safeRevisedPrompt}</p>\n    <p><strong>Generated:</strong> ${new Date(extractedData.generation_timestamp).toLocaleString()}</p>\n    <p><strong>Content Type:</strong> ${safeContentType}</p>\n    ${imageBase64 ? `<p><strong>Base64 Size:</strong> ${formatBytes(Math.round(imageBase64.length * 0.75))}</p>` : '<p><strong>Display Mode:</strong> Direct URL (Base64 conversion failed)</p>'}\n  </div>\n  \n  <div style=\"background: white; padding: 15px; border-radius: 8px; margin-top: 15px;\">\n    <h3 style=\"color: #555; margin-top: 0;\">🔗 Download Options</h3>\n    ${dataUri ? `<a href=\"${dataUri}\" download=\"generated-image.${fileExtension}\" style=\"display: inline-block; background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;\">💾 Download Base64</a>` : ''}\n    <a href=\"${safeImageUrl}\" target=\"_blank\" download=\"generated-image.${fileExtension}\" style=\"display: inline-block; background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;\">💾 Download Original</a>\n    <a href=\"${safeImageUrl}\" target=\"_blank\" style=\"display: inline-block; background: #6c757d; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;\">🌐 View Full Size</a>\n  </div>\n</div>\n`;\n\n// JavaScript code for interactive features - safely handle all string operations\nconst interactiveJs = `\n<script>\n// Function to copy image data URI to clipboard\nfunction copyImageData() {\n  const dataUri = '${dataUri.replace(/'/g, \"\\\\'\").replace(/\\\\/g, '\\\\\\\\')}' ;\n  if (dataUri && dataUri.length > 20) {\n    navigator.clipboard.writeText(dataUri).then(() => {\n      alert('Image data URI copied to clipboard!');\n    }).catch(err => {\n      console.error('Failed to copy: ', err);\n      alert('Failed to copy to clipboard');\n    });\n  } else {\n    alert('No image data available to copy');\n  }\n}\n\n// Function to share image (if supported)\nfunction shareImage() {\n  const dataUri = '${dataUri.replace(/'/g, \"\\\\'\").replace(/\\\\/g, '\\\\\\\\')}' ;\n  \n  if (navigator.share && dataUri && dataUri.length > 20) {\n    try {\n      const blob = dataURItoBlob(dataUri);\n      const file = new File([blob], 'generated-image.${fileExtension}', { type: '${safeContentType}' });\n      \n      navigator.share({\n        title: 'AI Generated Image',\n        text: 'Check out this AI generated image: ${safeOriginalPrompt.replace(/'/g, \"\\\\'\").replace(/\\\\/g, '\\\\\\\\')}' ,\n        files: [file]\n      });\n    } catch (error) {\n      console.error('Share failed:', error);\n      copyImageData();\n    }\n  } else {\n    // Fallback for browsers that don't support Web Share API\n    copyImageData();\n  }\n}\n\n// Helper function to convert data URI to blob\nfunction dataURItoBlob(dataURI) {\n  if (!dataURI || dataURI.length < 20) return null;\n  \n  try {\n    const byteString = atob(dataURI.split(',')[1]);\n    const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];\n    const ab = new ArrayBuffer(byteString.length);\n    const ia = new Uint8Array(ab);\n    \n    for (let i = 0; i < byteString.length; i++) {\n      ia[i] = byteString.charCodeAt(i);\n    }\n    \n    return new Blob([ab], { type: mimeString });\n  } catch (error) {\n    console.error('Failed to convert data URI to blob:', error);\n    return null;\n  }\n}\n\n// Add event listeners when DOM is ready\ndocument.addEventListener('DOMContentLoaded', function() {\n  console.log('Image display loaded successfully');\n});\n</script>\n`;\n\n// Calculate file size safely\nconst fileSizeBytes = (imageBase64 && imageBase64.length) ? Math.round(imageBase64.length * 0.75) : 0;\n\n// Return formatted response with multiple display options\nreturn {\n  status: 'success',\n  message: 'Image generated and processed successfully!',\n  data: {\n    // Original data\n    image_url: safeImageUrl,\n    image_base64: imageBase64,\n    content_type: safeContentType,\n    original_prompt: safeOriginalPrompt,\n    revised_prompt: safeRevisedPrompt,\n    timestamp: extractedData.generation_timestamp,\n    \n    // Display options\n    data_uri: dataUri,\n    html_display: imageHtml,\n    interactive_js: interactiveJs,\n    \n    // Image metadata\n    file_size_bytes: fileSizeBytes,\n    file_size_human: formatBytes(fileSizeBytes)\n  }\n};"
      },
      "id": "2d629505-13fd-4660-afac-220ddb438803",
      "name": "Process Image with JavaScript",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        20
      ]
    },
    {
      "parameters": {
        "respondWith": "redirect",
        "redirectURL": "={{ $json.data.image_url }}",
        "options": {}
      },
      "id": "7f169d11-2cf9-49b2-a1e7-a9563c8482ca",
      "name": "Respond to Webhook",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        660,
        120
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "error_message",
              "name": "error_message",
              "value": "={{ $json.error?.message || 'Failed to generate image' }}",
              "type": "string"
            },
            {
              "id": "original_prompt",
              "name": "original_prompt",
              "value": "={{ $('Form Trigger1').item.json.prompt }}",
              "type": "string"
            },
            {
              "id": "generation_timestamp",
              "name": "generation_timestamp",
              "value": "={{ new Date().toISOString() }}",
              "type": "string"
            },
            {
              "id": "status",
              "name": "status",
              "value": "error",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "8cc61ee7-3ab1-4115-98a7-59c9b2d67e36",
      "name": "Format Error Response1",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        440,
        220
      ]
    }
  ],
  "pinData": {},
  "connections": {
    "Form Trigger": {
      "main": [
        [
          {
            "node": "Prepare Request Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Request Data": {
      "main": [
        [
          {
            "node": "Generate Image",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Image": {
      "main": [
        [
          {
            "node": "Check Success",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Success": {
      "main": [
        [
          {
            "node": "Extract Image URL",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Format Error Response1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Image URL": {
      "main": [
        [
          {
            "node": "Download Image",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download Image": {
      "main": [
        [
          {
            "node": "Process Image with JavaScript",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process Image with JavaScript": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Error Response1": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "2f8996f7-feab-4957-928f-98e8d4210e36",
  "meta": {
    "instanceId": "9c269491062dc59e1b783da5b7c196b4239306151d1986cdfed697bdf5f04c6b"
  },
  "id": "74FHDHMHT6oNToAR",
  "tags": []
}