Sample code for 30+ languages & platforms
Android™

Upload an Image File to an AI Provider (OpenAI, Google, Antropic, X)

See more AI Examples

Uploads an image file to an AI provider using the provider's File API and returns the id that can later be used to reference the file in an query. This currently works with ChatGPT and Gemini, but not other AI's. Most AI's currently don't have the ability to reference pre-uploaded image data in conversations.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    CkAi ai = new CkAi();

    // Can currently be "openai" or "google" because these are the only AI's that can reference pre-loaded image data by file ID.
    ai.put_Provider("openai");
    // Use your provider's API key.
    ai.put_ApiKey("MY_API_KEY");

    // We can upload directly from a file in the filesystem, or from a Chilkat BinData.

    String contentType = "image/jpeg";
    String localFilePath = "qa_data/jpg/starfish.jpg";
    String filenameOnServer = "starfish.jpg";

    // Upload directly from a file.
    String file_id = ai.uploadFile(localFilePath,contentType);
    if (ai.get_LastMethodSuccess() == false) {
        Log.i(TAG, ai.lastErrorText());
        Log.i(TAG, "AI File Upload Failed.");
        }
    else {
        Log.i(TAG, "File ID: " + file_id);
        Log.i(TAG, "File uploaded.");
        }

    // Upload from the contents of a Chilkat BinData
    CkBinData bd = new CkBinData();
    success = bd.LoadFile(localFilePath);
    if (success == false) {
        Log.i(TAG, bd.lastErrorText());
        return;
        }

    file_id = ai.uploadFileBd(bd,filenameOnServer,contentType);
    if (ai.get_LastMethodSuccess() == false) {
        Log.i(TAG, ai.lastErrorText());
        Log.i(TAG, "AI File Upload Failed.");
        }
    else {
        Log.i(TAG, "File ID: " + file_id);
        Log.i(TAG, "File uploaded.");
        }


  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}