How to ipfs.dag.get the image in browser

I want to use ipds.dag.get to get an image and display it in an img tag.
The following code is breaking the image, what is wrong?

if(!ipfs) return
let cid = CID.parse("QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE")
let data = await ipfs.dag.get(cid);
// console.log(JSON.stringify(data,null,2))
let blob = new Blob([data.value.Data], { type: "image/png" })
console.log(data.value.Data)
console.log(blob)
const img = document.getElementById( 'img' );
let url = window.URL.createObjectURL(blob)
img.src = url

Images can be found at the gateway.

スクリーンショット 2023-02-04 17.25.25

I’m using ipfs-core version
ipfs-core": "version": "0.18.0"

I ran the following code to confirm.

async function addFile () {
  const { cid } = await ipfs.add('こんにちは')
  console.log(cid.toString())
} 
addFile()

CID is QmcZFY95TMnf57CuVaVPUaPyLiSsCWdacSxrLZYywqLDQS

Next, i run the following code

let cid = CID.parse("QmcZFY95TMnf57CuVaVPUaPyLiSsCWdacSxrLZYywqLDQS")
let data = await ipfs.dag.get(cid);
let blob = new Blob([data.value.Data], { type: "image/png" })
let reader = new FileReader();
reader.onload = () => e.innerText = this.replaceControlCharacters(reader.result, "")
fr.readAsText(blob, "UTF-8");

reader.result contained control codes.
[BS][STX][DC2][STX]
And i found the similar in the image data.I don’t know what this is… or is the code wrong?
Can someone please help me…

This there any reason you’re using ipfs.dag.get for this? ipfs.dag.get gets a DAG node, if you want to display an image, the easiest way to do that would likely be through ipfs.cat:

/** Uses `URL.createObjectURL` free returned ObjectURL with `URL.RevokeObjectURL` when done with it.
 * 
 * @param {string} cid CID you want to retrieve
 * @param {string} mime mimetype of image
 * @param {number} limit size limit of image in bytes
 * @returns ObjectURL
 */
async function loadImgURL(cid, mime, limit) {
    if (cid == "" || cid == null || cid == undefined) {
        return;
    }
    const content = [];
    for await (const chunk of ipfs.cat(cid, {length:limit})) {
        content.push(chunk);
    }
    return URL.createObjectURL(new Blob(content, {type: mime}));
}

I hope this helps.

1 Like

I was missunderstanding DAG API.
Your code worked, thank you!!

1 Like