Image field format guide
File field format guide
Files, such as images, audio, and video, support the following two formats when passed as input parameters:
URL format
Description: This format references a file resource using an external link. The URL must be an accessible web address that points to a valid file.
Example:
{ "image": "https://example.com/image.jpg" }Notes:
Ensure the URL is publicly accessible. Avoid URLs from a VPC or with restricted access.
When you pass a URL, ensure the service that provides the file resource has stable network connectivity. This prevents file read failures caused by network issues.
Base64 Data URI format
Description: This format embeds file data directly into the request in a Base64-encoded format. This method is suitable for small files and for scenarios that require file data to be embedded directly in the request.
Example:
{ "image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/..." }Notes:
Base64-encoded data can be large. Use this format only for small images.
Ensure the file data is encoded correctly and includes the correct Multipurpose Internet Mail Extensions (MIME) type prefix, such as
data:image/jpeg;base64,.Using Base64 encoding increases the request size and can affect performance. Use this method only when necessary.
Recommendations
In most cases, use the URL format. This format reduces the request size and is better for referencing hosted file resources.
The Base64 Data URI format is better for scenarios in which you want to embed file data directly in the request, such as for confidential data or temporary use.
Appendix
The following Python utility class shows how to convert a local image to a Base64 Data URI.
import base64
import os
def get_photo_base64(image_path, image_format=None):
"""
Converts an image file to a Base64-encoded Data URI.
Parameters:
image_path (str): The path to the image file.
image_format (str, optional): The image format. If not provided, it is automatically detected from the file name extension.
Returns:
str: The Base64-encoded Data URI.
"""
# Open the image file.
with open(image_path, "rb") as image_file:
image_data = image_file.read()
# If the image format is not specified, get it from the file name extension.
if not image_format:
_, extension = os.path.splitext(image_path)
image_format = extension.lstrip(".")
# Generate the Base64-encoded Data URI.
base64_data = base64.b64encode(image_data).decode('utf-8')
data_uri = f"data:image/{image_format.upper()};base64,{base64_data}"
return data_uri
print(get_photo_base64('/xxx/xxx.png'))
print(get_photo_base64('/xxx/xxx.jpeg', "jpeg"))