What is the best way to display an image/jpeg blob retrieved from an API call on screen using NextJS?

When using Next.js, I make an API call like this:

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

This triggers the following function:

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


export default async function generate (req, res) {

  try{
  const inference = new HfInference('[token]');
  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 output indicates that the response is:

Blob { size: 93803, type: 'image/jpeg' }

This confirms that it's a blob object.

I'm facing an obstacle trying to display this image on the screen. I attempted to use URL.createObjectURL but encountered an error. Any suggestions?

Answer №1

To display a blob in an img tag, you must first convert it to an object URL:

const imageUrl = useMemo(() => URL.createObjectURL(blob), [blob]);

<Image src={imageUrl} />

Please note: There is a possibility of receiving a warning or error from NextJS instructing you to use the img tag instead of the Image component as the real image source is not being used and cannot be optimized by NextJS. If this occurs, feel free to switch back to using the img tag without any issues.

Answer №2

It is generally recommended to directly use your API route within an <img src="…"> tag instead of utilizing the fetch function to fetch the image and then processing the resulting Blob.

Handling a fetch response on your own can be slower and consume more memory, and if your goal is simply to show the image, there is no need to complicate the process unnecessarily.

The solution should be straightforward:

<img src="/api/generateimageXY6">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to pass the "$user" variable in a loadable file using ajax?

Is there a way to send the variable user to the mLoad.php file before executing this script? Any suggestions would be greatly appreciated. Thank you! $(document).ready(function(){ $("#message_area").load('mLoad.php'); $("#userArea").submit(func ...

The performance of Three.js is directly influenced by the quantity of objects present

Just completed a project in WebGL using Javascript and the 3D library known as three.js Unfortunately, the performance of the project is less than impressive - slow from the start with occasional moments of adequacy. In this game, there are: 1 car, 6 ora ...

Build error occurred due to the presence of the following error: Module parse failed with an unexpected character ''' (1:0)

I am facing an issue regarding an unexpected character in a node module file. Below is the content of my next.config.js file: /** * @type {import('next').NextConfig} */ const UglifyJsPlugin = require("uglifyjs-webpack-p ...

Submitting forms from a different router in React can pose a unique challenge

As a beginner in React, I am working on creating a simple meal app. In my App component, I am fetching meal data from an api and allowing users to click on a meal for more details. However, I am facing an issue where searching for a new meal on the detail ...

Setting up routes in VueJS and NodeJS Express for API integration: a comprehensive guide

My API routes always return HTML instead of JSON, despite trying numerous solutions that have all failed. Here is my current setup: // app.js const express = require("express"); const app = express(); const history = require("connect-history-api-fallback ...

The mystery of why gulp-watch fails to remove files

I need help figuring out why my gulp-watch task isn't deleting files from the /dest directory when I delete them from /src. Can someone spot the issue? var watch = require('gulp-watch'); var imagemin = require('gulp-imagemin'); ...

Creating a Future Prediction Graph with ECharts

I am looking to create a forecast chart that includes both Actual values (presented as a line chart) and projected values (displayed as a dotted chart). An example of what I have in mind can be seen here, created using Excel: https://i.sstatic.net/q18An.pn ...

Is it possible to simultaneously play several one-shot sound effects on mobile web browsers?

I'm attempting to trigger a sound effect when the user clicks a button on my web application. Initially, I experimented with this approach: var sound = new Audio("soundeffect.ogg"); function clickHandler(){ sound.play(); } Unfortunately, if the ...

Encountering a "Token Error: Bad Request" when attempting to call the callback URL

Every time I try to invoke the callback URL with google-OAuth2, I encounter the following error: Error Traceback: TokenError: Bad Request at Strategy.OAuth2Strategy.parseErrorResponse (G:\projects\oauth\node_modules\passport-oauth ...

Angular Custom Pipe - Grouping by Substrings of Strings

In my Angular project, I developed a custom pipe that allows for grouping an array of objects based on a specific property: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'groupBy'}) export class GroupByPipe impleme ...

Experiencing prolonged delays with PHP/AJAX login process

Recently, I took over the maintenance of a website that requires users to log in. However, I've noticed that the login process is quite slow, especially when there are around 4000 registered users. The current login system utilizes a combination of A ...

What is the best way to incorporate React Odometerjs into a Next.js project?

It's quite disheartening that despite spending 3 days trying, I still can't seem to successfully integrate Odometer js into my Next js project. I'm at a loss as to where I might be going wrong in my code. Here is the code I've been work ...

Creating functions within the $scope that do not directly access the $scope object

tag, I am looking to create a $scope function that specifically manipulates the variables it receives. To test this functionality, I have set up a Plunker available at http://plnkr.co/edit/BCo9aH?p=preview. In my setup, there is an ng-repeat loop that lis ...

I am eager to create a Material-UI textfield using an array

My current task involves utilizing TextField based on an Array, but I am facing an issue with dynamically changing all the values. I understand that I can employ ternary conditions to accomplish this task effectively. const TextField = () => { r ...

Exploring the Methods to Monitor Variables in Framework7 Store

Currently, I am in the process of developing my app and have opted to utilize the new built-in store system instead of relying on Vuex. I have a variable that undergoes frequent changes and previously used the following code when working with Vuex: store.w ...

What is the best way to utilize Protractor to comb through a specific class, locate a p tag within that class, and validate certain text within it?

My current task involves using Protractor to locate a specific class and then search through all the p tags within that class to identify any containing the text "Glennville, GA". In my spec file, I have attempted the following steps: it('should fil ...

Having trouble with a beginner problem that's hindering the functionality of my code

I have been struggling with a particular piece of code and it is driving me crazy as I am unable to locate the source of my error: $.post($form.attr('action'), $form.serialize(), function (result) { console.log(result); if (result.succes ...

Importing models in SceneJS does not function properly with Internet Explorer

I've been exploring different webGL frameworks lately. While I like SceneJS, I've noticed some compatibility issues with Internet Explorer. For instance, in IE 11, importing OBJ files seems to cause the online examples to freeze up: Check out th ...

Error: Trying to access the 'blogpost' property of an undefined variable results in a TypeError while executing the NPM RUN BUILD command in Next.js

Encountering a frustrating issue while trying to run my Next.js application for production build. The problem seems to be related to the "blogpost" parameter in the following codeblock: import React from "react"; import Slab from "../../comp ...

Open the HTML page from a separate directory

I'm facing an issue with loading additional HTML onto a page in my project when a link is clicked. The HTML fragment file I want to load is stored in a different folder within the project structure. Despite my efforts, I keep encountering a 404 error ...