Skip to content

How to query the API from a web browser and display the image with an IMG element

The API returns images as raw binary PNG files. There's no extra-layer of JSON or Base64 decoding needed.

If you want to display the results with an <img> element, all you have to do, is to make sure to fetch the response as a Blob, and wrap it with URL.createObjectURL() before setting the image element src property.

Here's a full simple example to get you started:

<html>
    <head>
        <script type="text/javascript">

            async function generateImage() {

                var prompt = document.getElementById("prompt").value;

                const encodedParams = new URLSearchParams();
                encodedParams.append("prompt", prompt);

                const options = {
                    method: 'POST',
                    headers: {
                        'content-type': 'application/x-www-form-urlencoded',
                        'X-Dezgo-Key': 'YOUR_API_KEY_HERE'
                    },
                    body: encodedParams
                };

                var response = await fetch('https://api.dezgo.com/text2image', options)
                var pngBlob = await response.blob();    

                console.log("Got the image as a blob:", pngBlob)

                document.getElementById("my-image").src = URL.createObjectURL(pngBlob);
            }

        </script>
    </head>
    <body>
        <input type="text" id="prompt" /> <button onclick="generateImage()">Generate</button>
        <hr>
        <img id="my-image" />
    </body>
</html>