4

My function returns a blob object when I log it in my console:

Blob(623853) {name: "profile.jpg", size: 623853, type: "image/jpeg"}

I want to display this image to the user with JavaScript, how can I do it?

AmericanUmlaut
  • 2,729
  • 2
  • 15
  • 26
Mehmet Ali Peker
  • 601
  • 6
  • 17
  • you can probably create an img element on the page, and make the src attribute the image path. That should display the image. But you'll need the full path, not sure if 'profile.jpg' is enough. Also see this answer as it has more details: https://stackoverflow.com/questions/7650587/using-javascript-to-display-blob – duxfox-- Aug 08 '18 at 21:41
  • ı don't know full path of image, image is creating with js using canvas, and convert to blob – Mehmet Ali Peker Aug 08 '18 at 21:43
  • Possible duplicate of [Using Javascript to Display Blob](https://stackoverflow.com/questions/7650587/using-javascript-to-display-blob) – TJBlackman Aug 08 '18 at 21:48

1 Answers1

10

You can use URL.createObjectURL to generate a blob URL and set it as the image source.

const blobUrl = URL.createObjectURL(blob) // blob is the Blob object
image.src = blobUrl // image is the image element from the DOM
Arun Kumar Mohan
  • 9,934
  • 3
  • 16
  • 37
  • I get: errorReporting: unhandledrejection: TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed. – YTG Apr 19 '21 at 07:22
  • @YTG The argument passed to the [URL.createObjectURL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) method should be a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob), [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File), or [`MediaSource`](https://developer.mozilla.org/en-US/docs/Web/API/MediaSource). Can you share your code? – Arun Kumar Mohan Apr 19 '21 at 07:42