1

I am using canvas npm for create images, and trying to convert to readable stream and put it in a variable seems to corrupt.

This is how I save it:

    let fullStream;
    let stream = canvas.createPNGStream(null, { quality: 1 })      
    
    stream.on('data', (d) => {
      d = d.toString() 
      if (!fullStream) fullStream = d
      else fullStream = fullStream + d
    })

The question is, what am I doing wrong for corrupt, how to fix and how to save it in a variable.

The result of fullStream seems fine, but it is not.

Pedro.js
  • 21
  • 4

1 Answers1

0

createPNGStream is readable stream you just need to pipe the output to writable stream without handling the chunks

const fs = require('fs')
const { createCanvas, loadImage } = require('canvas')
// create canvas
const canvas = createCanvas(200, 200)
const ctx = canvas.getContext('2d')

ctx.font = '30px Impact'
ctx.rotate(0.1)
ctx.fillText('Awesome!', 50, 100)

const text = ctx.measureText('Awesome!')
ctx.strokeStyle = 'rgba(0,0,0,0.5)'
ctx.beginPath()
ctx.lineTo(50, 102)
ctx.lineTo(50 + text.width, 102)
ctx.stroke()
//save to png
const out = fs.createWriteStream(__dirname + '/test.png')
const stream = canvas.createPNGStream()
stream.pipe(out)
out.on('finish', () => console.log('The PNG file was created.'))
Naor Tedgi
  • 5,204
  • 3
  • 21
  • 48
  • The point is that I don't want to save it as a file, but I need it as a readable stream for send it via multipart request without need to read the file to get the readable stream. – Pedro.js Mar 08 '22 at 01:23
  • so just pass the stream object without piping it to WriteStream createPNGStream returning a readable stream – Naor Tedgi Mar 08 '22 at 06:43
  • What do you mean? By the way, this code you showed seems to have return invalid stream too. I've tried that using const ab = fs.createReadStream('./test.png') to read on out.on finish – Pedro.js Mar 09 '22 at 17:43