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
You cannot show a blob in
img
tag directly. You have to convert it to an object url first:note: I am not sure but you may get a warning or error from NextJS saying that you have to use
img
instead ofImage
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 useimg
tag without any problemIn general, you should prefer using your API route directly in an
<img src="…">
instead of usingfetch
to download the image and then handling the resultingBlob
.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: