0

I want to load an image from some url like https://example.com/picture1.png.

Then, I want to figure out:

  • The image's width (which I can)
  • The image's height (which I can)
  • The image's keccak256 hash (which I can)
  • The image's IPFS CID (which I can't)

I'm trying to do it with ipfs-mini.

My code:

const axios = require("axios");
const Web3 = require("web3");
const IPFS = require('ipfs-mini');
const sizeOf = require('image-size');

const web3 = new Web3();
const ipfs = new IPFS({ host: 'ipfs.infura.io', port: 5001, protocol: 'https' });

const loadAndHashImage = async (_url) => {
    const response = await axios.get(_url,  { responseType: 'arraybuffer' });
    const buffer = Buffer.from(response.data, "utf-8");

    const dimensions = sizeOf(buffer);
    console.log("Image Width:", dimensions.width)
    console.log("Image Height:", dimensions.height)

    const imageIpfsCid = await ipfs.add(buffer);
    console.log("Image IPFS CID:", imageIpfsCid); // is different for some reason

    const imageHash = web3.utils.keccak256(buffer);
    console.log("Image Hash:", imageHash);

    const urlIpfsCid = _url.substring(21)
    console.log("NEEDS TO BE TRUE:", imageIpfsCid === urlIpfsCid)
}

loadAndHashImage("https://ipfs.io/ipfs/QmSsYRx3LpDAb1GZQm7zZ1AuHZjfbPkD6J7s9r41xu1mf8");

(Right now, I'm passing in a IPFS url because it allows me to know beforehand what IPFS CID I should be getting in the imageIpfsCid variable.)

Currently, imageIpfsCid is different from the original passed in CID, which means something is wrong.

If I go to imageIpfsCid, instead of viewing an image, my computer automatically starts downloading a file, which makes me suspect that I'm not actually adding the image to IPFS, but it's data.

However, I can't seem to figure out how to fix this.

Once it's fixed, the passed in CID and imageIpfsCid should be a match.

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • I don't know about ipfs-mini, but js-ipfs this is as easy as adding `onlyHash` to `add`: https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md#ipfsadddata-options – Discordian Jun 12 '21 at 17:15
  • Reading over this again, the issue is the different CIDs? Could they be different versions? Would you mind sharing what "invalid CID" you're getting? BTW this resource might be useful: https://cid.ipfs.io/ – Discordian Jul 09 '21 at 01:57
  • Also perhaps of use: https://github.com/alanshaw/ipfs-only-hash – Discordian Jul 09 '21 at 02:01

0 Answers0