Working with images in IPFS

Are there good examples of working with images and IPFS? A scenario I’m thinking about:

  1. Upload an image to IPFS.
  2. Show this image from IPFS on an HTML page.
  3. Make a preview of an uploaded image, so it could be loaded faster on UI.
  4. Anything special about gifs?

Images can take a data URL as a src, which you can create from a Blob, which you can create from a Uint8Array so you could do something like:

const toBuffer = require('it-to-buffer') // or it-concat for more performant BufferLists

const buffer = await toBuffer(
const blob = new Blob(buffer)

const myImage = document.querySelector('img')
myImage.src = URL.createObjectURL(blob)

One other option would be storing your images and other formats as “unixfs objects”. The nide thing about this is that if you view the content over a gateway, the gateway will do mime-type detection and enable serving the content via the gateway.

storing your images and other formats as “unixfs objects”

How to do this?

For go-ipfs you can use the ipfs add command. I dont personally use js-ipfs so I’m not 100% sure what the equivalent command would be, but it should be something like add, addFromFS and there may be one other one.

In the case of the js-ipfs-http-client package it’s instanceOfAPIClient.add, and insanceOfAPIClient.addFromFS

Yes, the equivalent here would be just:

const myImage = document.querySelector('img')
myImage.src = `${cid}`

But you’re not really getting any of the benefits of IPFS here as the image is being served over HTTP.

There’s also a caveat that the gateway is a shared public resource and not one that you should rely on to power your app, instead you should set up your own gateways.


Key point here! Thanx @achingbrain

I mean if you’re using a remote gateway sure, but you can always use a local gateway on your laptop or whatever. Gateways have their uses, locally, or publicly; A gateway isn’t an exclusively public resource unless you make it.

The API seems to have changed. Trying to apply this exact code to an svg stored on IPFS seems to corrupt the data, while retrieving from the gateway works fine.