skip to Main Content

In nextjs, I do the following API call:

const response = await fetch('/api/generateimageHG2');

this call the following function:

import { HfInference } from "@huggingface/inference";


export default async function generate (req, res) {

  try{
  const inference = new HfInference('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');
  const response = await inference.textToImage({
      model: "stabilityai/stable-diffusion-2",
      inputs: "award winning high resolution photo of a giant dragon/((ladybird)) hybrid, [trending on artstation]",
      parameters: {
          negative_prompt: "blurry",
      },
  });
  
  console.log (response);  
   

    res.status(200).send(response);
  } catch (error) {
    throw new Error('Error fetching property information: ' + error.message);
  } 
  
};

The console log prints the following:

Blob { size: 93803, type: ‘image/jpeg’ }

So I know I’m getting a blob.

I’m really stuck in turning this blob into an image on the screen. I tried URL.CreateObjectURL, but that causes an error.

Anyone has any ideas?

2

Answers


  1. You cannot show a blob in img tag directly. You have to convert it to an object url first:

    const src = useMemo(() => URL.createObjectURL(blob), [blob]);
    
    <Image src={src} />
    

    note: I am not sure but you may get a warning or error from NextJS saying that you have to use img instead of Image in this case. the reason might be that we are not using the real source of the image and NextJS cannot optimize it. If that happened, that’s totally okay. you can use img tag without any problem

    Login or Signup to reply.
  2. In general, you should prefer using your API route directly in an <img src="…"> instead of using fetch to download the image and then handling the resulting Blob.

    Dealing with a fetch response yourself is slower and memory-inefficient, and if you just want to display the image, there’s no reason to overcomplicate things.

    It should be as simple as:

    <img src="/api/generateimageHG2">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search