Example #1
0
 function bufferContents(file, enc, cb) {
   getPixels(file._contents, `image/${file.path.split('.').pop()}`, (err, pixels) => {
     if(err) {
       return console.log("Bad image path")
     }
     let dimensions    = pixels.shape.slice()
     let width         = dimensions[0]
     let height        = dimensions[1]
     let values        = pixels.data
     let valuesLength  = values.length
     if(!output){
       let objectName  = fileName.split('.')[0]
       let outputClass;
       if(fileName.split('.').pop().includes("png")){
         outputClass = DepthMap
       } else {
         outputClass = Mesh
       }
       output = new outputClass(valuesLength / 4, width, height)
     }
     for(let i=0; i<valuesLength; i+=4){
       let r = values[i]
       let g = values[i+1]
       let b = values[i+2]
       let v = Math.max(Math.max(r, g), b)
       let z = (v > 127) ? 1 : 0
       output[i / 4] += z
     }
     output.layers += 1
     cb()
   })    
 }
Example #2
0
//Créer un nouveau salon
function ctrlNewLobby(req, res) {
//@todo : rework de la fonction. Lobby().error si une erreur est survenue.
  if (req.file) {
    getPixels(req.file.buffer, req.file.mimetype, function(err, pixels) {
      if (err) {
        console.log("Error when trying to read image data : " + err);

        res.redirect("/");
      } else {
      //@todo : tester si l'image correspond à certains critères
      //@todo : ajouter un nombre max de lobby
        var lbid;

        do lbid = genLbid(); while (!!lobbies[lbid]);

        lobbies[lbid] = newServer(lbid, pixels);

        console.log("New lobby created - ID("+lbid+")");

        res.redirect("/"+lbid);
      }
    });
  } else {
    res.redirect("/");
  }
}
 image.pixelGetter = function(cb) {
   getPixels(image.file, 'image/png', function(err, pixels) {
     if (err) return cb(err, null);
     console.log('Crunching Pixels Baby! Yeah!');
     return cb(null, pixels);
   })
 };
 before(function (done) {
   var that = this;
   getPixels(__dirname + '/expected-files/' + filename, function (err, expectedPixels) {
     that.expectedPixels = expectedPixels;
     done(err);
   });
 });
Example #5
0
  return through.obj((file, enc, callback) => {
    getPixels(file.contents, mime.lookup(file.path), (err, pixels) => {
      if (err) {
        return callback(err);
      }

      let buffer;
      switch (colorDepth) {
        case '12bit':
          buffer = encodeTo12bit(pixels);
          break;
        case '8bit':
          buffer = encodeTo8bit(pixels);
          break;
        default:
          throw new Error('Encoding not supported');
      }

      const [nx, ny] = pixels.shape;
      if (verbose) {
        console.log(`Converted colors successfully at: ${colorDepth}`);
        console.log(`- Image size: ${nx}x${ny}`);
        console.log(`- File size: ${buffer.length / 1000}kb`);
      }

      return callback(null, new File({
        path: `${path.basename(file.path).slice(0, -path.extname(file.path).length)}.mwt`,
        contents: buffer,
      }));
    });
  });
Example #6
0
 var concatStream = concat(function handleFileBuffer (buff) {
   // https://github.com/scijs/get-pixels/blob/2e8766f62a9043d74a4b1047294a25fea5b2eacf/node-pixels.js#L179
   if (buff.length === 0) {
     return cb(new Error('Expected image "' + file.path + '" to not be empty but it was'));
   }
   getPixels(buff, mime.lookup(file.path), cb);
 });
Example #7
0
    .toFile(resizeImg, function(err) {

      if (err) {
        sendError(res, 'Image could not be resized', 500);
        return;
      }

      winston.info('[IMG] resized image to 16x16');
      getPixels(resizeImg, function(pixelsErr, pixels) {
        if (pixelsErr) {
          var message = 'Could not read pixel data from: ' + resizeImg;
          fs.unlinkSync(resizeImg);
          if (unlink === true) {
            fs.unlinkSync(newImgPath);
          }
          sendError(res, message, 500);
          return;
        }

        fs.unlinkSync(resizeImg);
        if (unlink === true) {
          fs.unlinkSync(newImgPath);
        }
        winston.info('[IMG] :  Readed Image to pixels');

        var data = parseImageData(pixels);

        sendDataOverMqttBus(data, res);
      });
    });
 getPixels(actualDir + 'sprite.basic.png', function handleActualPixels (err, actualImage) {
   if (err) { return done(err); }
   getPixels(expectedDir + 'pixelsmith.basic.png', function handleExpectedPixels (err, expectedImage) {
     if (err) { return done(err); }
     assert.deepEqual(actualImage, expectedImage, 'Actual image does not match expected image');
     done();
   });
 });
Example #9
0
 stream.on("finish", function() {
     getPixels("./test/output.png", function(err, pixels) {
         const res = decodePixels(err, pixels);
         res.success.should.be.true();
         res.text.should.equal("hello");
         done();
     });
 });
Example #10
0
function loadImage(image, cb){
	pixels(image, function(err, pix){
		if(err){
			return err;
		}
		return pix;
	});
}
Example #11
0
function processImage(imgPath) {
    getPixels(imgPath, function(err, pixels) {
        if (err) {
            throw err;
        }
        function getRGB(x, y) {
            return (pixels.get(x, y, 0) + pixels.get(x, y, 1) + pixels.get(x, y, 2)) / 3 | 0;
        }
        function dropY(x, maxY) {
            var y = 0;
            var points = [];
            for (; y < maxY; y++) {
                if (intBlack(getRGB(x, y))) {
                    points.push([x, y]);
                    return points;
                }
            }
            return points;
        }
        function dropX(y, maxX) {
            var x = 0;
            var points = [];
            for (; x < maxX; x++) {
                if (intBlack(getRGB(x, y))) {
                    points.push([x, y]);
                }
            }
            return points;
        }

        var width = pixels.shape[0];
        var height = pixels.shape[1];

        var black = [];

        for (var x = 0; x < width; x++) {
            joinPoints(black, dropY(x, height));
        }

        var topEdge = findTopEdge(removeOutliers(black, 80));

        black.forEach(function(xy) {
            var x = xy[0];
            var y = xy[1];
            setColour(pixels, x, y, {green: 255});
        });
        topEdge.points.forEach(function(xy) {
            var x = xy[0];
            var y = xy[1];
            setColour(pixels, x, y, {red: 255});
        });

        // var outImage = zeros([width, height, 4]);
        // imageRotate(outImage, pixels, -Math.atan(topEdge.equation[0]), 0, 0);

        savePixels(pixels, 'jpeg').pipe(tmp);
    });
}
Example #12
0
client.connect(1234, '100.123.2.16', function() {
  console.log('Connected');
  px = parseInt(Math.random()*cw)
  py = parseInt(Math.random()*ch)
  hr = 0
  hg = 0
  hb = 0

  getPixels("harkharkhark.png", function(err, pixels) {
    if(err) {
      console.log("Bad image path")
      return
    }
    console.log(pixels.shape)
    var iw = pixels.shape[0]
    var ih = pixels.shape[1]
    var ic = pixels.shape[2]

    setInterval(function(){

      for (var i=1; i<=ih; i++){
        for (var k=1; k<=iw; k++){
          var col = []
          var colHex = ''
          for (var o=0; o<ic; o++){
            // if (o===3) break
            col[o] = pixels.data[i*k+o]
            var hex = pixels.data[i*k+o].toString(16)
            if (hex.length === 1) hex = '0'+hex;
            colHex += hex
          }
          // console.log(colHex)
          
          var command = 'PX ' + (200 + k) + ' ' + (200 + i) + ' '+colHex+'\n';
          // console.log(command)
          client.write(command);

          // client.write('PX ' + (cw - x) + ' ' + (ch - y) + ' '+rr+rb+rg+'\n');
          // client.write('PX ' + x + ' ' + (ch - y) + ' '+rr+rb+rg+'\n');
          // client.write('PX ' + (cw - x) + ' ' + y + ' '+rr+rb+rg+'\n');

        }
      }
      // px = px + Math.round(1 - Math.random()*2)*squareSize*jumpFactor
      // py = py + Math.round(1 - Math.random()*2)*squareSize*jumpFactor
      // if (px > cw + squareSize) px = px - squareSize;
      // if (px < 0) px++;
      // if (py > ch + squareSize) py = py - squareSize;
      // if (py < 0) py++;
      // // console.log(command)
    }, 0.01)

    // console.log("got pixels", pixels.shape.slice())
    // console.log("got pixels", pixels)
  })

});
Example #13
0
 it("should decode correctly", function(done) {
     getPixels("./test/image.png", function(err, pixels) {
     //getPixels("http://datamatrix.kaywa.com/img.php?s=6&d=Hello%20DmCreator", function(err, pixels) {
         const res = decodePixels(err, pixels);
         res.success.should.be.true();
         res.text.should.equal("Hello DmCreator");
         done();
     });
 });
Example #14
0
/**
 * @desc Gets all pixels colors from an image and calculate the background color
 * @param {object} jobData - a job object with image data
 * @returns {object} - promise
 */
function getBgColorForImage(jobData) {
	var deferred = Q.defer(),
		imgSrc = jobData.image,
		imgPath = jobData.dir + imgSrc,
		bgColor,
		aggregatedColorsNo;

	logger.info('Getting image pixels for ' + imgSrc + '...');
	getPixels(imgPath, function (err, pixels) {
		if (err) {
			logger.error('Error while getting image pixels ' + JSON.stringify(err));
			//For transparent png get-pixels fails, so fall back to default color
			jobData.bgColor = defaultBgColor;
			deferred.resolve(jobData);
			return;
		}

		var dimensions = pixels.shape.slice(),
			imgWidth = dimensions[1],
			imgHeight = dimensions[0],
			i,
			sortedResults = [];

		// top & bottom borders
		for (i = 0; i < imgWidth; i++) {
			addAndCountColors(getColorObject(i, 0, pixels));
			addAndCountColors(getColorObject(i, imgHeight - 1, pixels));
		}

		// left & right borders
		for (i = 0; i < imgHeight; i++) {
			addAndCountColors(getColorObject(imgWidth - 1, i, pixels));
			addAndCountColors(getColorObject(0, i, pixels));
		}

		Object.keys(aggregatedColors).forEach(function (color) {
			sortedResults.push({
				color: color,
				count: aggregatedColors[color]
			});
		});

		aggregatedColors = sortedResults.sort(function (a, b) {
			return a.count - b.count;
		});

		aggregatedColorsNo = aggregatedColors.length;
		bgColor = aggregatedColors[aggregatedColorsNo - 1] ?
			aggregatedColors[aggregatedColorsNo - 1].color : defaultBgColor;
		jobData.bgColor = bgColor;
		logger.info('Background color found: ' + bgColor);
		deferred.resolve(jobData);
	});

	return deferred.promise;
}
module.exports = function colorPalette (buffer, type, count, callback) {
  getPixels(buffer, type, function (err, pixels) {
    if (err) return callback(err)
    const palette = getRgbaPalette(pixels.data, count).map(function (rgba) {
      return chroma(rgba)
    })

    return callback(null, palette)
  })
}
Example #16
0
	return new Promise(function(accept, reject){
		getPixels(imgPath, function(err, pixels) {
			if(err) {
				reject(err);
			}
			else{
				accept(pixels);
			}
		});
	});
Example #17
0
Image.load = function(url, type, callback){
  if(typeof type == 'function'){
    callback = type;
    type = null;
  }
  getPixels(url, type, function(err, pixels){
    if(err) return callback(err);
    callback(new Image(pixels));
  });
};
Example #18
0
function processImage(imgPath) {
    getPixels(imgPath, function(err, pixels) {
        if (err) {
            throw err;
        }
        function getRGB(x, y) {
            return (pixels.get(x, y, 0) + pixels.get(x, y, 1) + pixels.get(x, y, 2)) / 3 | 0;
        }
        function dropY(x, maxY) {
            var y = 0;
            for (; y < maxY; y++) {
                if (intBlack(getRGB(x, y))) {
                    return y;
                }
            }
            return -1;
        }
        function dropX(y, maxX) {
            var x = 0;
            for (; x < maxX; x++) {
                if (intBlack(getRGB(x, y))) {
                    return x;
                }
            }
            return -1;
        }

        var width = pixels.shape[0];
        var height = pixels.shape[1];

        var top = [];

        for (var x = 0; x < width; x++) {
            let y = dropY(x, height);
            if (y !== -1) {
                pixels.set(x, y, 0, 255);
                pixels.set(x, y, 1, 0);
                pixels.set(x, y, 2, 0);
                pixels.set(x, y, 3, 0);
            }
        }
        for (var y = 0; y < height; y++) {
            let x = dropX(y, width);
            if (x !== -1) {
                pixels.set(x, y, 0, 255);
                pixels.set(x, y, 1, 0);
                pixels.set(x, y, 2, 0);
                pixels.set(x, y, 3, 0);
            }
        }

        savePixels(pixels, 'jpeg').pipe(tmp);

    });
}
Example #19
0
 process.nextTick(function() {
   getPixels(filepath, function(err, data) {
     if(err) {
       t.assert(false, err)
       cb()
       return
     }
     
     var arrayWidth = array.shape.length <= 3 ? array.shape[0] : array.shape[1]
     var arrayHeight = array.shape.length <= 3 ? array.shape[1] : array.shape[2]
     var dataWidth = data.shape.length <= 3 ? data.shape[0] : data.shape[1]
     var dataHeight = data.shape.length <= 3 ? data.shape[1] : data.shape[2]
     t.equals(arrayWidth, dataWidth)
     t.equals(arrayHeight, dataHeight)
     
     if(array.shape.length === 2) {
       for(var i=0; i<array.shape[0]; ++i) {
         for(var j=0; j<array.shape[1]; ++j) {
           if(data.shape.length === 3) {
             t.equals(array.get(i,j), data.get(i,j,0))
           } else {
             t.equals(array.get(i,j), data.get(i,j))
           }
         }
       }
     } else if(array.shape.length === 3) {
       for(var i=0; i<array.shape[0]; ++i) {
         for(var j=0; j<array.shape[1]; ++j) {
           for(var k=0; k<array.shape[2]; ++k) {
             if(data.shape.length === 3) {
               t.equals(array.get(i,j,k), data.get(i,j,k))
             } else {
               t.equals(array.get(i,j,k), data.get(0,i,j,k))
             }
           }
         }
       }
     } else {
       for(var i=0; i<array.shape[0]; ++i) {
         for(var j=0; j<array.shape[1]; ++j) {
           for(var k=0; k<array.shape[2]; ++k) {
             for(var l=0; l<array.shape[3]; ++l) {
               t.equals(array.get(i,j,k,l), data.get(i,j,k,l))
             }
           }
         }
       }
     }
     if (!process.env.TEST_DEBUG) {
       fs.unlinkSync(filepath)
     }
     cb()
   })
 })
 it('generates an image', function (done) {
   // Load in the images and compare them
   getPixels(actualDir + 'sprite.basic.png', function handleActualPixels (err, actualImage) {
     if (err) { return done(err); }
     getPixels(expectedDir + 'pixelsmith.basic.png', function handleExpectedPixels (err, expectedImage) {
       if (err) { return done(err); }
       assert.deepEqual(actualImage, expectedImage, 'Actual image does not match expected image');
       done();
     });
   });
 });
Example #21
0
    window.onload = function() {
	var path = "images/DogBeach.jpg";

	read(path, function(err, nd_originalImage) {
	    if (err) {
		console.log("Bad image path");
		return;
	    }
	    onSuccessfullImageLoading(nd_originalImage);
	});

    };
Example #22
0
 return new Promise(function(resolve, reject) {
     getPixels(path, function(err, pixels) {
         if (err) {
             reject(new Error('could not read: ' + path));
         }
         try {
             resolve(from_pixels(pixels, opts));
         } catch (e) {
             reject(e);
         }
     });
 });
Example #23
0
	process : function (path, callback) {
		methods.log('process:', path);
		
		getPixels(path, function (error, pixels) {
			if (error) {
				methods.log('process: an error occurred.', error);
				if (typeof callback === 'function') callback(false);
			}
			
			methods.handlePixels(pixels, callback);
		});
	}
Example #24
0
    /**
     * Load an image for processing
     * @param input {string} path
     * @param callback {function} callback
     */
    loadAsync(input, callback){
        getPixels(input, (err, pixels) => {

            if(err) {
                throw("Bad image path");
            }

            //get ndarray as pixels
            this.pixVals = Utils.nd_to_pixVal(pixels);

            callback();
        });
    }
Example #25
0
getPixels(process.argv[2], function(error, image1) {
  if (error) {
    console.log(error);
    process.exit(1);
  }
  getPixels(process.argv[3], function(error, image2) {
    if (error) {
      console.log(error);
      process.exit(1);
    }
    compare(image1, image2);
  });
});
Example #26
0
function loadVoxels(href) {
  getPixels(href, function(err, voxels) {
    if(err || voxels.dimension !== 4) {
      loadVoxels("example/banana.gif")
      return
    }
    if(viewer) {
      viewer.dispose()
    }
    window.history.replaceState({}, 'Gif 3D', '?href=' + href)
    viewer = createVolumeRenderer(shell.gl, voxels.transpose(0, 2, 1))
  })
}
Example #27
0
module.exports = function (hero, opts, callback) {

    if (typeof opts === 'function') {
        callback = opts;
        opts = {};
    }

    opts.step = opts.step || 1;
    opts.trimTop = opts.trimTop || null;
    opts.trimBottom = opts.trimBottom || null;

    Object.keys(hero.colors).forEach(function (key) {
        if (hero.colors[key] == null) delete hero.colors[key];
    });

    var pallete = nearestColor.from(hero.colors);

    getPixels(hero.image, function (err, pixels) {
        if (err) return callback(err);

        if (opts.trimBottom) {
            opts.trimBottom = pixels.shape[1] - (opts.trimTop || 0) - opts.trimBottom;
        }

        pixels = pixels
            .lo(null, opts.trimTop)
            .hi(null, opts.trimBottom)
            .step(opts.step, opts.step);

        var width = pixels.shape[0];
        var height = pixels.shape[1];

        var colors = [];

        var i, j, k;
        for (j = 0; j < height; j++) {
            var row = [];
            for (i = 0; i < width; i++) {
                var r = pixels.get(i, j, 0);
                var g = pixels.get(i, j, 1);
                var b = pixels.get(i, j, 2);
                var a = pixels.get(i, j, 3);
                row.push(a === 0 ? null : pallete('#' + rgbHex(r, g, b)).name.replace(/([0-9]+)/, ''));
            }
            colors.push(row);
        }

        callback(null, colors);
    });
};
Example #28
0
    // The function which is called on every draw.
    function draw(input, callback, progressObj) {
        var getPixels = require('get-pixels');
        var savePixels = require('save-pixels');

        var step = this;

        getPixels(input.src, function(err, pixels) {

            if (err) {
                console.log("Bad Image path");
                return;
            }
            var width = 0;

            for (var i = 0; i < pixels.shape[0]; i++) width++;

            for (var i = 0; i < pixels.shape[0]; i++) {
                for (var j = 0; j < pixels.shape[1]; j++) {
                    let val = (i / width) * 255;
                    pixels.set(i, j, 0, val);
                    pixels.set(i, j, 1, val);
                    pixels.set(i, j, 2, val);
                    pixels.set(i, j, 3, 255);
                }
            }
            var chunks = [];
            var totalLength = 0;
            var r = savePixels(pixels, input.format, { quality: 100 });

            r.on("data", function(chunk) {
                totalLength += chunk.length;
                chunks.push(chunk);
            });

            r.on("end", function() {
                var data = Buffer.concat(chunks, totalLength).toString("base64");
                var datauri = "data:image/" + input.format + ";base64," + data;
                output(input.image, datauri, input.format);
                callback();
            });
        });

        function output(image, datauri, mimetype) {

            // This output is accessible by Image Sequencer
            step.output = { src: datauri, format: mimetype };

        }
    }
function convertBitmapToJSON(bitmapPath, callback) {
    getPixels(bitmapPath, function(err, pixels) {
        if (err) {
            console.log("Bad image path")
            return
        }

        // computer, enhance
        pixels.getPixel = function(x, y) {
            var pixel = {
                r: pixels.get(x, y, 0),
                g: pixels.get(x, y, 1),
                b: pixels.get(x, y, 2)
            };

            pixel.rgb = [pixel.r, pixel.g, pixel.b].join(',');

            return pixel;
        };

        var tilePixelMap = {};
        tileTypes.tiles.forEach((tile) => {
            tilePixelMap[tile.palette.code] = tile;
        });

        var shape = pixels.shape.slice();
        var width = shape[0];
        var height = shape[1];
        var map = [];
        for (var j = 0; j < width; j++) {
            var row = [];
            for (var i = 0; i < height; i++) {
                pixel = pixels.getPixel(i, j);
                row[i] = (tilePixelMap[pixel.rgb] || {}).symbol || '#';
            }
            map[j] = row.join(':');
        }

        var histogram = createHistogram(pixels);

        // console.log("Histogram", JSON.stringify(histogram, null, 2));

        (callback) ? callback({
            histogram,
            mapData: map
        }): null;
    });
}
Example #30
0
  // This function is called on every draw.
  function draw(input, callback, progressObj) {

    progressObj.stop(true);
    progressObj.overrideFlag = true;

    var step = this;

    // convert to runnable code:
    if (typeof options.func === "string") eval('options.func = ' + options.func);

    var getPixels = require('get-pixels');

    // save first image's pixels
    var priorStep = this.getStep(-2);

    getPixels(priorStep.output.src, function(err, pixels) {
      options.firstImagePixels = pixels;

      function changePixel(r2, g2, b2, a2, x, y) {
        // blend!
        var p = options.firstImagePixels;
        return options.func(
          r2, g2, b2, a2,
          p.get(x, y, 0),
          p.get(x, y, 1),
          p.get(x, y, 2),
          p.get(x, y, 3)
        )
      }

      function output(image, datauri, mimetype) {

        // This output is accessible by Image Sequencer
        step.output = { src: datauri, format: mimetype };

      }

      // run PixelManipulatin on second image's pixels
      return require('../_nomodule/PixelManipulation.js')(input, {
        output: output,
        changePixel: changePixel,
        format: input.format,
        image: options.image,
        inBrowser: options.inBrowser,
        callback: callback
      });
    });
  }