This video shows the steps to use Open AI ChatGPT Dall-e RestAPIs to generate the images as per the prompt by the user of your Android App.
It refers to the curl commands provided in the below URLs:
https://openai.com/blog/dall-e-api-now-available-in-public-beta
https://platform.openai.com/docs/api-reference/images/create
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Complete source code and other details:
package com.programmerworld.aiimageusingchatgptdalle;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private EditText editText;
private TextView textView;
private String stringURLEndPoint = "https://api.openai.com/v1/images/generations";
private String stringAPIKey = "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";
private String stringOutput = "https://oaidalleapiprodscus.blob.core.windows.net/private/org-7vaCBBIvQdn5T6iXJ5d9rMCK/user-TuzNiGDDYMyNRWmuNsBV0Wc7/img-cimO4tIniv2MuvgI6GBIYOYB.png?st=2023-09-23T08%3A26%3A40Z&se=2023-09-23T10%3A26%3A40Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-09-22T22%3A41%3A54Z&ske=2023-09-23T22%3A41%3A54Z&sks=b&skv=2021-08-06&sig=T%2Bt87bUWUEWBRmGMLoqNH4fIgOIvEwDN5KHUogVS%2BLQ%3D";
private Bitmap bitmapOutputImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
}
public void buttonGenerateAIImage(View view){
String stringInputText = editText.getText().toString();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("prompt", stringInputText);
} catch (JSONException e) {
throw new RuntimeException(e);
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
stringURLEndPoint,
jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
stringOutput = response
.getJSONArray("data")
.getJSONObject(0)
.getString("url");
textView.setText(stringOutput);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textView.setText("ERROR");
}
}
){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> mapHeader = new HashMap<>();
mapHeader.put("Authorization", "Bearer "+stringAPIKey);
mapHeader.put("Content-Type", "application/json");
return mapHeader;
}
};
int intTimeOutPeriod = 60000; // 60 seconds
RetryPolicy retryPolicy = new DefaultRetryPolicy(intTimeOutPeriod,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(retryPolicy);
Volley.newRequestQueue(getApplicationContext()).add(jsonObjectRequest);
}
public void buttonShowImage(View view){
textView.setText("Thread is in process");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(stringOutput);
bitmapOutputImage = BitmapFactory.decodeStream(url.openStream());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
while (thread.isAlive()){
textView.setText("Thread is in process");
}
Bitmap bitmapFinalImage = Bitmap.createScaledBitmap(bitmapOutputImage,
imageView.getWidth()
,imageView.getHeight(),
true);
imageView.setImageBitmap(bitmapFinalImage);
textView.setText("Image Generation SUCCESSFUL!!!");
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AIImageUsingChatGPTDalle"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
plugins {
id("com.android.application")
}
android {
namespace = "com.programmerworld.aiimageusingchatgptdalle"
compileSdk = 34
defaultConfig {
applicationId = "com.programmerworld.aiimageusingchatgptdalle"
minSdk = 34
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
dependencies {
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.9.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
implementation("com.android.volley:volley:1.2.1")
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.331" />
<EditText
android:id="@+id/editText"
android:layout_width="334dp"
android:layout_height="69dp"
android:layout_marginStart="42dp"
android:layout_marginTop="24dp"
android:ems="10"
android:hint="Input Text here ..."
android:inputType="text"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="46dp"
android:layout_marginTop="31dp"
android:onClick="buttonGenerateAIImage"
android:text="Generate AI image"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="28dp"
android:onClick="buttonShowImage"
android:text="Show Image"
app:layout_constraintStart_toEndOf="@+id/button"
app:layout_constraintTop_toBottomOf="@+id/editText" />
<ImageView
android:id="@+id/imageView"
android:layout_width="315dp"
android:layout_height="279dp"
android:layout_marginStart="45dp"
android:layout_marginTop="64dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:srcCompat="@drawable/ic_launcher_background" />
</androidx.constraintlayout.widget.ConstraintLayout>
Screenshots:
Prompt: “Mountain with rising sun”
Prompt: White Tiger
Sample output image URL:
Prompt: Baby Horse
CURL Command reference:
https://platform.openai.com/docs/api-reference/images/create
curl https://api.openai.com/v1/images/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"prompt": "A cute baby sea otter",
"n": 2,
"size": "1024x1024"
}'
{
"created": 1589478378,
"data": [
{
"url": "https://..."
},
{
"url": "https://..."
}
]
}
https://openai.com/blog/dall-e-api-now-available-in-public-beta
#generations
curl https://api.openai.com/v1/images/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"prompt": "a photo of a happy corgi puppy sitting and facing forward, studio light, longshot",
"n":1,
"size":"1024x1024"
}'