Featured image of post Create a front-end webpage for an image generator with Cloudflare Workers and Cloudflare AI.

Create a front-end webpage for an image generator with Cloudflare Workers and Cloudflare AI.

๐Ÿ“Œ Introduction

Create a front-end webpage for an image generator using Cloudflare Workers and Cloudflare AI.

ๅœจ Cloudflare worker ๅปบ็ซ‹ๅœ–็‰‡็”ข็”Ÿๅ™จ็š„ๅ‰็ซฏ็ถฒ้ ใ€‚

๐Ÿ“ Steps

  1. Log in to the Cloudflare dashboard and select your account.
  2. Select Workers & Pages > Create application.
  3. In Start from a template Select Text to Image > Deploy.
  4. Select Edit code.
  5. Replace all the original content in the text editor and paste the following code.
  6. Select Deploy.
const html = `<html class=is-large><meta charset=UTF-8><meta content="width=device-width,initial-scale=1,shrink-to-fit=no"name=viewport><title>image generator</title><link href=https://cdnjs.cloudflare.com/ajax/libs/tocas/4.2.5/tocas.min.css rel=stylesheet><script src=https://cdnjs.cloudflare.com/ajax/libs/tocas/4.2.5/tocas.min.js></script><link href=https://fonts.googleapis.com rel=preconnect><link href=https://fonts.gstatic.com rel=preconnect crossorigin><link href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@400;500;700&display=swap"rel=stylesheet><script src=https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js></script><div class="is-fliud ts-container"><div class="has-flex-center has-full-size"><div class=ts-segment><div class="is-vertical ts-wrap"><div class="is-label ts-text">Key word</div><div class=ts-input><input></div><button class="is-fluid ts-button"onclick=main()>Submit</button><div class="step-2 ts-box"style=display:none><div class="is-centered ts-loading"></div><div class=ts-image><img></div></div><button class="is-fluid ts-button step-2"onclick=save() style=display:none>Save image</button></div></div></div></div><script>var url;
function main() {
    if (document.querySelector('.ts-input input').value === '') {
        alert('text is requirement.');
        return;
    }
    document.querySelectorAll('.step-2')[0].style.display = 'block';
    document.querySelectorAll('.step-2')[1].style.display = 'block';
    
    document.querySelector('.ts-input').classList.add('is-disabled');
    
    fetch('/api/image.php?keyword=' + document.querySelector('.ts-input input').value)
        .then(response => response.blob())
        .then(blob => {
            document.querySelector('.ts-loading').style.display = 'none';
            
            url = URL.createObjectURL(blob);
            document.querySelector('.ts-image img').src = url;
        });
}

function save() {
    saveAs(url, 'image.png');
}</script>`;

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    if (url.pathname != "/api/image.php") {
      return new Response(html, {
        headers: {
          "content-type": "text/html;charset=UTF-8",
        },
      });
    }

    const ai = new Ai(env.AI);

    const inputs = {
      prompt: url.searchParams.get('keyword')
    };

    const response = await ai.run(
      '@cf/stabilityai/stable-diffusion-xl-base-1.0',
      inputs
    );

    return new Response(response, {
      status: 200,
      headers: {
        'content-type': 'image/png'
      }
    });
  }
};

๐Ÿ“– Ref.

https://developers.cloudflare.com/workers/get-started/guide/

ย