Guest User

Bad Code Coding Challenge #49 - Image from String of Colours

a guest
Nov 18th, 2020
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const readline = require('readline');
  2. const fs = require('fs');
  3. const express = require('express');
  4. const router = express();
  5. const { createCanvas } = require('canvas');
  6.  
  7. const pixelSize = 20;
  8.  
  9. var canvas;
  10. var context;
  11.  
  12. async function processLines() {
  13.     const fileStream = fs.createReadStream('input.txt');
  14.  
  15.     const rl = readline.createInterface({
  16.       input: fileStream,
  17.       crlfDelay: Infinity
  18.     });
  19.  
  20.     var lines = [];
  21.     var lineIndex = 0;
  22.  
  23.     for await (const line of rl) {
  24.         var colors = {};
  25.         colors.line = lineIndex;
  26.         colors.pixels = [];
  27.    
  28.         pixels = line.split("][");
  29.         for (i = 0; i < pixels.length; i++){
  30.             colors.pixels[i] = pixels[i].replace(/\[|\]/g, "").split(",");
  31.         }
  32.         lines.push(colors);
  33.         lineIndex++;
  34.     }
  35.  
  36.     var longestWidth = 0;
  37.     for (y = 0; y < lines.length; y++){
  38.         var pixels = lines[y].pixels;
  39.         if (pixels.length > longestWidth) longestWidth = pixels.length;
  40.     }
  41.  
  42.     canvas = createCanvas(longestWidth*pixelSize, lines.length*pixelSize);
  43.     context = canvas.getContext('2d');
  44.    
  45.     context.fillStyle = '#000';
  46.     context.fillRect(0, 0, longestWidth*pixelSize, lines.length*pixelSize);
  47.    
  48.     for (y = 0; y < lines.length; y++){
  49.         var line = lines[y];
  50.         for (x = 0; x < line.pixels.length; x++){
  51.             var pixel = line.pixels[x];
  52.             context.clearRect(x*pixelSize,y*pixelSize,pixelSize,pixelSize);
  53.             context.beginPath();
  54.             context.rect(x*pixelSize,y*pixelSize,pixelSize,pixelSize);
  55.             context.fillStyle = 'rgb(' + pixel[0] + ',' + pixel[1] + ',' + pixel[2] + ')';
  56.             context.fill();
  57.         }
  58.     }
  59.   }
  60.  
  61. processLines();
  62.  
  63. //The image will be available in the browser
  64. router.get('/', function (req, res, next) {
  65.     res.setHeader('Content-Type', 'image/png');
  66.     canvas.pngStream().pipe(res);
  67.   });
  68.  
  69. router.listen(80);
Advertisement
Add Comment
Please, Sign In to add comment