텍스트 편집기를 통해 바이너리 데이터를 요청에 삽입하는 것은 바람직하지 않으며 실용적이지도 않습니다. 실제로는 클라이언트 코드에 base64 인코딩 파일을 삽입합니다. 지원되는 모든 프로그래밍 언어에는 base64 인코딩 콘텐츠를 위한 기본 메커니즘이 있습니다.
Python
# Import the base64 encoding library.importbase64# Pass the image data to an encoding function.defencode_image(image):withopen(image,"rb")asimage_file:encoded_string=base64.b64encode(image_file.read())returnencoded_string
Node.js
// Read the file into memory.varfs=require('fs');varimageFile=fs.readFileSync('/path/to/file');// Convert the image data to a Buffer and base64 encode it.varencoded=Buffer.from(imageFile).toString('base64');
자바
// Import the Base64 encoding library.importorg.apache.commons.codec.binary.Base64;// Encode the image.StringencodedString=Base64.getEncoder().encodeToString(imageFile.getBytes());
Go
import("bufio""encoding/base64""io""os")// Open image file.f,_:=os.Open("image.jpg")// Read entire image into byte slice.reader:=bufio.NewReader(f)content,_:=io.ReadAll(reader)// Encode image as base64.base64.StdEncoding.EncodeToString(content)
Base64 디코딩 이미지
API 요청은 생성 또는 수정된 이미지를 base64로 인코딩된 문자열로 반환합니다. 다음 클라이언트 라이브러리 샘플을 사용하여 이 데이터를 디코딩하고 로컬에 이미지 파일로 저장할 수 있습니다.
Python
# Import the base64 encoding library.importbase64# Pass the base64 encoded image data to a decoding function and save image file.defdecode_image(b64_encoded_string):withopen("b64DecodedImage.png","wb")asfh:fh.write(base64.decodebytes(b64_encoded_string))
Node.js
varfs=require('fs');// Create buffer object, specifying base64 as encodingvarbuf=Buffer.from(base64str,'base64');// Write buffer content to a filefs.writeFile("b64DecodedImage.png",buf,function(error){if(error){throwerror;}else{console.log('File created from base64 string');returntrue;}});
자바
// Import librariesimportorg.apache.commons.codec.binary.Base64;importorg.apache.commons.io.FileUtils;// Create new fileFilefile=newFile("./b64DecodedImage.png");// Convert base64 encoded string to byte arraybyte[]bytes=Base64.decodeBase64("base64");// Write out fileFileUtils.writeByteArrayToFile(file,bytes);
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[],[],null,["# Base64 encode and decode files\n\nBase64 encode images\n--------------------\n\nTo make image generation requests you must send image data as\n[Base64 encoded](https://en.wikipedia.org/wiki/Base64) text.\n\nUsing the command line\n----------------------\n\nWithin a gRPC request, you can simply write binary data out directly;\nhowever, JSON is used when making a REST request. JSON\nis a text format that does not directly support binary data, so you will need to\nconvert such binary data into text using\n[Base64](https://en.wikipedia.org/wiki/Base64) encoding.\n\nMost development environments contain a native `base64` utility to\nencode a binary into ASCII text data. To encode a file: \n\n### Linux\n\nEncode the file using the `base64` command line tool, making sure to\nprevent line-wrapping by using the `-w 0` flag: \n\n```\nbase64 INPUT_FILE -w 0 \u003e OUTPUT_FILE\n```\n\n### macOS\n\nEncode the file using the `base64` command line tool: \n\n```\nbase64 -i INPUT_FILE -o OUTPUT_FILE\n```\n\n### Windows\n\nEncode the file using the `Base64.exe` tool: \n\n```\nBase64.exe -e INPUT_FILE \u003e OUTPUT_FILE\n```\n\n### PowerShell\n\nEncode the file using the `Convert.ToBase64String` method: \n\n```\n[Convert]::ToBase64String([IO.File]::ReadAllBytes(\"./INPUT_FILE\")) \u003e OUTPUT_FILE\n```\n\nCreate a JSON request file, inlining the base64-encoded data: \n\n### JSON\n\n\n```json\n{\n \"instances\": [\n {\n \"prompt\": \"\u003cvar translate=\"no\"\u003eTEXT_PROMPT\u003c/var\u003e\",\n \"image\": {\n \"bytes_base64_encoded\": \"\u003cvar translate=\"no\"\u003eB64_BASE_IMAGE\u003c/var\u003e\"\n }\n }\n ]\n}\n```\n\n\u003cbr /\u003e\n\nUsing client libraries\n----------------------\n\nEmbedding binary data into requests through text editors is neither\ndesirable or practical. In practice, you will be embedding base64 encoded files\nwithin client code. All supported programming languages have built-in mechanisms\nfor base64 encoding content. \n\n### Python\n\n # Import the base64 encoding library.\n import base64\n\n # Pass the image data to an encoding function.\n def encode_image(image):\n with open(image, \"rb\") as image_file:\n encoded_string = base64.b64encode(image_file.read())\n return encoded_string\n\n### Node.js\n\n // Read the file into memory.\n var fs = require('fs');\n var imageFile = fs.readFileSync('/path/to/file');\n\n // Convert the image data to a Buffer and base64 encode it.\n var encoded = Buffer.from(imageFile).toString('base64');\n\n### Java\n\n // Import the Base64 encoding library.\n import org.apache.commons.codec.binary.Base64;\n\n // Encode the image.\n String encodedString = Base64.getEncoder().encodeToString(imageFile.getBytes());\n\n### Go\n\n import (\n \"bufio\"\n \"encoding/base64\"\n \"io\"\n \"os\"\n )\n\n // Open image file.\n f, _ := os.Open(\"image.jpg\")\n\n // Read entire image into byte slice.\n reader := bufio.NewReader(f)\n content, _ := io.ReadAll(reader)\n\n // Encode image as base64.\n base64.StdEncoding.EncodeToString(content)\n\nBase64 decode images\n--------------------\n\nAPI requests return generated or edited images as base64-encoded strings. You\ncan use the following client library samples to decode this data and save it\nlocally as an image file. \n\n### Python\n\n # Import the base64 encoding library.\n import base64\n\n # Pass the base64 encoded image data to a decoding function and save image file.\n def decode_image(b64_encoded_string):\n with open(\"b64DecodedImage.png\", \"wb\") as fh:\n fh.write(base64.decodebytes(b64_encoded_string))\n\n### Node.js\n\n var fs = require('fs');\n\n // Create buffer object, specifying base64 as encoding\n var buf = Buffer.from(base64str,'base64');\n\n // Write buffer content to a file\n fs.writeFile(\"b64DecodedImage.png\", buf, function(error){\n if(error){\n throw error;\n }else{\n console.log('File created from base64 string');\n return true;\n }\n });\n\n### Java\n\n // Import libraries\n import org.apache.commons.codec.binary.Base64;\n import org.apache.commons.io.FileUtils;\n\n // Create new file\n File file = new File(\"./b64DecodedImage.png\");\n // Convert base64 encoded string to byte array\n byte[] bytes = Base64.decodeBase64(\"base64\");\n // Write out file\n FileUtils.writeByteArrayToFile(file, bytes);\n\n### Go\n\n // Import packages\n import (\n \"encoding/base64\"\n \"io\"\n \"os\"\n )\n\n // Add encoded file string\n var b64 = `\u003cvar translate=\"no\"\u003eTWFuIGlz...Vhc3VyZS4=\u003c/var\u003e`\n\n // Decode base64-encoded string\n dec, err := base64.StdEncoding.DecodeString(b64)\n if err != nil {\n panic(err)\n }\n\n // Create output file\n f, err := os.Create(\"b64DecodedImage.png\")\n if err != nil {\n panic(err)\n }\n defer f.Close()\n\n if _, err := f.Write(dec); err != nil {\n panic(err)\n }\n if err := f.Sync(); err != nil {\n panic(err)\n }"]]