Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsUse the official OpenAI Python SDK, set OPENAI_API_KEY, call client.images.generate() for a prompt-to-image request, then base64-decode result.data[0].b64_json and write the bytes in binary mode. Use client.images.edit() when you have a reference image or mask. Model names, parameters, package releases, and account requirements change, so verify the current OpenAI image guide and API reference before deploying.
What you need before writing code
- A Python environment with permission to install packages.
- An OpenAI API key created in the OpenAI dashboard.
- The key exported as
OPENAI_API_KEY; the SDK reads it whenOpenAI()is initialized. - A current image-capable model name and supported parameter values from the live image guide. Do not assume that an example model name or option remains available.
Keep the key out of source files, notebooks committed to version control, client-side applications, and public repositories. Set it in your shell, a protected deployment secret, or your platform’s environment-variable manager. The exact dashboard controls and account requirements can change.
Install and initialize the official Python client
Install the official OpenAI package using the command shown in the current quickstart. Package names and releases can change, so avoid pinning an unverified version copied from an old tutorial. After installation, export your key and create the client:
export OPENAI_API_KEY="your_api_key_here"
python -m pip install openai
On Windows PowerShell, the equivalent environment-variable command is:
#1 Best Overall
$env:OPENAI_API_KEY="your_api_key_here"
Initialize the client without placing the secret in Python:
from openai import OpenAI
client = OpenAI()
If initialization reports a missing key, check the variable in the same shell or process that runs Python. A terminal where the variable was not exported, a misspelled variable name, or a service process that was not restarted are common causes.
Generate an image from a text prompt
For text-to-image work, call client.images.generate(). The following complete script demonstrates the documented response shape and file-writing pattern. Confirm that the model name and any optional arguments are supported by the current guide before running it.
import base64
from openai import OpenAI
client = OpenAI()
result = client.images.generate(
model="gpt-image-2",
prompt="A small red fox reading a book in a sunlit library",
)
image_bytes = base64.b64decode(result.data[0].b64_json)
with open("fox.png", "wb") as f:
f.write(image_bytes)
print("Saved fox.png")
result.data is a collection of image results. This example selects the first item, reads its base64-encoded JSON field, decodes it to raw bytes, and writes those bytes unchanged. Binary mode (wb) is essential; text mode can corrupt an image.
Make the output format and filename agree
The image API documents PNG, WebP, and JPEG output options, along with model-dependent size, quality, and background settings. If you request a format explicitly, use the matching extension:
Rank #2
import base64
from openai import OpenAI
client = OpenAI()
result = client.images.generate(
model="gpt-image-2",
prompt="A clean geometric icon of a mountain and moon",
output_format="webp",
quality="high",
)
with open("mountain.webp", "wb") as f:
f.write(base64.b64decode(result.data[0].b64_json))
The exact accepted values for output_format, quality, size, and background are model-dependent. Check the current API reference rather than assuming that every model accepts every combination. Preserve the returned bytes when you need alpha transparency; converting them through another image library can remove or alter it.
Generate reliably in a reusable function
A small function makes validation, naming, and error handling consistent across jobs. This version lets the caller choose a destination and keeps the response decoding in one place:
import base64
from pathlib import Path
from openai import OpenAI
def generate_image(prompt: str, destination: str, model: str = "gpt-image-2") -> Path:
if not prompt.strip():
raise ValueError("prompt must not be empty")
client = OpenAI()
response = client.images.generate(model=model, prompt=prompt)
encoded = response.data[0].b64_json
output = Path(destination)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_bytes(base64.b64decode(encoded))
return output
saved = generate_image(
"A watercolor map of a fictional coastal town, readable labels, no border",
"outputs/coastal-town.png",
)
print(f"Saved {saved}")
For a batch job, create one client and pass it into your worker rather than constructing a client for every image. Add your own retry policy around transient network or service failures, with a bounded number of attempts and backoff. Do not blindly retry validation errors, authentication failures, or requests that exceed the model’s limits.
Recommended Free Tools
Edit an existing image or use a reference
Use client.images.edit() when the request includes one or more existing images, asks for a transformation, or uses a mask for a localized edit. The current guide specifies the accepted file and parameter shape, so verify it before choosing a multipart argument name. Conceptually, the Python flow is:
import base64
from openai import OpenAI
client = OpenAI()
with open("source.png", "rb") as source:
result = client.images.edit(
model="gpt-image-2",
image=source,
prompt="Replace the cloudy sky with a clear sunset while keeping the buildings unchanged",
)
with open("edited.png", "wb") as f:
f.write(base64.b64decode(result.data[0].b64_json))
Reference images constrain content more directly than a text-only prompt, but they do not guarantee that every detail will remain unchanged. A mask can identify the area you want to alter, yet the model may not follow the mask boundary with pixel-perfect precision. Inspect the result and, for production workflows, retain the original and record the prompt and settings used.
Choose settings deliberately
| Decision | Use it when | What to verify |
|---|---|---|
| Generate or edit | Generate for a new scene; edit for reference images, transformations, or masks. | Current method signature and input-file requirements. |
| Size | You need a particular aspect ratio or delivery resolution. | Supported dimensions for the selected model. |
| Quality | You are balancing detail, latency, and cost for the workload. | Accepted quality values and their model-specific behavior. |
| Format | Choose PNG for lossless output and transparency, JPEG for common photographic delivery, or WebP where your pipeline supports it. | Whether the selected model supports the format and whether alpha is preserved. |
| Background | You need a solid, automatic, or transparent background. | Supported background values and transparency behavior. |
| Streaming | You want partial-image events for a progressive interface. | Event types and the final completion event carrying base64 content. |
Streaming is unnecessary for a script that only needs a completed file. It adds event-handling code, so adopt it when users benefit from progressive display rather than for a one-shot batch save.
Save, name, and validate files safely
- Use a unique or deterministic destination policy so concurrent jobs do not overwrite one another.
- Write to a temporary path and rename it after a successful decode if another process watches the output directory.
- Check that
result.datacontains an item and that the base64 field is present before writing. - Match extensions to the requested format and let downstream tools inspect the actual bytes.
- Keep prompts, model names, dimensions, and timestamps in adjacent metadata when reproducibility matters.
- Do not log API keys or entire sensitive prompts in ordinary application logs.
Common failures and fixes
Authentication or missing-key errors
Confirm that OPENAI_API_KEY is set in the running process, has not been truncated, and belongs to the intended account or project. Restart long-running services after changing environment variables.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Model or parameter not found
Model availability and accepted arguments change. Compare the model and every optional setting with the current image guide and reference. Remove optional settings one at a time to identify an incompatible value.
Invalid image or mask
Check the file path, read permissions, supported format, and the edit endpoint’s current multipart requirements. Ensure the mask and source image meet the documented size and format rules.
Base64 decoding or truncated output
Decode the returned field exactly once and write bytes with wb. If a process is interrupted, remove the partial file and retry the request with bounded backoff; do not treat a partial file as a valid result.
Timeouts and transient network failures
Use a client or transport timeout appropriate for image generation, retry only transient failures, and make retries observable. For batch work, persist job inputs so an interrupted run can resume without losing which requests already succeeded.
Unexpected mask boundaries
Masks are guidance, not a promise of exact pixel-boundary adherence. Expand the mask or adjust the prompt when necessary, and review outputs before publishing them.
Privacy and data controls
If prompts or input images contain sensitive material, review the current OpenAI data-controls documentation and your organization’s settings before sending them. OpenAI lists zero-data-retention-compatible image-generation models, but model compatibility alone does not prove that your organization’s zero-data-retention configuration is active. Confirm the effective policy with the account administrator and current documentation.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If what you actually need is a screenshot of a web page rather than a generated image, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF. Its cleanup steps accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in headers.
Using the API requires an access key. The complete documentation is at https://screenshotneo.com/docs/.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await Bun.write("shot.webp", bytes);
ScreenshotNeo also has an MCP server for Claude, Cursor, and other MCP clients, with take_screenshot, get_page_info, and capture_pdf tools. It supports full-page captures with lazy images loaded, CSS-selector element shots, dark mode, device presets, custom viewports, retina scale, PDF paper settings, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, selectable cache TTLs, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage APIs, and an OpenAPI specification. The parameter names used by other screenshot APIs also work to ease migration.
Best Value
| Plan | Included shots | Price |
|---|---|---|
| Free | 1,000 per month | $0, no card |
| Starter | 3,000 | $5 |
| Growth | 15,000 | $15 |
| Pro | 60,000 | $39 |
| Scale | 250,000 | $99 |
| Business | 1,000,000 | $249 |
Yearly billing provides two months free, and every feature is available on every plan. Start with 1,000 free screenshots a month with no card; paid plans start at $5 for 3,000.
FAQ
Do I need to download an image URL?
No. The documented image response contains base64 data, so decode it and write the resulting bytes locally.
Should I use streaming for ordinary file generation?
No. A completed response is simpler. Use streaming only when partial-image events improve an interactive experience.
Are masks exact?
No. They guide localized edits, but exact boundary adherence is not guaranteed.
Frequently Asked Questions
Can I keep the generated image in memory instead of saving it?
Yes. Keep the bytes returned by base64 decoding in a variable and pass them to your image-processing or storage library; writing with Path.write_bytes is only the local-file option.
Why should I recheck model names before deployment?
The official guide and catalog can change model availability and parameter compatibility. Treat example names as illustrative until confirmed in the current reference.
The Bottom Line
Configure OPENAI_API_KEY, call images.generate or images.edit, decode the first result’s b64_json, and write it in binary mode. Keep model-specific settings tied to the live API reference, and validate files and retries in your own deployment.
Free tools Windows power users keep installed
One-click scans. No signup required.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

