'Saving canvas readable stream from createPNGStream into a variable
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.
Solution 1:[1]
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.'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Naor Tedgi |
