Flutter generate image Recognizer to text using openAI - Devhubspot
In this Flutter Article we will make use of OpenAI DALL-E 2 API and explore the super power of OpenAI, By creating an flutter application that can convert a given Text into an AI image. You'll discover how we leverage the OpenAI API to produce a remarkable and realistic AI image, as well as how to integrate it into our Flutter app to produce an AI image from a specified text sentence.
Creating an Account
Step 1: Create an account in openai.com
In browser, search for openai.com and SignIn using Google account or any other account.
Step 2: You need to activity a billing
Added your credit card for billing, Initially OpenAI gives you $15 free to generate images from Text. Then you will be charged.
Here are charges depending on the Image Size you order for:
RESOLUTION | PRICE |
---|---|
1024×1024 | $0.020 / image |
512×512 | $0.018 / image |
256×256 | $0.016 / image |
Step 3: Generate a openai API key
Create a Flutter App
If everything is properly set up, then in order to create a project we can simply run the following command in our desired local directory:
flutter create flutter-open-ai-text-to-image
After we've set up the project, we can navigate inside the project directory and execute the following command in the terminal to run the project in either an available emulator or an actual device:
flutter run
Generate an AI Image from Text by using open ai image generation
Implementing OpenAI in Flutter App
First, we need to make some simple configurations to the default boilerplate code in the main.dart file. We'll remove some default code and add following code
import 'package:flutter/material.dart'; import 'package:texttoimageai/screens/home/home.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Home(), ); } }]
Step 1: Install http package
As we are going to make internet call in our flutter app generate an AI Image to open ai API, we need a http package to do so.
In flutter project, open pubspec.yaml file and under dependencies section add http package.
Step 2: Import the http class
In main.dart file of flutter project, Import http.dart file
import 'package:http/http.dart' as http; import 'dart:convert';
Step 3: Create a async function
Now, Create a function generateAIImage()
that makes a HTTP call to OpenAI DALL-E Image Generation API by passing desired Text of which you want AI to generate a Image.
Future<void> genrateAIImage(String value) async { setState(() { finalImages = ''; }); final url = Uri.parse("https://api.openai.com/v1/images/generations"); final headers = { "Content-Type":"application/json", "Authorization":"Bearer ${apiKey}" }; var response = await http.post(url, headers:headers, body: jsonEncode({"prompt":value, "n":1, "size":'256x256'})); print(response); if(response.statusCode == 200){ var responsedecode = jsonDecode(response.body); print(responsedecode['data'][0]['url'].toString()); // finalImages = responsedecode['data'][0]['url']; setState(() { finalImages = responsedecode['data'][0]['url']; }); }else{ print("Failed to genrate image"); } }
The above function will make a http post request to openai, so in this http request we are passing the data and in header we are passing openai authorization api key.
In request body we need to pass this parameters
prompt: a Text of which AI should generate an image.
n: Number of different image to be generate of the given text.
size: The size of the generated images.
Step 4: Show the image response in app
Once the above function return the response, we need to parse the JSON response from the API and extract only url of the generate image.
Complete Source Code – Flutter open ai image generation
Home.dart
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { String finalImages = ''; TextEditingController texttoImage = TextEditingController(); // final apiKeys = "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"; Future<void> genrateAIImage(String value) async { setState(() { finalImages = ''; }); final url = Uri.parse("https://api.openai.com/v1/images/generations"); final headers = { "Content-Type":"application/json", "Authorization":"Bearer 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" }; var response = await http.post(url, headers:headers, body: jsonEncode({"prompt":value, "n":1, "size":'256x256'})); print(response); if(response.statusCode == 200){ var responsedecode = jsonDecode(response.body); print(responsedecode['data'][0]['url'].toString()); // finalImages = responsedecode['data'][0]['url']; setState(() { finalImages = responsedecode['data'][0]['url']; }); }else{ print("Failed to genrate image"); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Open AI"), elevation: 0, ), body: Container( child: Column(children: [ Padding( padding: const EdgeInsets.all(16.0), child: TextField( controller: texttoImage, onSubmitted: (value) async { await genrateAIImage(value); }, decoration: InputDecoration( hintText: "Enter Text to Generate AI Image", filled: true, fillColor: Colors.blue.shade100, border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none), suffixIcon: IconButton(icon: const Icon(Icons.clear, color: Colors.black), onPressed: () {}, ), prefixIcon: IconButton(icon: const Icon(Icons.search, color: Colors.black), onPressed: () {}, ), ), ), ), Container( padding: const EdgeInsets.all(10), height: 400, child: finalImages !='' ? Image.network(finalImages, width: 256, height: 256,) : const Text("Please enter text to Genearte Ai Image"), ) ],) ), ); } }