[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M783BY2ESPWYB2E18BRCBR07":3,"skill-same:01M783BY2ESPWYB2E18BRCBR07":56},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":15,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":13,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M783BY2ESPWYB2E18BRCBR07","image-edit",null,"Implement AI image editing and modification capabilities using the z-ai-web-dev-sdk. Use this skill when the user needs to edit existing images, create variations, modify visual content, redesign assets, or transform images based on text descriptions. Supports multiple image sizes and returns base64 encoded results. Also includes CLI tool for quick image editing.","nordeim\u002Fyoga-studio","nordeim","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F194583642?v=4","01M75CZEV8C3V4DDQNPQ1EA7QJ","01M782NVR9711WMKQXZBPA5P70",0,"MIT","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fimage-edit\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fimage-edit\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: image-edit\ndescription: Implement AI image editing and modification capabilities using the z-ai-web-dev-sdk. Use this skill when the user needs to edit existing images, create variations, modify visual content, redesign assets, or transform images based on text descriptions. Supports multiple image sizes and returns base64 encoded results. Also includes CLI tool for quick image editing.\nlicense: MIT\n---\n\n# Image Edit Skill\n\nThis skill guides the implementation of image editing and modification functionality using the z-ai-web-dev-sdk package and CLI tool, enabling intelligent transformation and editing of images based on text descriptions.\n\n## Skills Path\n\n**Skill Location**: `{project_path}\u002Fskills\u002Fimage-edit`\n\nthis skill is located at above path in your project.\n\n**Reference Scripts**: Example test scripts are available in the `{Skill Location}\u002Fscripts\u002F` directory for quick testing and reference. See `{Skill Location}\u002Fscripts\u002Fimage-edit.ts` for a working example.\n\n## Overview\n\nImage Edit allows you to build applications that modify, transform, and enhance existing images using AI models. Perfect for redesigning assets, creating variations, improving visual content, and transforming images based on textual descriptions.\n\n**IMPORTANT**: z-ai-web-dev-sdk MUST be used in backend code only. Never use it in client-side code.\n\n## SDK API Method\n\nThe image editing functionality uses the following API method:\n\n```javascript\nawait zai.images.generations.edit({\n  prompt: string,              \u002F\u002F Required: Description of the edit to apply\n  images: [{ url: string }],  \u002F\u002F Required: Array with image URL or base64 data URL\n  size?: string,              \u002F\u002F Optional: Output size (default: '1024x1024')\n  model?: string              \u002F\u002F Optional: Model name\n})\n```\n\n**Important**: The `images` parameter must be an array of objects with a `url` property, not a plain string.\n\n**API Endpoint**: `POST \u002Fimages\u002Fgenerations\u002Fedit`\n\n**Returns**: `ImageGenerationResponse` with base64 encoded edited image\n\n## Prerequisites\n\nThe z-ai-web-dev-sdk package is already installed. Import it as shown in the examples below.\n\n## Basic Image Editing\n\n### Simple Image Transformation\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\nasync function editImage(imageSource, editPrompt, outputPath, size = '1024x1024') {\n  const zai = await ZAI.create();\n\n  const response = await zai.images.generations.edit({\n    prompt: editPrompt,\n    images: [{ url: imageSource }],  \u002F\u002F Array of objects with url property\n    size: size\n  });\n\n  const imageBase64 = response.data[0].base64;\n  \n  \u002F\u002F Save edited image\n  const buffer = Buffer.from(imageBase64, 'base64');\n  fs.writeFileSync(outputPath, buffer);\n  \n  console.log(`Edited image saved to ${outputPath}`);\n  return outputPath;\n}\n\n\u002F\u002F Usage - Using remote image URL\nawait editImage(\n  'https:\u002F\u002Fexample.com\u002Flandscape.jpg',\n  'Transform this landscape into a night scene with stars and moon',\n  '.\u002Flandscape_night.png'\n);\n\n\u002F\u002F Usage - Using local image converted to base64\nimport { readFileSync } from 'fs';\nconst imageBuffer = readFileSync('.\u002Fphoto.jpg');\nconst base64Image = imageBuffer.toString('base64');\nconst dataUrl = `data:image\u002Fjpeg;base64,${base64Image}`;\n\nawait editImage(\n  dataUrl,\n  'Change the cat to a dog, keep everything else the same',\n  '.\u002Fdog_version.png'\n);\n```\n\n### Create Image Variations\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\nasync function createVariation(imageSource, baseDescription, variation, outputPath, size = '1024x1024') {\n  const zai = await ZAI.create();\n\n  \u002F\u002F Combine base description with variation request\n  const prompt = `${baseDescription}, ${variation}`;\n\n  const response = await zai.images.generations.edit({\n    prompt: prompt,\n    images: [{ url: imageSource }],\n    size: size\n  });\n\n  const imageBase64 = response.data[0].base64;\n  const buffer = Buffer.from(imageBase64, 'base64');\n  fs.writeFileSync(outputPath, buffer);\n\n  return {\n    path: outputPath,\n    prompt: prompt,\n    variation: variation\n  };\n}\n\n\u002F\u002F Usage - Create variations from original image\nawait createVariation(\n  'https:\u002F\u002Fexample.com\u002Fheadshot.jpg',\n  'Professional headshot photo',\n  'with blue background instead of gray',\n  '.\u002Fheadshot_blue.png'\n);\n\nawait createVariation(\n  '.\u002Fsmartphone.png',\n  'Product photo of smartphone',\n  'on wooden table instead of white background',\n  '.\u002Fproduct_wood.png'\n);\n```\n\n### Multiple Image Sizes for Editing\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\n\u002F\u002F Supported sizes\nconst SUPPORTED_SIZES = [\n  '1024x1024',  \u002F\u002F Square\n  '768x1344',   \u002F\u002F Portrait\n  '864x1152',   \u002F\u002F Portrait\n  '1344x768',   \u002F\u002F Landscape\n  '1152x864',   \u002F\u002F Landscape\n  '1440x720',   \u002F\u002F Wide landscape\n  '720x1440'    \u002F\u002F Tall portrait\n];\n\nasync function editImageWithSize(imageSource, editPrompt, size, outputPath) {\n  if (!SUPPORTED_SIZES.includes(size)) {\n    throw new Error(`Unsupported size: ${size}. Use one of: ${SUPPORTED_SIZES.join(', ')}`);\n  }\n\n  const zai = await ZAI.create();\n\n  const response = await zai.images.generations.edit({\n    prompt: editPrompt,\n    images: [{ url: imageSource }],\n    size: size\n  });\n\n  const imageBase64 = response.data[0].base64;\n  const buffer = Buffer.from(imageBase64, 'base64');\n  fs.writeFileSync(outputPath, buffer);\n\n  return {\n    path: outputPath,\n    size: size,\n    fileSize: buffer.length\n  };\n}\n\n\u002F\u002F Usage - Edit with different aspect ratios\nawait editImageWithSize(\n  '.\u002Flogo.png',\n  'Redesign the logo to be more modern and minimalist',\n  '1024x1024',\n  '.\u002Flogo_redesigned.png'\n);\n\nawait editImageWithSize(\n  'https:\u002F\u002Fexample.com\u002Fportrait.jpg',\n  'Transform the portrait to landscape orientation, sunset lighting',\n  '1344x768',\n  '.\u002Fportrait_landscape.png'\n);\n```\n\n## CLI Tool Usage\n\nThe z-ai CLI tool provides a convenient way to edit images directly from the command line.\n\n### Basic CLI Usage\n\n```bash\n# Edit image with full options\nz-ai image-edit --prompt \"Change the background to sunset colors\" --image \".\u002Fphoto.png\" --output \".\u002Fedited.png\"\n\n# Short form\nz-ai image-edit -p \"Make it darker and moodier\" -i \".\u002Foriginal.jpg\" -o \".\u002Fmoody.png\"\n\n# Specify output size\nz-ai image-edit -p \"Redesign in modern style\" -i \".\u002Fdesign.png\" -o \".\u002Fmodern.png\" -s 1344x768\n\n# Using remote image URL\nz-ai image-edit -p \"Convert to landscape orientation\" -i \"https:\u002F\u002Fexample.com\u002Fphoto.png\" -o \".\u002Flandscape.png\" -s 1344x768\n```\n\n### CLI Parameters\n\n- `--prompt, -p`: **Required** - Description of the edit to apply\n- `--image, -i`: **Required** - Original image URL or local file path\n- `--output, -o`: **Required** - Output image file path (PNG format)\n- `--size, -s`: Optional - Image size, default is 1024x1024\n- `--help, -h`: Optional - Display help information\n\n### Supported Sizes\n\n- `1024x1024`, `768x1344`, `864x1152`, `1344x768`, `1152x864`, `1440x720`, `720x1440`\n\n### CLI Use Cases for Image Editing\n\n```bash\n# Redesign existing asset\nz-ai image-edit -p \"Redesign the logo with gradients and modern styling\" -i \".\u002Flogo.png\" -o \".\u002Flogo_v2.png\" -s 1024x1024\n\n# Change color scheme\nz-ai image-edit -p \"Change color scheme to blue and white, professional style\" -i \".\u002Foriginal.png\" -o \".\u002Frecolored.png\" -s 1440x720\n\n# Style transformation\nz-ai image-edit -p \"Transform to oil painting style, vibrant colors\" -i \".\u002Fphoto.jpg\" -o \".\u002Foil_painting.png\" -s 1152x864\n\n# Background replacement\nz-ai image-edit -p \"Replace background with modern office setting\" -i \".\u002Fportrait.png\" -o \".\u002Fnew_background.png\" -s 1344x768\n\n# Lighting adjustment\nz-ai image-edit -p \"Adjust to golden hour lighting, warm tones\" -i \".\u002Flandscape.jpg\" -o \".\u002Fgolden_hour.png\" -s 1024x1024\n\n# Element modification\nz-ai image-edit -p \"Replace the red car with a blue motorcycle\" -i \".\u002Fscene.png\" -o \".\u002Fmodified.png\" -s 1344x768\n\n# Mood transformation\nz-ai image-edit -p \"Transform to dark moody atmosphere with dramatic lighting\" -i \".\u002Fbright.jpg\" -o \".\u002Fmoody.png\" -s 1440x720\n\n# Using remote image URL\nz-ai image-edit -p \"Add a hat to the person\" -i \"https:\u002F\u002Fexample.com\u002Fphoto.png\" -o \".\u002Fresult.png\" -s 1024x1024\n```\n\n## Advanced Use Cases\n\n### Batch Image Editing\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\nimport path from 'path';\n\nasync function batchEditImages(editInstructions, outputDir, size = '1024x1024') {\n  const zai = await ZAI.create();\n\n  \u002F\u002F Ensure output directory exists\n  if (!fs.existsSync(outputDir)) {\n    fs.mkdirSync(outputDir, { recursive: true });\n  }\n\n  const results = [];\n\n  for (let i = 0; i \u003C editInstructions.length; i++) {\n    try {\n      const instruction = editInstructions[i];\n      const filename = `edited_${i + 1}.png`;\n      const outputPath = path.join(outputDir, filename);\n\n      const response = await zai.images.generations.edit({\n        prompt: instruction.prompt,\n        images: [{ url: instruction.imageSource }],\n        size: size\n      });\n\n      const imageBase64 = response.data[0].base64;\n      const buffer = Buffer.from(imageBase64, 'base64');\n      fs.writeFileSync(outputPath, buffer);\n\n      results.push({\n        success: true,\n        instruction: instruction.prompt,\n        path: outputPath,\n        size: buffer.length\n      });\n\n      console.log(`✓ Edited: ${filename}`);\n    } catch (error) {\n      results.push({\n        success: false,\n        instruction: editInstructions[i].prompt,\n        error: error.message\n      });\n\n      console.error(`✗ Failed: ${editInstructions[i].prompt} - ${error.message}`);\n    }\n  }\n\n  return results;\n}\n\n\u002F\u002F Usage - Create multiple variations from the same image\nconst editInstructions = [\n  { \n    imageSource: '.\u002Foriginal.jpg',\n    prompt: 'Change background to blue gradient' \n  },\n  { \n    imageSource: '.\u002Foriginal.jpg',\n    prompt: 'Transform to black and white, high contrast' \n  },\n  { \n    imageSource: '.\u002Foriginal.jpg',\n    prompt: 'Add sunset lighting effects' \n  }\n];\n\nconst results = await batchEditImages(editInstructions, '.\u002Fedited-images');\nconsole.log(`Edited ${results.filter(r => r.success).length} images`);\n```\n\n### Image Editing Service\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\nimport path from 'path';\nimport crypto from 'crypto';\n\nclass ImageEditingService {\n  constructor(outputDir = '.\u002Fedited-images') {\n    this.outputDir = outputDir;\n    this.zai = null;\n    this.editHistory = [];\n  }\n\n  async initialize() {\n    this.zai = await ZAI.create();\n    \n    if (!fs.existsSync(this.outputDir)) {\n      fs.mkdirSync(this.outputDir, { recursive: true });\n    }\n  }\n\n  generateFilename(editPrompt) {\n    const hash = crypto\n      .createHash('md5')\n      .update(`${editPrompt}-${Date.now()}`)\n      .digest('hex')\n      .substring(0, 8);\n    \n    return `edited_${hash}.png`;\n  }\n\n  async edit(imageSource, editPrompt, options = {}) {\n    const {\n      size = '1024x1024',\n      saveToHistory = true,\n      filename = null\n    } = options;\n\n    const response = await this.zai.images.generations.edit({\n      prompt: editPrompt,\n      images: [{ url: imageSource }],\n      size: size\n    });\n\n    const imageBase64 = response.data[0].base64;\n    const buffer = Buffer.from(imageBase64, 'base64');\n\n    \u002F\u002F Determine output path\n    const outputFilename = filename || this.generateFilename(editPrompt);\n    const outputPath = path.join(this.outputDir, outputFilename);\n\n    fs.writeFileSync(outputPath, buffer);\n\n    const result = {\n      path: outputPath,\n      imageSource: imageSource,\n      editPrompt: editPrompt,\n      size: size,\n      fileSize: buffer.length,\n      timestamp: new Date().toISOString()\n    };\n\n    \u002F\u002F Save to history\n    if (saveToHistory) {\n      this.editHistory.push(result);\n    }\n\n    return result;\n  }\n\n  async createVariations(imageSource, basePrompt, variations, options = {}) {\n    const results = [];\n    \n    for (const variation of variations) {\n      const fullPrompt = `${basePrompt}, ${variation}`;\n      const result = await this.edit(imageSource, fullPrompt, options);\n      result.variation = variation;\n      results.push(result);\n    }\n\n    return results;\n  }\n\n  getEditHistory() {\n    return this.editHistory;\n  }\n\n  clearHistory() {\n    this.editHistory = [];\n  }\n}\n\n\u002F\u002F Usage\nconst service = new ImageEditingService();\nawait service.initialize();\n\n\u002F\u002F Single edit\nconst edited = await service.edit(\n  '.\u002Foriginal.jpg',\n  'Transform to watercolor painting style',\n  { size: '1024x1024' }\n);\n\n\u002F\u002F Multiple variations from the same image\nconst variations = await service.createVariations(\n  'https:\u002F\u002Fexample.com\u002Fproduct.png',\n  'Professional product photo',\n  [\n    'with blue background',\n    'with wooden surface',\n    'with dramatic lighting'\n  ]\n);\n\nconsole.log('Edit history:', service.getEditHistory());\n```\n\n### Style Transfer and Transformation\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\nasync function applyStyleTransfer(imageSource, content, style, outputPath, size = '1024x1024') {\n  const zai = await ZAI.create();\n\n  const prompt = `${content} transformed into ${style} style, maintain composition and subject`;\n\n  const response = await zai.images.generations.edit({\n    prompt: prompt,\n    images: [{ url: imageSource }],\n    size: size\n  });\n\n  const imageBase64 = response.data[0].base64;\n  const buffer = Buffer.from(imageBase64, 'base64');\n  fs.writeFileSync(outputPath, buffer);\n\n  return {\n    path: outputPath,\n    content: content,\n    style: style\n  };\n}\n\n\u002F\u002F Usage - Apply different styles to the same image\nawait applyStyleTransfer(\n  '.\u002Fportrait.jpg',\n  'Portrait photograph',\n  'oil painting',\n  '.\u002Fportrait_oil.png'\n);\n\nawait applyStyleTransfer(\n  'https:\u002F\u002Fexample.com\u002Fcity.jpg',\n  'City landscape',\n  'watercolor',\n  '.\u002Fcity_watercolor.png'\n);\n\nawait applyStyleTransfer(\n  '.\u002Fproduct.png',\n  'Product photo',\n  'minimalist illustration',\n  '.\u002Fproduct_minimal.png'\n);\n```\n\n### Element Replacement\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\nasync function replaceElement(imageSource, baseScene, replaceWhat, replaceWith, outputPath, size = '1024x1024') {\n  const zai = await ZAI.create();\n\n  const prompt = `${baseScene}, replace ${replaceWhat} with ${replaceWith}, keep everything else identical`;\n\n  const response = await zai.images.generations.edit({\n    prompt: prompt,\n    images: [{ url: imageSource }],\n    size: size\n  });\n\n  const imageBase64 = response.data[0].base64;\n  const buffer = Buffer.from(imageBase64, 'base64');\n  fs.writeFileSync(outputPath, buffer);\n\n  return {\n    path: outputPath,\n    modification: `${replaceWhat} → ${replaceWith}`\n  };\n}\n\n\u002F\u002F Usage\nawait replaceElement(\n  '.\u002Fworkspace.jpg',\n  'Office workspace with laptop',\n  'laptop',\n  'desktop computer with dual monitors',\n  '.\u002Fworkspace_desktop.png'\n);\n\nawait replaceElement(\n  'https:\u002F\u002Fexample.com\u002Fliving-room.jpg',\n  'Living room interior with sofa',\n  'blue sofa',\n  'brown leather sofa',\n  '.\u002Fliving_room_leather.png'\n);\n```\n\n## Best Practices\n\n### 1. Effective Edit Prompts\n\n```javascript\nfunction buildEditPrompt(baseDescription, modification, preserveElements = []) {\n  const components = [\n    baseDescription,\n    modification\n  ];\n\n  if (preserveElements.length > 0) {\n    components.push(`keep ${preserveElements.join(', ')} unchanged`);\n  }\n\n  components.push('maintain overall composition');\n\n  return components.filter(Boolean).join(', ');\n}\n\n\u002F\u002F Usage\nconst editPrompt = buildEditPrompt(\n  'Professional headshot photo',\n  'change background to modern office',\n  ['lighting', 'pose', 'expression']\n);\n\n\u002F\u002F Result: \"Professional headshot photo, change background to modern office, keep lighting, pose, expression unchanged, maintain overall composition\"\n```\n\n### 2. Size Selection for Different Edit Types\n\n```javascript\nfunction selectSizeForEdit(editType) {\n  const sizeMap = {\n    'background-change': '1440x720',\n    'style-transfer': '1024x1024',\n    'color-adjustment': '1024x1024',\n    'element-replacement': '1344x768',\n    'composition-change': '1152x864',\n    'portrait-edit': '768x1344',\n    'landscape-edit': '1344x768'\n  };\n\n  return sizeMap[editType] || '1024x1024';\n}\n\n\u002F\u002F Usage\nconst size = selectSizeForEdit('background-change');\nawait editImage('Replace background with beach scene', '.\u002Fbeach_bg.png', size);\n```\n\n### 3. Error Handling with Retry\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\nasync function safeEditImage(imageSource, editPrompt, size, outputPath, retries = 3) {\n  let lastError;\n\n  for (let attempt = 1; attempt \u003C= retries; attempt++) {\n    try {\n      const zai = await ZAI.create();\n\n      const response = await zai.images.generations.edit({\n        prompt: editPrompt,\n        images: [{ url: imageSource }],\n        size: size\n      });\n\n      if (!response.data || !response.data[0] || !response.data[0].base64) {\n        throw new Error('Invalid response from image editing API');\n      }\n\n      const imageBase64 = response.data[0].base64;\n      const buffer = Buffer.from(imageBase64, 'base64');\n      fs.writeFileSync(outputPath, buffer);\n\n      return {\n        success: true,\n        path: outputPath,\n        attempts: attempt\n      };\n    } catch (error) {\n      lastError = error;\n      console.error(`Attempt ${attempt} failed:`, error.message);\n\n      if (attempt \u003C retries) {\n        \u002F\u002F Wait before retry (exponential backoff)\n        await new Promise(resolve => setTimeout(resolve, 1000 * attempt));\n      }\n    }\n  }\n\n  return {\n    success: false,\n    error: lastError.message,\n    attempts: retries\n  };\n}\n```\n\n## Common Image Editing Use Cases\n\n1. **Background Replacement**: Change or remove backgrounds in photos\n2. **Style Transformation**: Convert photos to paintings, illustrations, etc.\n3. **Color Adjustment**: Change color schemes, saturation, mood\n4. **Element Modification**: Replace or modify specific elements\n5. **Composition Changes**: Adjust framing, orientation, layout\n6. **Lighting Adjustments**: Modify lighting, shadows, highlights\n7. **Asset Redesign**: Modernize or rebrand existing designs\n8. **Quality Enhancement**: Improve overall visual quality\n9. **Variation Creation**: Generate multiple versions of an image\n10. **Format Conversion**: Transform between different styles or formats\n\n## Integration Examples\n\n### Express.js API Endpoint\n\n```javascript\nimport express from 'express';\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\nimport path from 'path';\n\nconst app = express();\napp.use(express.json());\napp.use('\u002Fedited-images', express.static('edited-images'));\n\nlet zaiInstance;\nconst outputDir = '.\u002Fedited-images';\n\nasync function initZAI() {\n  zaiInstance = await ZAI.create();\n  if (!fs.existsSync(outputDir)) {\n    fs.mkdirSync(outputDir, { recursive: true });\n  }\n}\n\napp.post('\u002Fapi\u002Fedit-image', async (req, res) => {\n  try {\n    const { \n      imageSource,           \u002F\u002F URL or base64 data URL\n      editPrompt, \n      size = '1024x1024', \n      baseDescription = '' \n    } = req.body;\n\n    if (!imageSource || !editPrompt) {\n      return res.status(400).json({ \n        error: 'imageSource and editPrompt are required' \n      });\n    }\n\n    \u002F\u002F Combine base description with edit instruction\n    const fullPrompt = baseDescription \n      ? `${baseDescription}, ${editPrompt}`\n      : editPrompt;\n\n    const response = await zaiInstance.images.generations.edit({\n      prompt: fullPrompt,\n      images: [{ url: imageSource }],\n      size: size\n    });\n\n    const imageBase64 = response.data[0].base64;\n    const buffer = Buffer.from(imageBase64, 'base64');\n    \n    const filename = `edited_${Date.now()}.png`;\n    const filepath = path.join(outputDir, filename);\n    fs.writeFileSync(filepath, buffer);\n\n    res.json({\n      success: true,\n      imageUrl: `\u002Fedited-images\u002F${filename}`,\n      editPrompt: fullPrompt,\n      size: size\n    });\n  } catch (error) {\n    res.status(500).json({\n      success: false,\n      error: error.message\n    });\n  }\n});\n\napp.post('\u002Fapi\u002Fcreate-variations', async (req, res) => {\n  try {\n    const { \n      imageSource,      \u002F\u002F URL or base64 data URL\n      baseDescription, \n      variations, \n      size = '1024x1024' \n    } = req.body;\n\n    if (!imageSource || !baseDescription || !variations || !Array.isArray(variations)) {\n      return res.status(400).json({ \n        error: 'imageSource, baseDescription and variations array are required' \n      });\n    }\n\n    const results = [];\n\n    for (const variation of variations) {\n      const fullPrompt = `${baseDescription}, ${variation}`;\n\n      const response = await zaiInstance.images.generations.edit({\n        prompt: fullPrompt,\n        images: [{ url: imageSource }],\n        size: size\n      });\n\n      const imageBase64 = response.data[0].base64;\n      const buffer = Buffer.from(imageBase64, 'base64');\n      \n      const filename = `variation_${Date.now()}_${Math.random().toString(36).substr(2, 9)}.png`;\n      const filepath = path.join(outputDir, filename);\n      fs.writeFileSync(filepath, buffer);\n\n      results.push({\n        variation: variation,\n        imageUrl: `\u002Fedited-images\u002F${filename}`\n      });\n    }\n\n    res.json({\n      success: true,\n      results: results\n    });\n  } catch (error) {\n    res.status(500).json({\n      success: false,\n      error: error.message\n    });\n  }\n});\n\ninitZAI().then(() => {\n  app.listen(3000, () => {\n    console.log('Image editing API running on port 3000');\n  });\n});\n```\n\n## CLI Integration in Scripts\n\n### Shell Script for Batch Editing\n\n```bash\n#!\u002Fbin\u002Fbash\n\n# Batch edit images with different styles\necho \"Creating style variations...\"\n\nORIGINAL_IMAGE=\".\u002Fproduct.jpg\"\nBASE=\"Professional product photo of laptop\"\n\nz-ai image-edit -p \"$BASE, modern minimalist style, white background\" -i \"$ORIGINAL_IMAGE\" -o \".\u002Fvariations\u002Fminimal.png\" -s 1024x1024\nz-ai image-edit -p \"$BASE, dramatic lighting, dark background\" -i \"$ORIGINAL_IMAGE\" -o \".\u002Fvariations\u002Fdramatic.png\" -s 1024x1024\nz-ai image-edit -p \"$BASE, on wooden desk, natural lighting\" -i \"$ORIGINAL_IMAGE\" -o \".\u002Fvariations\u002Fnatural.png\" -s 1024x1024\n\necho \"Variations created successfully!\"\n```\n\n## Troubleshooting\n\n**Issue**: \"SDK must be used in backend\"\n- **Solution**: Ensure z-ai-web-dev-sdk is only used in server-side code\n\n**Issue**: Invalid size parameter\n- **Solution**: Use only supported sizes: 1024x1024, 768x1344, 864x1152, 1344x768, 1152x864, 1440x720, 720x1440\n\n**Issue**: Edited image doesn't match intention\n- **Solution**: Be more specific in edit prompts. Include what to change AND what to preserve\n\n**Issue**: CLI command not found\n- **Solution**: Ensure z-ai CLI is properly installed and in PATH\n\n**Issue**: Image quality loss after editing\n- **Solution**: Use larger size options and include quality terms in prompts\n\n**Issue**: Inconsistent results across variations\n- **Solution**: Include more specific base description and detailed modification instructions\n\n## Edit Prompt Engineering Tips\n\n### Good Edit Prompts\n- ✓ \"Change background to modern office, keep subject and lighting identical\"\n- ✓ \"Transform to watercolor style, maintain composition and colors\"\n- ✓ \"Replace red car with blue motorcycle, keep road and scenery unchanged\"\n- ✓ \"Adjust to golden hour lighting, preserve all elements\"\n\n### Poor Edit Prompts\n- ✗ \"make it better\"\n- ✗ \"change something\"\n- ✗ \"different version\"\n\n### Edit Prompt Components\n1. **Base Context**: What the image currently represents\n2. **Modification**: What specific changes to make\n3. **Preservation**: What elements to keep unchanged\n4. **Quality**: Desired output quality or style\n\n### Effective Edit Patterns\n\n**Background Changes:**\n```\n\"[Subject description], replace background with [new background], maintain subject lighting and pose\"\n```\n\n**Style Transfers:**\n```\n\"[Current description] transformed into [style name] style, preserve composition and key elements\"\n```\n\n**Element Replacement:**\n```\n\"[Scene description], replace [element A] with [element B], keep everything else identical\"\n```\n\n**Color Adjustments:**\n```\n\"[Image description], change color scheme to [colors], maintain contrast and composition\"\n```\n\n## Supported Image Sizes\n\n- `1024x1024` - Square (Best for general editing)\n- `768x1344` - Portrait\n- `864x1152` - Portrait\n- `1344x768` - Landscape\n- `1152x864` - Landscape\n- `1440x720` - Wide landscape\n- `720x1440` - Tall portrait\n\n## Remember\n\n- Always use z-ai-web-dev-sdk in backend code only\n- The SDK is already installed - import as shown\n- CLI tool is available for quick image editing\n- Be specific about what to change AND what to preserve\n- Include base description for better context\n- Use appropriate size for the edit type\n- Implement retry logic for production applications\n- Test edit prompts iteratively for best results\n- Consider creating variations to explore options\n- Base64 images need to be decoded before saving\n","# Image Edit Skill\n\nThis skill guides the implementation of image editing and modification functionality using the z-ai-web-dev-sdk package and CLI tool, enabling intelligent transformation and editing of images based on text descriptions.\n\n## Skills Path\n\n**Skill Location**: `{project_path}\u002Fskills\u002Fimage-edit`\n\nthis skill is located at above path in your project.\n\n**Reference Scripts**: Example test scripts are available in the `{Skill Location}\u002Fscripts\u002F` directory for quick testing and reference. See `{Skill Location}\u002Fscripts\u002Fimage-edit.ts` for a working example.\n\n## Overview\n\nImage Edit allows you to build applications that modify, transform, and enhance existing images using AI models. Perfect for redesigning assets, creating variations, improving visual content, and transforming images based on textual descriptions.\n\n**IMPORTANT**: z-ai-web-dev-sdk MUST be used in backend code only. Never use it in client-side code.\n\n## SDK API Method\n\nThe image editing functionality uses the following API method:\n\n```javascript\nawait zai.images.generations.edit({\n  prompt: string,              \u002F\u002F Required: Description of the edit to apply\n  images: [{ url: string }],  \u002F\u002F Required: Array with image URL or base64 data URL\n  size?: string,              \u002F\u002F Optional: Output size (default: '1024x1024')\n  model?: string              \u002F\u002F Optional: Model name\n})\n```\n\n**Important**: The `images` parameter must be an array of objects with a `url` property, not a plain string.\n\n**API Endpoint**: `POST \u002Fimages\u002Fgenerations\u002Fedit`\n\n**Returns**: `ImageGenerationResponse` with base64 encoded edited image\n\n## Prerequisites\n\nThe z-ai-web-dev-sdk package is already installed. Import it as shown in the examples below.\n\n## Basic Image Editing\n\n### Simple Image Transformation\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\nasync function editImage(imageSource, editPrompt, outputPath, size = '1024x1024') {\n  const zai = await ZAI.create();\n\n  const response = await zai.images.generations.edit({\n    prompt: editPrompt,\n    images: [{ url: imageSource }],  \u002F\u002F Array of objects with url property\n    size: size\n  });\n\n  const imageBase64 = response.data[0].base64;\n  \n  \u002F\u002F Save edited image\n  const buffer = Buffer.from(imageBase64, 'base64');\n  fs.writeFileSync(outputPath, buffer);\n  \n  console.log(`Edited image saved to ${outputPath}`);\n  return outputPath;\n}\n\n\u002F\u002F Usage - Using remote image URL\nawait editImage(\n  'https:\u002F\u002Fexample.com\u002Flandscape.jpg',\n  'Transform this landscape into a night scene with stars and moon',\n  '.\u002Flandscape_night.png'\n);\n\n\u002F\u002F Usage - Using local image converted to base64\nimport { readFileSync } from 'fs';\nconst imageBuffer = readFileSync('.\u002Fphoto.jpg');\nconst base64Image = imageBuffer.toString('base64');\nconst dataUrl = `data:image\u002Fjpeg;base64,${base64Image}`;\n\nawait editImage(\n  dataUrl,\n  'Change the cat to a dog, keep everything else the same',\n  '.\u002Fdog_version.png'\n);\n```\n\n### Create Image Variations\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\nasync function createVariation(imageSource, baseDescription, variation, outputPath, size = '1024x1024') {\n  const zai = await ZAI.create();\n\n  \u002F\u002F Combine base description with variation request\n  const prompt = `${baseDescription}, ${variation}`;\n\n  const response = await zai.images.generations.edit({\n    prompt: prompt,\n    images: [{ url: imageSource }],\n    size: size\n  });\n\n  const imageBase64 = response.data[0].base64;\n  const buffer = Buffer.from(imageBase64, 'base64');\n  fs.writeFileSync(outputPath, buffer);\n\n  return {\n    path: outputPath,\n    prompt: prompt,\n    variation: variation\n  };\n}\n\n\u002F\u002F Usage - Create variations from original image\nawait createVariation(\n  'https:\u002F\u002Fexample.com\u002Fheadshot.jpg',\n  'Professional headshot photo',\n  'with blue background instead of gray',\n  '.\u002Fheadshot_blue.png'\n);\n\nawait createVariation(\n  '.\u002Fsmartphone.png',\n  'Product photo of smartphone',\n  'on wooden table instead of white background',\n  '.\u002Fproduct_wood.png'\n);\n```\n\n### Multiple Image Sizes for Editing\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\n\u002F\u002F Supported sizes\nconst SUPPORTED_SIZES = [\n  '1024x1024',  \u002F\u002F Square\n  '768x1344',   \u002F\u002F Portrait\n  '864x1152',   \u002F\u002F Portrait\n  '1344x768',   \u002F\u002F Landscape\n  '1152x864',   \u002F\u002F Landscape\n  '1440x720',   \u002F\u002F Wide landscape\n  '720x1440'    \u002F\u002F Tall portrait\n];\n\nasync function editImageWithSize(imageSource, editPrompt, size, outputPath) {\n  if (!SUPPORTED_SIZES.includes(size)) {\n    throw new Error(`Unsupported size: ${size}. Use one of: ${SUPPORTED_SIZES.join(', ')}`);\n  }\n\n  const zai = await ZAI.create();\n\n  const response = await zai.images.generations.edit({\n    prompt: editPrompt,\n    images: [{ url: imageSource }],\n    size: size\n  });\n\n  const imageBase64 = response.data[0].base64;\n  const buffer = Buffer.from(imageBase64, 'base64');\n  fs.writeFileSync(outputPath, buffer);\n\n  return {\n    path: outputPath,\n    size: size,\n    fileSize: buffer.length\n  };\n}\n\n\u002F\u002F Usage - Edit with different aspect ratios\nawait editImageWithSize(\n  '.\u002Flogo.png',\n  'Redesign the logo to be more modern and minimalist',\n  '1024x1024',\n  '.\u002Flogo_redesigned.png'\n);\n\nawait editImageWithSize(\n  'https:\u002F\u002Fexample.com\u002Fportrait.jpg',\n  'Transform the portrait to landscape orientation, sunset lighting',\n  '1344x768',\n  '.\u002Fportrait_landscape.png'\n);\n```\n\n## CLI Tool Usage\n\nThe z-ai CLI tool provides a convenient way to edit images directly from the command line.\n\n### Basic CLI Usage\n\n```bash\n# Edit image with full options\nz-ai image-edit --prompt \"Change the background to sunset colors\" --image \".\u002Fphoto.png\" --output \".\u002Fedited.png\"\n\n# Short form\nz-ai image-edit -p \"Make it darker and moodier\" -i \".\u002Foriginal.jpg\" -o \".\u002Fmoody.png\"\n\n# Specify output size\nz-ai image-edit -p \"Redesign in modern style\" -i \".\u002Fdesign.png\" -o \".\u002Fmodern.png\" -s 1344x768\n\n# Using remote image URL\nz-ai image-edit -p \"Convert to landscape orientation\" -i \"https:\u002F\u002Fexample.com\u002Fphoto.png\" -o \".\u002Flandscape.png\" -s 1344x768\n```\n\n### CLI Parameters\n\n- `--prompt, -p`: **Required** - Description of the edit to apply\n- `--image, -i`: **Required** - Original image URL or local file path\n- `--output, -o`: **Required** - Output image file path (PNG format)\n- `--size, -s`: Optional - Image size, default is 1024x1024\n- `--help, -h`: Optional - Display help information\n\n### Supported Sizes\n\n- `1024x1024`, `768x1344`, `864x1152`, `1344x768`, `1152x864`, `1440x720`, `720x1440`\n\n### CLI Use Cases for Image Editing\n\n```bash\n# Redesign existing asset\nz-ai image-edit -p \"Redesign the logo with gradients and modern styling\" -i \".\u002Flogo.png\" -o \".\u002Flogo_v2.png\" -s 1024x1024\n\n# Change color scheme\nz-ai image-edit -p \"Change color scheme to blue and white, professional style\" -i \".\u002Foriginal.png\" -o \".\u002Frecolored.png\" -s 1440x720\n\n# Style transformation\nz-ai image-edit -p \"Transform to oil painting style, vibrant colors\" -i \".\u002Fphoto.jpg\" -o \".\u002Foil_painting.png\" -s 1152x864\n\n# Background replacement\nz-ai image-edit -p \"Replace background with modern office setting\" -i \".\u002Fportrait.png\" -o \".\u002Fnew_background.png\" -s 1344x768\n\n# Lighting adjustment\nz-ai image-edit -p \"Adjust to golden hour lighting, warm tones\" -i \".\u002Flandscape.jpg\" -o \".\u002Fgolden_hour.png\" -s 1024x1024\n\n# Element modification\nz-ai image-edit -p \"Replace the red car with a blue motorcycle\" -i \".\u002Fscene.png\" -o \".\u002Fmodified.png\" -s 1344x768\n\n# Mood transformation\nz-ai image-edit -p \"Transform to dark moody atmosphere with dramatic lighting\" -i \".\u002Fbright.jpg\" -o \".\u002Fmoody.png\" -s 1440x720\n\n# Using remote image URL\nz-ai image-edit -p \"Add a hat to the person\" -i \"https:\u002F\u002Fexample.com\u002Fphoto.png\" -o \".\u002Fresult.png\" -s 1024x1024\n```\n\n## Advanced Use Cases\n\n### Batch Image Editing\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\nimport path from 'path';\n\nasync function batchEditImages(editInstructions, outputDir, size = '1024x1024') {\n  const zai = await ZAI.create();\n\n  \u002F\u002F Ensure output directory exists\n  if (!fs.existsSync(outputDir)) {\n    fs.mkdirSync(outputDir, { recursive: true });\n  }\n\n  const results = [];\n\n  for (let i = 0; i \u003C editInstructions.length; i++) {\n    try {\n      const instruction = editInstructions[i];\n      const filename = `edited_${i + 1}.png`;\n      const outputPath = path.join(outputDir, filename);\n\n      const response = await zai.images.generations.edit({\n        prompt: instruction.prompt,\n        images: [{ url: instruction.imageSource }],\n        size: size\n      });\n\n      const imageBase64 = response.data[0].base64;\n      const buffer = Buffer.from(imageBase64, 'base64');\n      fs.writeFileSync(outputPath, buffer);\n\n      results.push({\n        success: true,\n        instruction: instruction.prompt,\n        path: outputPath,\n        size: buffer.length\n      });\n\n      console.log(`✓ Edited: ${filename}`);\n    } catch (error) {\n      results.push({\n        success: false,\n        instruction: editInstructions[i].prompt,\n        error: error.message\n      });\n\n      console.error(`✗ Failed: ${editInstructions[i].prompt} - ${error.message}`);\n    }\n  }\n\n  return results;\n}\n\n\u002F\u002F Usage - Create multiple variations from the same image\nconst editInstructions = [\n  { \n    imageSource: '.\u002Foriginal.jpg',\n    prompt: 'Change background to blue gradient' \n  },\n  { \n    imageSource: '.\u002Foriginal.jpg',\n    prompt: 'Transform to black and white, high contrast' \n  },\n  { \n    imageSource: '.\u002Foriginal.jpg',\n    prompt: 'Add sunset lighting effects' \n  }\n];\n\nconst results = await batchEditImages(editInstructions, '.\u002Fedited-images');\nconsole.log(`Edited ${results.filter(r => r.success).length} images`);\n```\n\n### Image Editing Service\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\nimport path from 'path';\nimport crypto from 'crypto';\n\nclass ImageEditingService {\n  constructor(outputDir = '.\u002Fedited-images') {\n    this.outputDir = outputDir;\n    this.zai = null;\n    this.editHistory = [];\n  }\n\n  async initialize() {\n    this.zai = await ZAI.create();\n    \n    if (!fs.existsSync(this.outputDir)) {\n      fs.mkdirSync(this.outputDir, { recursive: true });\n    }\n  }\n\n  generateFilename(editPrompt) {\n    const hash = crypto\n      .createHash('md5')\n      .update(`${editPrompt}-${Date.now()}`)\n      .digest('hex')\n      .substring(0, 8);\n    \n    return `edited_${hash}.png`;\n  }\n\n  async edit(imageSource, editPrompt, options = {}) {\n    const {\n      size = '1024x1024',\n      saveToHistory = true,\n      filename = null\n    } = options;\n\n    const response = await this.zai.images.generations.edit({\n      prompt: editPrompt,\n      images: [{ url: imageSource }],\n      size: size\n    });\n\n    const imageBase64 = response.data[0].base64;\n    const buffer = Buffer.from(imageBase64, 'base64');\n\n    \u002F\u002F Determine output path\n    const outputFilename = filename || this.generateFilename(editPrompt);\n    const outputPath = path.join(this.outputDir, outputFilename);\n\n    fs.writeFileSync(outputPath, buffer);\n\n    const result = {\n      path: outputPath,\n      imageSource: imageSource,\n      editPrompt: editPrompt,\n      size: size,\n      fileSize: buffer.length,\n      timestamp: new Date().toISOString()\n    };\n\n    \u002F\u002F Save to history\n    if (saveToHistory) {\n      this.editHistory.push(result);\n    }\n\n    return result;\n  }\n\n  async createVariations(imageSource, basePrompt, variations, options = {}) {\n    const results = [];\n    \n    for (const variation of variations) {\n      const fullPrompt = `${basePrompt}, ${variation}`;\n      const result = await this.edit(imageSource, fullPrompt, options);\n      result.variation = variation;\n      results.push(result);\n    }\n\n    return results;\n  }\n\n  getEditHistory() {\n    return this.editHistory;\n  }\n\n  clearHistory() {\n    this.editHistory = [];\n  }\n}\n\n\u002F\u002F Usage\nconst service = new ImageEditingService();\nawait service.initialize();\n\n\u002F\u002F Single edit\nconst edited = await service.edit(\n  '.\u002Foriginal.jpg',\n  'Transform to watercolor painting style',\n  { size: '1024x1024' }\n);\n\n\u002F\u002F Multiple variations from the same image\nconst variations = await service.createVariations(\n  'https:\u002F\u002Fexample.com\u002Fproduct.png',\n  'Professional product photo',\n  [\n    'with blue background',\n    'with wooden surface',\n    'with dramatic lighting'\n  ]\n);\n\nconsole.log('Edit history:', service.getEditHistory());\n```\n\n### Style Transfer and Transformation\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\nasync function applyStyleTransfer(imageSource, content, style, outputPath, size = '1024x1024') {\n  const zai = await ZAI.create();\n\n  const prompt = `${content} transformed into ${style} style, maintain composition and subject`;\n\n  const response = await zai.images.generations.edit({\n    prompt: prompt,\n    images: [{ url: imageSource }],\n    size: size\n  });\n\n  const imageBase64 = response.data[0].base64;\n  const buffer = Buffer.from(imageBase64, 'base64');\n  fs.writeFileSync(outputPath, buffer);\n\n  return {\n    path: outputPath,\n    content: content,\n    style: style\n  };\n}\n\n\u002F\u002F Usage - Apply different styles to the same image\nawait applyStyleTransfer(\n  '.\u002Fportrait.jpg',\n  'Portrait photograph',\n  'oil painting',\n  '.\u002Fportrait_oil.png'\n);\n\nawait applyStyleTransfer(\n  'https:\u002F\u002Fexample.com\u002Fcity.jpg',\n  'City landscape',\n  'watercolor',\n  '.\u002Fcity_watercolor.png'\n);\n\nawait applyStyleTransfer(\n  '.\u002Fproduct.png',\n  'Product photo',\n  'minimalist illustration',\n  '.\u002Fproduct_minimal.png'\n);\n```\n\n### Element Replacement\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\nasync function replaceElement(imageSource, baseScene, replaceWhat, replaceWith, outputPath, size = '1024x1024') {\n  const zai = await ZAI.create();\n\n  const prompt = `${baseScene}, replace ${replaceWhat} with ${replaceWith}, keep everything else identical`;\n\n  const response = await zai.images.generations.edit({\n    prompt: prompt,\n    images: [{ url: imageSource }],\n    size: size\n  });\n\n  const imageBase64 = response.data[0].base64;\n  const buffer = Buffer.from(imageBase64, 'base64');\n  fs.writeFileSync(outputPath, buffer);\n\n  return {\n    path: outputPath,\n    modification: `${replaceWhat} → ${replaceWith}`\n  };\n}\n\n\u002F\u002F Usage\nawait replaceElement(\n  '.\u002Fworkspace.jpg',\n  'Office workspace with laptop',\n  'laptop',\n  'desktop computer with dual monitors',\n  '.\u002Fworkspace_desktop.png'\n);\n\nawait replaceElement(\n  'https:\u002F\u002Fexample.com\u002Fliving-room.jpg',\n  'Living room interior with sofa',\n  'blue sofa',\n  'brown leather sofa',\n  '.\u002Fliving_room_leather.png'\n);\n```\n\n## Best Practices\n\n### 1. Effective Edit Prompts\n\n```javascript\nfunction buildEditPrompt(baseDescription, modification, preserveElements = []) {\n  const components = [\n    baseDescription,\n    modification\n  ];\n\n  if (preserveElements.length > 0) {\n    components.push(`keep ${preserveElements.join(', ')} unchanged`);\n  }\n\n  components.push('maintain overall composition');\n\n  return components.filter(Boolean).join(', ');\n}\n\n\u002F\u002F Usage\nconst editPrompt = buildEditPrompt(\n  'Professional headshot photo',\n  'change background to modern office',\n  ['lighting', 'pose', 'expression']\n);\n\n\u002F\u002F Result: \"Professional headshot photo, change background to modern office, keep lighting, pose, expression unchanged, maintain overall composition\"\n```\n\n### 2. Size Selection for Different Edit Types\n\n```javascript\nfunction selectSizeForEdit(editType) {\n  const sizeMap = {\n    'background-change': '1440x720',\n    'style-transfer': '1024x1024',\n    'color-adjustment': '1024x1024',\n    'element-replacement': '1344x768',\n    'composition-change': '1152x864',\n    'portrait-edit': '768x1344',\n    'landscape-edit': '1344x768'\n  };\n\n  return sizeMap[editType] || '1024x1024';\n}\n\n\u002F\u002F Usage\nconst size = selectSizeForEdit('background-change');\nawait editImage('Replace background with beach scene', '.\u002Fbeach_bg.png', size);\n```\n\n### 3. Error Handling with Retry\n\n```javascript\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\n\nasync function safeEditImage(imageSource, editPrompt, size, outputPath, retries = 3) {\n  let lastError;\n\n  for (let attempt = 1; attempt \u003C= retries; attempt++) {\n    try {\n      const zai = await ZAI.create();\n\n      const response = await zai.images.generations.edit({\n        prompt: editPrompt,\n        images: [{ url: imageSource }],\n        size: size\n      });\n\n      if (!response.data || !response.data[0] || !response.data[0].base64) {\n        throw new Error('Invalid response from image editing API');\n      }\n\n      const imageBase64 = response.data[0].base64;\n      const buffer = Buffer.from(imageBase64, 'base64');\n      fs.writeFileSync(outputPath, buffer);\n\n      return {\n        success: true,\n        path: outputPath,\n        attempts: attempt\n      };\n    } catch (error) {\n      lastError = error;\n      console.error(`Attempt ${attempt} failed:`, error.message);\n\n      if (attempt \u003C retries) {\n        \u002F\u002F Wait before retry (exponential backoff)\n        await new Promise(resolve => setTimeout(resolve, 1000 * attempt));\n      }\n    }\n  }\n\n  return {\n    success: false,\n    error: lastError.message,\n    attempts: retries\n  };\n}\n```\n\n## Common Image Editing Use Cases\n\n1. **Background Replacement**: Change or remove backgrounds in photos\n2. **Style Transformation**: Convert photos to paintings, illustrations, etc.\n3. **Color Adjustment**: Change color schemes, saturation, mood\n4. **Element Modification**: Replace or modify specific elements\n5. **Composition Changes**: Adjust framing, orientation, layout\n6. **Lighting Adjustments**: Modify lighting, shadows, highlights\n7. **Asset Redesign**: Modernize or rebrand existing designs\n8. **Quality Enhancement**: Improve overall visual quality\n9. **Variation Creation**: Generate multiple versions of an image\n10. **Format Conversion**: Transform between different styles or formats\n\n## Integration Examples\n\n### Express.js API Endpoint\n\n```javascript\nimport express from 'express';\nimport ZAI from 'z-ai-web-dev-sdk';\nimport fs from 'fs';\nimport path from 'path';\n\nconst app = express();\napp.use(express.json());\napp.use('\u002Fedited-images', express.static('edited-images'));\n\nlet zaiInstance;\nconst outputDir = '.\u002Fedited-images';\n\nasync function initZAI() {\n  zaiInstance = await ZAI.create();\n  if (!fs.existsSync(outputDir)) {\n    fs.mkdirSync(outputDir, { recursive: true });\n  }\n}\n\napp.post('\u002Fapi\u002Fedit-image', async (req, res) => {\n  try {\n    const { \n      imageSource,           \u002F\u002F URL or base64 data URL\n      editPrompt, \n      size = '1024x1024', \n      baseDescription = '' \n    } = req.body;\n\n    if (!imageSource || !editPrompt) {\n      return res.status(400).json({ \n        error: 'imageSource and editPrompt are required' \n      });\n    }\n\n    \u002F\u002F Combine base description with edit instruction\n    const fullPrompt = baseDescription \n      ? `${baseDescription}, ${editPrompt}`\n      : editPrompt;\n\n    const response = await zaiInstance.images.generations.edit({\n      prompt: fullPrompt,\n      images: [{ url: imageSource }],\n      size: size\n    });\n\n    const imageBase64 = response.data[0].base64;\n    const buffer = Buffer.from(imageBase64, 'base64');\n    \n    const filename = `edited_${Date.now()}.png`;\n    const filepath = path.join(outputDir, filename);\n    fs.writeFileSync(filepath, buffer);\n\n    res.json({\n      success: true,\n      imageUrl: `\u002Fedited-images\u002F${filename}`,\n      editPrompt: fullPrompt,\n      size: size\n    });\n  } catch (error) {\n    res.status(500).json({\n      success: false,\n      error: error.message\n    });\n  }\n});\n\napp.post('\u002Fapi\u002Fcreate-variations', async (req, res) => {\n  try {\n    const { \n      imageSource,      \u002F\u002F URL or base64 data URL\n      baseDescription, \n      variations, \n      size = '1024x1024' \n    } = req.body;\n\n    if (!imageSource || !baseDescription || !variations || !Array.isArray(variations)) {\n      return res.status(400).json({ \n        error: 'imageSource, baseDescription and variations array are required' \n      });\n    }\n\n    const results = [];\n\n    for (const variation of variations) {\n      const fullPrompt = `${baseDescription}, ${variation}`;\n\n      const response = await zaiInstance.images.generations.edit({\n        prompt: fullPrompt,\n        images: [{ url: imageSource }],\n        size: size\n      });\n\n      const imageBase64 = response.data[0].base64;\n      const buffer = Buffer.from(imageBase64, 'base64');\n      \n      const filename = `variation_${Date.now()}_${Math.random().toString(36).substr(2, 9)}.png`;\n      const filepath = path.join(outputDir, filename);\n      fs.writeFileSync(filepath, buffer);\n\n      results.push({\n        variation: variation,\n        imageUrl: `\u002Fedited-images\u002F${filename}`\n      });\n    }\n\n    res.json({\n      success: true,\n      results: results\n    });\n  } catch (error) {\n    res.status(500).json({\n      success: false,\n      error: error.message\n    });\n  }\n});\n\ninitZAI().then(() => {\n  app.listen(3000, () => {\n    console.log('Image editing API running on port 3000');\n  });\n});\n```\n\n## CLI Integration in Scripts\n\n### Shell Script for Batch Editing\n\n```bash\n#!\u002Fbin\u002Fbash\n\n# Batch edit images with different styles\necho \"Creating style variations...\"\n\nORIGINAL_IMAGE=\".\u002Fproduct.jpg\"\nBASE=\"Professional product photo of laptop\"\n\nz-ai image-edit -p \"$BASE, modern minimalist style, white background\" -i \"$ORIGINAL_IMAGE\" -o \".\u002Fvariations\u002Fminimal.png\" -s 1024x1024\nz-ai image-edit -p \"$BASE, dramatic lighting, dark background\" -i \"$ORIGINAL_IMAGE\" -o \".\u002Fvariations\u002Fdramatic.png\" -s 1024x1024\nz-ai image-edit -p \"$BASE, on wooden desk, natural lighting\" -i \"$ORIGINAL_IMAGE\" -o \".\u002Fvariations\u002Fnatural.png\" -s 1024x1024\n\necho \"Variations created successfully!\"\n```\n\n## Troubleshooting\n\n**Issue**: \"SDK must be used in backend\"\n- **Solution**: Ensure z-ai-web-dev-sdk is only used in server-side code\n\n**Issue**: Invalid size parameter\n- **Solution**: Use only supported sizes: 1024x1024, 768x1344, 864x1152, 1344x768, 1152x864, 1440x720, 720x1440\n\n**Issue**: Edited image doesn't match intention\n- **Solution**: Be more specific in edit prompts. Include what to change AND what to preserve\n\n**Issue**: CLI command not found\n- **Solution**: Ensure z-ai CLI is properly installed and in PATH\n\n**Issue**: Image quality loss after editing\n- **Solution**: Use larger size options and include quality terms in prompts\n\n**Issue**: Inconsistent results across variations\n- **Solution**: Include more specific base description and detailed modification instructions\n\n## Edit Prompt Engineering Tips\n\n### Good Edit Prompts\n- ✓ \"Change background to modern office, keep subject and lighting identical\"\n- ✓ \"Transform to watercolor style, maintain composition and colors\"\n- ✓ \"Replace red car with blue motorcycle, keep road and scenery unchanged\"\n- ✓ \"Adjust to golden hour lighting, preserve all elements\"\n\n### Poor Edit Prompts\n- ✗ \"make it better\"\n- ✗ \"change something\"\n- ✗ \"different version\"\n\n### Edit Prompt Components\n1. **Base Context**: What the image currently represents\n2. **Modification**: What specific changes to make\n3. **Preservation**: What elements to keep unchanged\n4. **Quality**: Desired output quality or style\n\n### Effective Edit Patterns\n\n**Background Changes:**\n```\n\"[Subject description], replace background with [new background], maintain subject lighting and pose\"\n```\n\n**Style Transfers:**\n```\n\"[Current description] transformed into [style name] style, preserve composition and key elements\"\n```\n\n**Element Replacement:**\n```\n\"[Scene description], replace [element A] with [element B], keep everything else identical\"\n```\n\n**Color Adjustments:**\n```\n\"[Image description], change color scheme to [colors], maintain contrast and composition\"\n```\n\n## Supported Image Sizes\n\n- `1024x1024` - Square (Best for general editing)\n- `768x1344` - Portrait\n- `864x1152` - Portrait\n- `1344x768` - Landscape\n- `1152x864` - Landscape\n- `1440x720` - Wide landscape\n- `720x1440` - Tall portrait\n\n## Remember\n\n- Always use z-ai-web-dev-sdk in backend code only\n- The SDK is already installed - import as shown\n- CLI tool is available for quick image editing\n- Be specific about what to change AND what to preserve\n- Include base description for better context\n- Use appropriate size for the edit type\n- Implement retry logic for production applications\n- Test edit prompts iteratively for best results\n- Consider creating variations to explore options\n- Base64 images need to be decoded before saving\n",{"name":5,"license":14,"description":7},"main","98424cecddddf49c7a3d5f70f34d8bfff7e74357","skills\u002Fimage-edit","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio","https:\u002F\u002Fgithub.com\u002Fnordeim","A freelance IT engineer","2026-07-06 19:55:45",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add nordeim\u002Fyoga-studio --skill image-edit",{"tool":37,"command":38},"bunx","bunx skills add nordeim\u002Fyoga-studio --skill image-edit",{"tool":40,"command":41},"pnpm","pnpm dlx skills add nordeim\u002Fyoga-studio --skill image-edit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fimage-edit\u002FSKILL.md",true,[45,50],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":15},"LICENSE.txt","LICENSE","许可证",1080,{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"scripts\u002Fimage-edit.ts","SCRIPT","脚本",1158,"https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fimage-edit\u002Fscripts\u002Fimage-edit.ts",[57,66,74,82,89,97],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":61,"licenseFileUrl":62,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M783VZ3397F6J78J4FTDJN4S","webapp-testing","Web application testing principles. E2E, Playwright, deep audit strategies.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":70,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M783VE24VSNZVBGZD1S88XCF","web-search","Implement web search capabilities using the z-ai-web-dev-sdk. Use this skill when the user needs to search for real-time information from the web, retrieve up-to-date content beyond the knowledge cutoff, or find the latest news and data. Returns structured search results with URLs, snippets, and metadata.","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fweb-search\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fweb-search\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":78,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M783V8S6X871D5Z7X8TJDCQS","web-reader","Implement web page content extraction capabilities using the z-ai-web-dev-sdk. Use this skill when the user needs to scrape web pages, extract article content, retrieve page metadata, or build applications that process web content. Supports automatic content extraction with title, HTML, and publication time retrieval.","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fweb-reader\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fweb-reader\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M783V2QN3TQBPB06WK5C3PED","web-frameworks","Build modern full-stack web applications with Next.js 16 + React 19 (App Router, Server Components, RSC, PPR, cacheComponents, async params, SSR, SSG, ISR, standalone output), Turborepo (monorepo, task pipelines, remote caching, parallel execution), and RemixIcon (3100+ SVG icons). Use when creating React applications, implementing server-side rendering, setting up monorepos, optimizing build performance and caching, or working with TypeScript full-stack projects.","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fweb-frameworks\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":93,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M783TJF06W3R5KVKWH4AGVE5","video-understand","Implement specialized video understanding capabilities using the z-ai-web-dev-sdk. Use this skill when the user needs to analyze video content, understand motion and temporal sequences, extract information from video frames, describe video scenes, or perform video-based AI analysis. Optimized for MP4, AVI, MOV, and other common video formats.","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fvideo-understand\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fvideo-understand\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":101,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M783TC8J5JMJY4369A7HCJ3G","video-generation","Implement AI-powered video generation capabilities using the z-ai-web-dev-sdk. Use this skill when the user needs to generate videos from text prompts or images, create video content programmatically, or build applications that produce video outputs. Supports asynchronous task management with status polling and result retrieval.","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fvideo-generation\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fnordeim\u002Fyoga-studio\u002Fblob\u002Fmain\u002Fskills\u002Fvideo-generation\u002FSKILL.md",[],[]]