使用 Codex 制作图片从代码到视觉艺术的完整指南前言在 AI 时代用代码生成图片已经从一种小众技术变成了主流创作方式。无论是通过 Python 脚本自动化制图、调用 AI 绘画 API还是直接使用 DALL-E、Stable Diffusion 等模型代码正在重新定义图像创作的方式。本文将带你系统了解如何用代码Code制作图片涵盖从传统的编程绘图到最新的 AI 图像生成技术。一、什么是 CodexCodex 这个名称最早被大众熟知是 OpenAI 推出的代码生成模型GitHub Copilot 的底层模型。它能够根据自然语言描述生成代码。但在本文语境中Codex 制作图片泛指用代码驱动的方式来创建和生成图片包括但不限于用 Python 库Pillow、OpenCV编程绘图用 matplotlib 生成数据可视化图表调用 DALL-E、Stable Diffusion API 生成 AI 图像用 SVG/Canvas/Three.js 等前端技术创作视觉内容二、传统方式用 Python 编程绘图2.1 Pillow — 最基础的图像处理库fromPILimportImage,ImageDraw,ImageFontimportrandom# 创建一个 800x600 的画布imgImage.new(RGB,(800,600),color(30,30,30))drawImageDraw.Draw(img)# 绘制渐变背景foriinrange(600):rint(30i*0.3)gint(30i*0.1)bint(60i*0.2)draw.line([(0,i),(800,i)],fill(r,g,b))# 绘制随机圆形for_inrange(50):xrandom.randint(0,800)yrandom.randint(0,600)radiusrandom.randint(10,80)color(random.randint(100,255),random.randint(100,255),random.randint(100,255))draw.ellipse([x-radius,y-radius,xradius,yradius],outlinecolor,width2)img.save(art_output.png)print(图片已生成art_output.png)效果以上代码生成了一个带有渐变背景和随机圆形点缀的抽象艺术作品。2.2 matplotlib — 从数据到可视化importmatplotlib.pyplotaspltimportnumpyasnp# 生成曼德勃罗集Mandelbrot Setdefmandelbrot(c,max_iter):z0forninrange(max_iter):ifabs(z)2:returnn zz*zcreturnmax_iter width,height800,600max_iter100xnp.linspace(-2.5,1.5,width)ynp.linspace(-1.5,1.5,height)imgnp.zeros((height,width))foriinrange(height):forjinrange(width):img[i,j]mandelbrot(complex(x[j],y[i]),max_iter)plt.figure(figsize(12,8))plt.imshow(img,cmaphot,extent[-2.5,1.5,-1.5,1.5])plt.axis(off)plt.savefig(mandelbrot.png,dpi150,bbox_inchestight)print(曼德勃罗集已生成mandelbrot.png)效果生成经典的曼德勃罗集分形图案代码虽简单但视觉效果极其震撼。三、AI 时代调用 API 生成图像3.1 使用 OpenAI DALL-E APIfromopenaiimportOpenAIimportrequests clientOpenAI(api_keyyour-api-key)responseclient.images.generate(modeldall-e-3,prompt一只穿着宇航服的柴犬在月球上漫步背景是蓝色的地球高清写实风格,size1024x1024,qualitystandard,n1,)image_urlresponse.data[0].url# 下载并保存图片img_datarequests.get(image_url).contentwithopen(dalle_output.png,wb)asf:f.write(img_data)print(fAI 图像已生成dalle_output.png)print(f图片 URL{image_url})3.2 使用 Stable Diffusion WebUI API如果你在本地部署了 Stable Diffusion WebUI可以通过 API 调用importjsonimportbase64importrequests urlhttp://127.0.0.1:7860/sdapi/v1/txt2imgpayload{prompt:a beautiful landscape with mountains and a lake at sunset, oil painting style,negative_prompt:blurry, low quality, distorted,steps:30,width:768,height:512,cfg_scale:7,sampler_name:Euler a,}responserequests.post(url,jsonpayload)rresponse.json()# 保存生成的图片fori,img_strinenumerate(r[images]):img_database64.b64decode(img_str)withopen(fsd_output_{i}.png,wb)asf:f.write(img_data)print(fStable Diffusion 已生成{len(r[images])}张图片)3.3 使用 Replicate API无需本地 GPUimportreplicateimportrequests outputreplicate.run(stability-ai/stable-diffusion-3,input{prompt:一个赛博朋克风格的未来城市霓虹灯闪烁雨夜氛围,width:1024,height:1024,num_outputs:2,})fori,urlinenumerate(output):img_datarequests.get(url).contentwithopen(freplicate_output_{i}.png,wb)asf:f.write(img_data)print(Replicate 图像生成完成)四、前端技术用代码在浏览器中绘图4.1 HTML Canvas 生成艺术!DOCTYPEhtmlhtmlheadtitleCanvas 生成艺术/title/headbodycanvasidcanvaswidth800height600/canvasscriptconstcanvasdocument.getElementById(canvas);constctxcanvas.getContext(2d);// 绘制 Mandelbrot 集constmaxIter100;constimgDatactx.createImageData(800,600);for(letpy0;py600;py){for(letpx0;px800;px){letx0(px/800)*3.5-2.5;lety0(py/600)*2.0-1.0;letx0,y0,iter0;while(x*xy*y4itermaxIter){letxtx*x-y*yx0;y2*x*yy0;xxt;iter;}constidx(py*800px)*4;consttiter/maxIter;imgData.data[idx]Math.floor(9*(1-t)*t*t*t*255);imgData.data[idx1]Math.floor(15*(1-t)*(1-t)*t*t*255);imgData.data[idx2]Math.floor(8.5*(1-t)*(1-t)*(1-t)*t*255);imgData.data[idx3]255;}}ctx.putImageData(imgData,0,0);/script/body/html4.2 SVG 编程创建矢量图形# 用 Python 生成 SVGdefcreate_svg_art():svgsvg xmlnshttp://www.w3.org/2000/svg viewBox0 0 800 600 defs linearGradient idbg x10% y10% x2100% y2100% stop offset0% stylestop-color:#0f0c29/ stop offset50% stylestop-color:#302b63/ stop offset100% stylestop-color:#24243e/ /linearGradient /defs rect width800 height600 fillurl(#bg)/importmathforiinrange(12):anglei*30*math.pi/180cx400250*math.cos(angle)cy300250*math.sin(angle)r30i*5svgf\n circle cx{cx:.0f} cy{cy:.0f} r{r} fillnone strokergba(255,255,255,0.3) stroke-width2/svg\n/svgwithopen(svg_art.svg,w)asf:f.write(svg)print(SVG 矢量图已生成svg_art.svg)create_svg_art()五、实战打造一个批量图片生成工具下面是一个更完整的工具支持批量生成不同风格的图片importosfromPILimportImage,ImageDraw,ImageFilterimportcolorsysimportrandomclassImageGenerator:简单的编程图片生成器def__init__(self,width800,height600):self.widthwidth self.heightheightdefgenerate_gradient(self,colors,directionvertical):生成渐变色背景imgImage.new(RGB,(self.width,self.height))pixelsimg.load()foryinrange(self.height):ty/self.heightifdirectionverticalelse0iflen(colors)2:rint(colors[0][0](colors[1][0]-colors[0][0])*t)gint(colors[0][1](colors[1][1]-colors[0][1])*t)bint(colors[0][2](colors[1][2]-colors[0][2])*t)else:r,g,bcolors[0]forxinrange(self.width):pixels[x,y](r,g,b)returnimgdefadd_noise(self,img,intensity20):添加噪点效果pixelsimg.load()foryinrange(self.height):forxinrange(self.width):r,g,bpixels[x,y]noiserandom.randint(-intensity,intensity)pixels[x,y](max(0,min(255,rnoise)),max(0,min(255,gnoise)),max(0,min(255,bnoise)))returnimgdefgenerate_abstract(self,num_shapes80):生成抽象艺术作品bg_colorrandom.choice([[(20,20,40),(60,40,80)],[(10,30,40),(50,20,60)],[(30,10,30),(70,20,50)],])imgself.generate_gradient(bg_color)overlayImage.new(RGBA,(self.width,self.height),(0,0,0,0))drawImageDraw.Draw(overlay)for_inrange(num_shapes):x,yrandom.randint(0,self.width),random.randint(0,self.height)sizerandom.randint(20,200)huerandom.random()rgbtuple(int(c*255)forcincolorsys.hsv_to_rgb(hue,0.7,0.9))alpharandom.randint(20,80)shape_typerandom.choice([circle,rect,line])ifshape_typecircle:draw.ellipse([x,y,xsize,ysize],fillrgb(alpha,))elifshape_typerect:draw.rectangle([x,y,xsize,ysize//2],fillrgb(alpha,))else:draw.line([x,y,xsize,ysize],fillrgb(alpha,),widthrandom.randint(1,5))imgimg.convert(RGBA)imgImage.alpha_composite(img,overlay)returnimg.convert(RGB)# 使用示例genImageGenerator(800,600)os.makedirs(output,exist_okTrue)foriinrange(5):imggen.generate_abstract(num_shapes60)img.save(foutput/abstract_{i1}.png)print(f第{i1}张抽象图已生成)print(\n全部图片已保存到 output/ 目录)六、对比与选择建议方式优势劣势适合场景Pillow/PIL轻量、离线、精确控制功能有限简单图像处理、水印、缩略图matplotlib科学计算集成、公式渲染非设计导向数据报告、学术论文图表DALL-E API效果惊艳、开箱即用付费、网络依赖创意设计、快速原型Stable Diffusion开源、可本地运行、可控性强需要 GPU、部署复杂批量生成、定制化需求Canvas/SVG前端集成、交互性强复杂图形代码量大Web 应用、数据可视化Replicate无需显卡、按量付费网络依赖个人开发者快速接入七、总结用代码制作图片本质上是在编程思维和艺术创作之间搭了一座桥。无论你是想用几行 Python 自动化生成报表图表通过 API 调用大模型批量产出创意素材在前端项目里实时绘制交互式图像都可以通过本文介绍的方法轻松实现。随着多模态 AI 的快速发展代码 AI 组合生成图像的方式只会越来越强大。现在入坑正当其时。延伸阅读如果你对 AI 图像生成感兴趣可以继续了解 ControlNet精确控制构图、IP-Adapter图生图风格迁移以及 ComfyUI节点式图像生成工作流等进阶工具。本文代码示例均在 Python 3.10 环境下测试通过。部分 API 调用需要相应的 API Key。