How To Generate Image Using OpenAI API In Flutter?

Introduction

Hi friends!! In this article, you will learn about how to generate images from text using OpenAI in Flutter. We are going to generate or manipulate images with DALL·E models. According to OpenAI- "DALL·E 2 can create original, realistic images and art from a text description. It can combine concepts, attributes, and styles."

 

We are going to use the following OpenAI API and response.

 OpenAI API and Response

Create image 

Source:-"OpenAI"

Let's Start With Android Studio,

Create New Flutter Project In Android Studio

Open your Android Studio and create a new project. Edit the project name, android language, iOS language, and platform, and click Create button.

Project  

Add Required Dependancy In Pubspec.yaml 

Add the following dependency in pubspec.yaml file, and please click on the pub get button.

http: ^0.13.5

HTTP Package

HTTP is a network library that allows us to make HTTP requests to the web server and receive responses. HTTP package allows us to perform operations such as making GET and POST requests.

Go to Main.dart 

Replace your existing code with the below code.

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Image Generation App',
      home: ImageGenerator(),
    );
  }
}

class ImageGenerator extends StatefulWidget {
  @override
  _ImageGeneratorState createState() => _ImageGeneratorState();
}

class _ImageGeneratorState extends State<ImageGenerator> {
  final TextEditingController _textController = TextEditingController();
  String _generatedImageUrl = '';

  Future<void> generateImage() async {
    final String apiKey = 'your OpenAI API key'; // Replace with your OpenAI API key
    final String prompt = _textController.text.toString();

    // Make a POST request to OpenAI API to generate image
    final response = await http.post(
      Uri.parse('https://api.openai.com/v1/images/generations'),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $apiKey',
      },
      body: jsonEncode({
        'prompt': prompt,
        "n": 1,
        "size": "512x512"
      }),
    );

    if (response.statusCode == 200) {
      // Parse the API response and update the generated image URL
      final responseData = jsonDecode(response.body);
      setState(() {
        _generatedImageUrl = responseData['data'][0]['url'];
      });
    } else {
      // Handle API error
      print('Error generating image: ${response.reasonPhrase}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Generation App'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Text input field for entering the prompt
            TextField(
              controller: _textController,
              decoration: InputDecoration(
                labelText: 'Enter text prompt',
              ),
            ),
            SizedBox(height: 16),
            // Button to trigger image generation
            ElevatedButton(
              onPressed: generateImage,
              child: Text('Generate Image'),
            ),
            SizedBox(height: 16),
            // Display the generated image if available
            if (_generatedImageUrl.isNotEmpty)
              Image.network(_generatedImageUrl),
          ],
        ),
      ),
    );
  }
}

Explanation

Here we have taken a simple TextField to take a prompt from the user, and the button is used to perform an action to generate an image from OpenAI. The generateImage() function is called when the "Generate Image" button is pressed. It sends a request to the OpenAI API with the user's text prompt and receives a response containing the generated image URL. If an image is generated successfully, it's displayed using the Image.network widget. Please make sure to replace 'your OpenAI API key' with your actual OpenAI API key.

Please check out the 

Output 1

Image Generator App 

Output 2

Image Generator App 

Output 3

Image Generator App 

Conclusion

In this article, we have seen how to generate images from text using OpenAI in Flutter. Thanks for reading, and hope you like it. If you have any suggestions or queries about this article, please share your thoughts. You can read my other articles by clicking here.

Happy learning, friends!


Similar Articles