Friday, July 19, 2024

Blogger Script for Text to Image generator tool

 

AI Image Generator sample script

Script for Text to Image generator tool


Free Text to Image generator tool can be created in Blogger with nice user interface to engage application users and generate AI image from text effectively to their desired result. Different selectable options can be given to choose Style for example, Realistic, Cartoon, Abstract etc. They can choose Color Preset for example, Vibrant, Monochrome, Pastel etc. Different frame options can be given for resulting generated image for example, Simple, Ornate etc. Lighting can be another attribute which can improvise the generated image and options to support that can be like Natural, Dramatic, Soft as needed. Similar to these image attributes, few others can also added to enhance the AI image generated based on the user prompt which is captured as part of idea description entered by the user.

Preview image placeholder and generated image placeholder can be managed and worked with same component. On selection of user values, the tool can update the image based on the selected style, color, frame, and lighting options. Images involved in the preview or generation can be named according to the pattern for example, style_color_frame_lighting.jpg and placed in the images directory or accessible via the specified path. As an example in sample script below, event listeners can be used to update the image when any form field changes based on user input.

Generate Image functionality initiates once the "Generate Image" button is clicked, the form submits the user entered values and the generated image can be displayed based on the filled description and selected options. The main tricky part here is usage of API services that accept JSON input and return a URL to the generated image. First we can see the consolidated sample script with JavaScript, HTML and CSS for blogger as mentioned below, using DeepAI API with dummy API KEY syntax .

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>AI Image Generator</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            background-color: #f4f4f4;

            margin: 0;

            padding: 0;

        }

        .container {

            background-color: #fff;

            padding: 20px;

            border-radius: 8px;

            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

            max-width: 600px;

            margin: 20px auto;

        }

        h1, h2 {

            text-align: center;

        }

        form {

            display: flex;

            flex-direction: column;

        }

        label {

            margin-top: 10px;

        }

        textarea, select, button {

            margin-top: 5px;

            padding: 10px;

            border-radius: 5px;

            border: 1px solid #ddd;

        }

        button {

            background-color: #007bff;

            color: white;

            cursor: pointer;

            transition: background-color 0.3s ease;

        }

        button:hover {

            background-color: #0056b3;

        }

        #output {

            margin-top: 20px;

            text-align: center;

        }

        #imagePlaceholder {

            max-width: 100%;

            height: auto;

            border-radius: 8px;

            border: 1px solid #ddd;

            margin-top: 10px;

        }

    </style>

</head>

<body>

    <div class="container">

        <h1>AI Image Generator</h1>

        <form id="imageForm">

            <label for="idea">Describe your idea:</label>

            <textarea id="idea" name="idea" rows="4" required></textarea>

            <label for="style">Choose a style:</label>

            <select id="style" name="style">

                <option value="realistic">Realistic</option>

                <option value="cartoon">Cartoon</option>

                <option value="abstract">Abstract</option>

                <!-- Add more styles as needed -->

            </select>

            <label for="color">Choose a color preset:</label>

            <select id="color" name="color">

                <option value="vibrant">Vibrant</option>

                <option value="monochrome">Monochrome</option>

                <option value="pastel">Pastel</option>

                <!-- Add more color presets as needed -->

            </select>

            <label for="frame">Choose a frame:</label>

            <select id="frame" name="frame">

                <option value="none" selected>None</option>

                <option value="simple">Simple</option>

                <option value="ornate">Ornate</option>

                <!-- Add more frame options as needed -->

            </select>         

            <label for="lighting">Choose lighting:</label>

            <select id="lighting" name="lighting">

                <option value="natural">Natural</option>

                <option value="dramatic">Dramatic</option>

                <option value="soft">Soft</option>

                <!-- Add more lighting options as needed -->

            </select>             

            <button type="submit">Generate Image</button>

        </form>         

        <div id="output">

            <h2>Generated Image:</h2>        

            <img id="imagePlaceholder" src="images/default_sample.jpg" alt="Image Preview">

        </div>

    </div> 

    <script>

        const ideaInput = document.getElementById('idea');

        const styleSelect = document.getElementById('style');

        const colorSelect = document.getElementById('color');

        const frameSelect = document.getElementById('frame');

        const lightingSelect = document.getElementById('lighting');

        const imagePlaceholder = document.getElementById('imagePlaceholder');

        const updateSampleImage = () => {

            const style = styleSelect.value;

            const color = colorSelect.value;

            const frame = frameSelect.value;

            const lighting = lightingSelect.value;

            imagePlaceholder.src = `images/${style}_${color}_${frame}_${lighting}.jpg`;

        };

        ideaInput.addEventListener('input', updateSampleImage);

        styleSelect.addEventListener('change', updateSampleImage);

        colorSelect.addEventListener('change', updateSampleImage);

        frameSelect.addEventListener('change', updateSampleImage);

        lightingSelect.addEventListener('change', updateSampleImage);

        document.getElementById('imageForm').addEventListener('submit', function(event) {

            event.preventDefault();

            const idea = ideaInput.value;

            const style = styleSelect.value;

            const color = colorSelect.value;

            const frame = frameSelect.value;

            const lighting = lightingSelect.value;

            generateImage(idea, style, color, frame, lighting);

        });

        function generateImage(idea, style, color, frame, lighting) {

            const apiKey = 'YOUR_DEEPAI_API_KEY';

            fetch('https://api.deepai.org/api/text2img', {

                method: 'POST',

                headers: {

                    'Content-Type': 'application/json',

                    'Api-Key': apiKey

                },

                body: JSON.stringify({

                    text: idea

                })

            })

            .then(response => response.json())

            .then(data => {

                const imageUrl = data.output_url;

                imagePlaceholder.src = imageUrl;

            })

            .catch(error => console.error('Error:', error));

        }

        // Initialize sample image on page load

        updateSampleImage();

    </script>

</body>

</html>

 


As mentioned earlier, there are several out-of-the-box API services that accept JSON input and return a URL to the generated image. DeepAI API, we already covered in above sample script, here are a few other popular ones: 

1. OpenAI DALL-E API

OpenAI's DALL-E, a powerful model for generating images from textual descriptions, it's API can be used to send a description and receive a generated image. JavaScript part will have slight change as follows:

const apiKey = 'YOUR_OPENAI_API_KEY'; 

fetch('https://api.openai.com/v1/images/generations', {

    method: 'POST',

    headers: {

        'Content-Type': 'application/json',

        'Authorization': `Bearer ${apiKey}`

    },

    body: JSON.stringify({

        prompt: idea,

        n: 1,

        size: '1024x1024'

    })

})

.then(response => response.json())

.then(data => {

    const imageUrl = data.data[0].url;

    document.getElementById('generatedImage').src = imageUrl;

})

.catch(error => console.error('Error:', error));

 


2. Replicate API

Replicate API, can also be used as it offers various models for image generation, including DALL-E, Stable Diffusion, and others. For Replicate API, sample script have few changes as:

const apiKey = 'YOUR_REPLICATE_API_KEY'; 

fetch('https://api.replicate.com/v1/predictions', {

    method: 'POST',

    headers: {

        'Content-Type': 'application/json',

        'Authorization': `Token ${apiKey}`

    },

    body: JSON.stringify({

        version: 'MODEL_VERSION_ID', // Replace with the specific model version you want to use

        input: {

            prompt: idea,

            style: style,

            color: color,

            frame: frame,

            lighting: lighting

        }

    })

})

.then(response => response.json())

.then(data => {

    const imageUrl = data.urls.get; // The URL to get the generated image

    document.getElementById('generatedImage').src = imageUrl;

})

.catch(error => console.error('Error:', error));

 


3. Stable Diffusion via Stability AI API

Now, Stability AI provides access to the Stable Diffusion model, which is again, a great option for generating high-quality images. It's sample JavaScript part can minor changes as compared to other options as follows:

const apiKey = 'YOUR_STABILITY_API_KEY'; 

fetch('https://api.stability.ai/v2/generation/stable-diffusion-v1-4/text-to-image', {

    method: 'POST',

    headers: {

        'Content-Type': 'application/json',

        'Authorization': `Bearer ${apiKey}`

    },

    body: JSON.stringify({

        text_prompts: [{text: idea}],

        cfg_scale: 7.5,

        width: 512,

        height: 512,

        samples: 1,

        sampler: 'k_lms'

    })

})

.then(response => response.json())

.then(data => {

    const imageUrl = data.artifacts[0].url;

    document.getElementById('generatedImage').src = imageUrl;

})

.catch(error => console.error('Error:', error));

  


Using These TEXT to IMAGE API Services in Your Application

Simply, we need to replace the placeholder values (like YOUR_OPENAI_API_KEY, YOUR_DEEPAI_API_KEY, etc.) with the actual API keys and model version IDs. Mandatory part is that you may need to sign up for these TEXT to IMAGE API Services and obtain API keys to access them.


No comments:

Post a Comment

Popular Posts