Grok 图片编辑接口 - apizt API 中转接口
▼
Authorization
在 Header 添加参数 Authorization,其值为 Bearer 之后拼接 Token
示例:
Authorization: Bearer ********************
请求参数
Header 参数
Authorization
string
可选
示例: Bearer {{YOUR_API_KEY}}
Body 参数multipart/form-data
modelstring必需
示例:grok-imagine-image-2.0
promptstring必需
示例:将背景改为海滩
imagefile必需
选择本地文件,使用 multipart/form-data 上传。
请求示例代码
{
"model": "grok-imagine-image-2.0",
"prompt": "将背景改为海滩"
}
curl --fail-with-body --request POST 'https://api.apizt.com/v1/images/edits' \
--header "Authorization: Bearer ${tokenba_API_KEY}" \
--form 'model=grok-imagine-image-2.0' \
--form 'prompt=将背景改为海滩' \
--form '[email protected]'
async function main() {
const headers = { Authorization: "Bearer " + process.env.tokenba_API_KEY };
const { readFile } = require("node:fs/promises");
const body = new FormData();
body.append("model", "grok-imagine-image-2.0");
body.append("prompt", "将背景改为海滩");
body.append("image", new Blob([await readFile("reference.png")], { type: "image/png" }), "reference.png");
const response = await fetch("https://api.apizt.com/v1/images/edits", { method: "POST", headers, body });
const result = await response.text();
if (!response.ok) throw new Error("HTTP " + response.status + ": " + result);
console.log(result);
}
main().catch(console.error);
import okhttp3.*;
import java.io.File;
class Example {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
MultipartBody.Builder form = new MultipartBody.Builder().setType(MultipartBody.FORM);
form.addFormDataPart("model", "grok-imagine-image-2.0");
form.addFormDataPart("prompt", "将背景改为海滩");
form.addFormDataPart("image", "reference.png", RequestBody.create(MediaType.parse("image/png"), new File("reference.png")));
RequestBody body = form.build();
Request.Builder request = new Request.Builder().url("https://api.apizt.com/v1/images/edits").header("Authorization", "Bearer " + System.getenv("tokenba_API_KEY"));
request.method("POST", body);
try (Response response = client.newCall(request.build()).execute()) {
if (!response.isSuccessful()) throw new Exception("HTTP " + response.code());
System.out.println(response.body().string());
}
}
}
import Foundation
var request = URLRequest(url: URL(string: "https://api.apizt.com/v1/images/edits")!)
request.httpMethod = "POST"
request.setValue("Bearer " + ProcessInfo.processInfo.environment["tokenba_API_KEY"]!, forHTTPHeaderField: "Authorization")
let boundary = UUID().uuidString
var data = Data()
func append(_ value: String) { data.append(value.data(using: .utf8)!) }
append("--\(boundary)\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\ngrok-imagine-image-2.0\r\n")
append("--\(boundary)\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\n将背景改为海滩\r\n")
append("--\(boundary)\r\nContent-Disposition: form-data; name=\"image\"; filename=\"reference.png\"\r\nContent-Type: image/png\r\n\r\n")
data.append(try Data(contentsOf: URL(fileURLWithPath: "reference.png")))
append("\r\n")
append("--\(boundary)--\r\n")
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpBody = data
let (data, response) = try await URLSession.shared.data(for: request)
print((response as? HTTPURLResponse)?.statusCode ?? 0)
print(String(data: data, encoding: .utf8) ?? "")
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
"mime/multipart"
)
func main() {
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
if err := writer.WriteField("model", "grok-imagine-image-2.0"); err != nil { panic(err) }
if err := writer.WriteField("prompt", "将背景改为海滩"); err != nil { panic(err) }
file0, err := os.Open("reference.png")
if err != nil { panic(err) }; defer file0.Close()
part0, err := writer.CreateFormFile("image", "reference.png")
if err != nil { panic(err) }
if _, err = io.Copy(part0, file0); err != nil { panic(err) }
if err := writer.Close(); err != nil { panic(err) }
req, err := http.NewRequest("POST", "https://api.apizt.com/v1/images/edits", &buffer)
if err != nil { panic(err) }
req.Header.Set("Authorization", "Bearer " + os.Getenv("tokenba_API_KEY"))
req.Header.Set("Content-Type", writer.FormDataContentType())
resp, err := http.DefaultClient.Do(req)
if err != nil { panic(err) }; defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil { panic(err) }
fmt.Println(resp.Status, string(data))
}
<?php
$headers = ["Authorization: Bearer " . getenv("tokenba_API_KEY")];
$body = [
'model' => 'grok-imagine-image-2.0',
'prompt' => '将背景改为海滩',
'image' => new CURLFile('reference.png'),
];
$curl = curl_init('https://api.apizt.com/v1/images/edits');
curl_setopt_array($curl, [CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => $body]);
$result = curl_exec($curl);
if ($result === false) throw new Exception(curl_error($curl));
echo $result;
curl_close($curl);
import os
import requests
from contextlib import ExitStack
headers = {"Authorization": "Bearer " + os.environ["tokenba_API_KEY"]}
data = {'model': 'grok-imagine-image-2.0', 'prompt': '将背景改为海滩'}
with ExitStack() as stack:
files = {
'image': stack.enter_context(open('reference.png', "rb")),
}
response = requests.request('POST', 'https://api.apizt.com/v1/images/edits', headers=headers, data=data, files=files, timeout=120)
response.raise_for_status()
print(response.text)
POST /v1/images/edits HTTP/1.1
Host: api.apizt.com
Authorization: Bearer YOUR_tokenba_API_KEY
Content-Type: multipart/form-data; boundary=tokenba-demo
--tokenba-demo
Content-Disposition: form-data; name="model"
grok-imagine-image-2.0
--tokenba-demo
Content-Disposition: form-data; name="prompt"
将背景改为海滩
--tokenba-demo
Content-Disposition: form-data; name="image"; filename="reference.png"
Content-Type: image/png
< ./reference.png
--tokenba-demo--
#include <curl/curl.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL *curl = curl_easy_init();
if (!curl) return 1;
char auth[4096];
snprintf(auth, sizeof(auth), "Authorization: Bearer %s", getenv("tokenba_API_KEY"));
struct curl_slist *headers = curl_slist_append(NULL, auth);
curl_mime *mime = curl_mime_init(curl);
curl_mimepart *part;
part = curl_mime_addpart(mime); curl_mime_name(part, "model"); curl_mime_data(part, "grok-imagine-image-2.0", CURL_ZERO_TERMINATED);
part = curl_mime_addpart(mime); curl_mime_name(part, "prompt"); curl_mime_data(part, "将背景改为海滩", CURL_ZERO_TERMINATED);
part = curl_mime_addpart(mime); curl_mime_name(part, "image"); curl_mime_filedata(part, "reference.png");
curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime);
curl_easy_setopt(curl, CURLOPT_URL, "https://api.apizt.com/v1/images/edits");
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
CURLcode result = curl_easy_perform(curl);
curl_mime_free(mime);
curl_slist_free_all(headers); curl_easy_cleanup(curl); curl_global_cleanup();
return result == CURLE_OK ? 0 : 1;
}
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using var client = new HttpClient();
using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.apizt.com/v1/images/edits");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("tokenba_API_KEY"));
using var form = new MultipartFormDataContent();
form.Add(new StringContent("grok-imagine-image-2.0"), "model");
form.Add(new StringContent("将背景改为海滩"), "prompt");
form.Add(new StreamContent(File.OpenRead("reference.png")), "image", "reference.png");
request.Content = form;
using var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
dispatch_semaphore_t done = dispatch_semaphore_create(0);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.apizt.com/v1/images/edits"]];
request.HTTPMethod = @"POST";
NSDictionary *env = [[NSProcessInfo processInfo] environment];
[request setValue:[@"Bearer " stringByAppendingString:env[@"tokenba_API_KEY"]] forHTTPHeaderField:@"Authorization"];
NSString *boundary = [[NSUUID UUID] UUIDString];
NSMutableData *data = [NSMutableData data];
[data appendData:[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\ngrok-imagine-image-2.0\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\n将背景改为海滩\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"image\"; filename=\"reference.png\"\r\nContent-Type: image/png\r\n\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[NSData dataWithContentsOfFile:@"reference.png"]];
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:[@"multipart/form-data; boundary=" stringByAppendingString:boundary] forHTTPHeaderField:@"Content-Type"];
request.HTTPBody = data;
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) { NSLog(@"%@", error); dispatch_semaphore_signal(done); return; }
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
dispatch_semaphore_signal(done);
}] resume];
dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);
}
return 0;
}
require "net/http"
require "json"
uri = URI("https://api.apizt.com/v1/images/edits")
request = Net::HTTPGenericRequest.new("POST", true, true, uri.request_uri)
request["Authorization"] = "Bearer " + ENV.fetch("tokenba_API_KEY")
files = []
begin
fields = [["model", "grok-imagine-image-2.0"], ["prompt", "将背景改为海滩"]]
file = File.open("reference.png", "rb"); files << file; fields << ["image", file]
request.set_form(fields, "multipart/form-data")
puts Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request).body }
ensure
files.each(&:close)
end
open Lwt.Infix
let () =
let headers = Cohttp.Header.init_with "Authorization" ("Bearer " ^ Sys.getenv "tokenba_API_KEY") in
let data = "--tokenba-demo\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\ngrok-imagine-image-2.0\r\n" ^
"--tokenba-demo\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\n将背景改为海滩\r\n" ^
"--tokenba-demo\r\nContent-Disposition: form-data; name=\"image\"; filename=\"reference.png\"\r\nContent-Type: image/png\r\n\r\n" ^
(let f = open_in_bin "reference.png" in let data = really_input_string f (in_channel_length f) in close_in f; data) ^
"\r\n" ^
"--tokenba-demo--\r\n" in
let headers = Cohttp.Header.add headers "Content-Type" "multipart/form-data; boundary=tokenba-demo" in
Lwt_main.run (
Cohttp_lwt_unix.Client.call ~headers ~body:(Cohttp_lwt.Body.of_string data) `POST (Uri.of_string "https://api.apizt.com/v1/images/edits") >>= fun (_, body) ->
Cohttp_lwt.Body.to_string body >|= print_endline
)
import "dart:io";
import "package:http/http.dart" as http;
Future<void> main() async {
final headers = {"Authorization": "Bearer ${Platform.environment['tokenba_API_KEY']}"};
final request = http.MultipartRequest("POST", Uri.parse("https://api.apizt.com/v1/images/edits"));
request.headers.addAll(headers);
request.fields["model"] = "grok-imagine-image-2.0";
request.fields["prompt"] = "将背景改为海滩";
request.files.add(await http.MultipartFile.fromPath("image", "reference.png"));
final response = await request.send();
print(response.statusCode);
print(await response.stream.bytesToString());
}
library(httr)
headers <- c(Authorization = paste("Bearer", Sys.getenv("tokenba_API_KEY")))
body <- list(
model = "grok-imagine-image-2.0",
prompt = "将背景改为海滩",
image = upload_file("reference.png")
)
response <- VERB("POST", "https://api.apizt.com/v1/images/edits", add_headers(.headers = headers), body = body, encode = "multipart")
stop_for_status(response)
cat(content(response, "text", encoding = "UTF-8"))
返回响应
响应参数 🟢 200 OK · application/json
object
可选
{ "created": 1773127037, "data": [ { "url": "https://pub-85624410c6c44bdb802187ae2bd8afff.r2.dev/grok/8903fc79-152b-4b80-b384-d74ae6775b07.jpg" } ], "usage": { "generated_images": 1, "output_tokens": 16384, "total_tokens": 16384 } }
示例先设置 tokenba_API_KEY。JavaScript 使用 Node.js 20+,Python 安装 requests。流式示例的 Python 与 JavaScript 会逐段输出事件数据。代码中的 ID、文件名与令牌须替换为自己的值。
当前示例模型 ID 为 grok-imagine-image-2.0,对应 apizt 价格页所列接口协议;请为令牌选择包含该型号的分组。
当前模型与版本
依据 apizt 价格页,同步于 。以下型号按目录声明的协议与本页用途筛选;不代表所有参数和功能通用。切换前请核对型号说明、令牌分组与参数差异。Gemini 原生接口需同时替换 URL 中的模型 ID。
| 模型 ID | 能力标签 | 支持分组 |
|---|---|---|
grok-imagine-image-quality | 绘画 | 分组(1)
|
grok-imagine-image-2.0 | 绘画 | 分组(1)
|
共列入 2 个候选型号。查看完整模型、版本与接口目录。