This article shows how to generate a web request in VB.NET to OpenAI imaging model Dall-E-2, as an alternative to web-based and NodeJS and Python solutions.
Introduction
The code send a request in JSON format to OpenAI image generation endpoint, composing a standard request to generate 1 single image using the Dall-E-2 model and standard quality size 512x512; the response in JSON format is deserialized, and the image URL is extracted and shown in a Picturebox
Using the code
The code is composed of a single long procedure that manages sending the request and getting the response; two minor procedures enable to manage the prompt textbox and to save the image to a local disk.
The code makes use of the following imports:
Imports System.Net
Imports System.IO
Imports System.Configuration
Imports System.Security.Cryptography
Imports System.Net.SecurityProtocolType
Imports System.Threading.Tasks
Imports System.ComponentModel
The dedicated form contains:
- a textbox for the prompt
- a textbox for the OpenAI API Key
- a pictureBox to show the image url
- a button to send the request
- a button to save the image
- a textbox showing the activity log (a sort of console)
The btnSend_Click
event triggers all the magic!
The first operation is to set up the request and JSONify it:
logTxt.Text = "Sending request..." & vbCrLf
System.Net.ServicePointManager.SecurityProtocol = DirectCast(3072, System.Net.SecurityProtocolType)
Dim apiEndpoint As String = "https://api.openai.com/v1/images/generations"
Dim apiKey As String = ApiKeyTextBox.Text
Dim prompt As String = PromptTextBox.Text
Dim model As String = "dall-e-2"
Dim numberofimages As String = "1"
Dim imagesize As String = "512x512"
Dim request As HttpWebRequest = WebRequest.Create(apiEndpoint)
request.Method = "POST"
request.ContentType = "application/json"
request.Headers.Add("Authorization", "Bearer " & apiKey)
Dim data As String = "{"
data += " ""model"": """ & model & ""","
data += " ""prompt"": """ & prompt & ""","
data += " ""n"": 1,"
data += " ""size"": """ & imagesize & """"
data += "}"
logTxt.Text += "Request grammar: " & data.ToString & vbCrLf
Using streamWriter As New StreamWriter(request.GetRequestStream())
streamWriter.Write(data)
End Using
The second step is to gather the response and deserialize it.
Dim response As HttpWebResponse = Nothing
Try
response = CType(request.GetResponse(), HttpWebResponse)
Dim responseStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(responseStream)
Dim jsonResponse As String = reader.ReadToEnd()
logTxt.Text += "Receiving response..." & vbCrLf
reader.Close()
responseStream.Close()
Dim oJavaScriptSerializer As New System.Web.Script.Serialization.JavaScriptSerializer
Dim oJson As Hashtable = oJavaScriptSerializer.Deserialize(Of Hashtable)(jsonResponse)
logTxt.Text += "Response received: " & jsonResponse.ToString & vbCrLf
Once done, we can intercept the image url and show it in the PictureBox
:
Dim imageUrl As String = oJson("data")(0)("url").ToString()
Dim imageClient As New WebClient()
Dim imageData As Byte() = imageClient.DownloadData(imageUrl)
Using ms As New MemoryStream(imageData)
PictureBox1.Image = Image.FromStream(ms)
End Using
saveBtn.Visible = True
There is some simple error handling to be done:
Catch ex As WebException
MessageBox.Show("Web error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
If response IsNot Nothing Then
response.Close()
End If
End Try
For the sake of completeness, here is reported the routine to save the image to a local disc:
If PictureBox1.Image IsNot Nothing Then
Dim saveDialog As New SaveFileDialog()
saveDialog.Filter = "JPG Image|*.jpg"
saveDialog.Title = "Save Image"
If saveDialog.ShowDialog() = DialogResult.OK Then
PictureBox1.Image.Save(saveDialog.FileName, Imaging.ImageFormat.Jpeg)
MessageBox.Show("Imge saved correctly!", "Save Image", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Else
MessageBox.Show("Image could not be saved.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Points of Interest
The major interest in the code is to interrogate OpenAI API via VB.NET without having to depend on Python or NodeJS, the two main technologies used in this kind of operations and the only 2 supported by OpenAI in their documentation.
VB.NET still allows desktop developers to interact with modern technologies, especially without depending on 3rd-parties libraries.
History
Version 1.0 - May 13th 2024