简体   繁体   中英

How to create an ipfs hash from an image source?

I have the src (data) of an image, that is not saved yet and doesn't have a path yet. I would like to know the future ipfs hash that will result from it once it is saved and sent to ipfs.

So far I have done this, but the hashes don't match.

import { saveAs } from 'file-saver';
const dagPB = require('ipld-dag-pb')
const UnixFS = require('ipfs-unixfs')

func = async () => {   
    let bgImage = await import(`./images/bg.png`);
    let bodyImage = await import(`./images/body.png`);
    let headImage = await import(`./images/head.png`);
    let eyesImage = await import(`./images/eye.png`);
    let mouthImage = await import(`./images/mouth.png`);
    let levelImage = await import(`./images/level.png`);

    src = await mergeImages([
      bgImage.default,
      bodyImage.default,
      headImage.default,
      eyesImage.default,
      mouthImage.default,
      levelImage.default,
    ]);
    
    image.src = src;
    saveAs(image.src, `photo.png`);
    const fileBuffer = Buffer.from(image.src)
    const file = new UnixFS('file', fileBuffer)

    dagPB.DAGNode.create(file.marshal(), (err, node) => {
     if(err) return console.error(err)
     console.log(node._cid.toBaseEncodedString())
    })
}

What is missing or wrong?

And here is what I did.

    const Hash = require('ipfs-only-hash')

    func = async () => {   
      let bgImage = await import(`./images/bg${ex}.png`);
      let bodyImage = await import(`./images/body${ex}.png`);
      let headImage = await import(`./images/head${ex}.png`);
      let eyesImage = await import(`./images/eye${ex}.png`);
      let mouthImage = await import(`./images/mouth${ex}.png`);
      let levelImage = await import(`./images/level${ex}.png`);

      src = await mergeImages([
        bgImage.default,
        bodyImage.default,
        headImage.default,
        eyesImage.default,
        mouthImage.default,
        levelImage.default,
      ]);

      const endOfPrefix = src.indexOf(",");
      const cleanStrData = src.slice(endOfPrefix+1);
      const imageData = Buffer.from(cleanStrData, "base64");
      const imageHash = await Hash.of(imageData);
      console.log("fetch data CID: " + imageHash)
      }

Remove the header of the data, to keep only the data and then hash it it with ipfs-hash-only. The image hash is then written in the.json and the same process is used to hash the.json and know before hand the metadata's ipfs address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM