我需要使用数组imageData nodejs创建图像

时间:2017-02-28 15:36:10

标签: node.js

请我需要帮助,我有一个imageData数组,例如: 23, 0,
54, 255, .... r,g,b,a

我需要创建一个图像

我的代码是:

var sobel = require("sobel");
var Canvas = require("canvas");
var Image = Canvas.Image;
var canvas = new Canvas();
var image = new Image();
var ctx = canvas.getContext("2d");
var chunk = require("chunk");
var fs = require("fs");
image.src = "../test.jpg";
// console.log(image);
var width = image.width;
var height = image.height;
//
canvas.width = width;
canvas.height = height;
ctx.drawImage(image, 0, 0);

var imageData = ctx.getImageData(0, 0, width, height);
// Sobel constructor returns an Uint8ClampedArray with sobel data

var sobelData = sobel(imageData);
// [sobelData].toImageData() returns a new ImageData object

var sobelImageData = sobelData.toImageData();

//show sobel data 0,0,0,255  r,g,b,a
console.log(sobelData);

var final_image = chunk(sobelData, 4);
console.log(final_image);
//create buffer
var buffer = new Buffer(final_image);//create buffer with array sobeData
//show buffer
console.log(buffer);
//try to convert in a image
fs.writeFile("sobel.jpg", buffer, function(err) {
  if (err) {
    console.log(err);

  } else {
    console.log("logrado :D");
  }
});

感谢您的帮助,如果有人知道我能做什么,请告诉我

1 个答案:

答案 0 :(得分:1)

我使用了pngjs lib,代码就是这个。

var sobel = require("sobel");
var Canvas = require("canvas");
var ImageSobel = Canvas.Image;
var canvas = new Canvas();
var PNG = require("pngjs").PNG;



var imgs = new ImageSobel();


var ctx = canvas.getContext("2d");
var chunk = require("chunk");

var fs = require("fs");


imgs.src = "./output.jpg";
// console.log(image);
var width = imgs.width;
var height = imgs.height;
var newfile = new PNG({width: width, height: height});

canvas.width = width;
canvas.height = height;
ctx.drawImage(imgs, 0, 0);

var imageData = ctx.getImageData(0, 0, width, height);
// console.log(imageData);
var sobelData = sobel(imageData);
// console.log(sobelData);
var final_image = chunk(sobelData, 4);

var sobelImageData = sobelData.toImageData();
for (var y = 0; y < newfile.height; y++) {
  for (var x = 0; x < newfile.width; x++) {
    var idx = (newfile.width * y + x) << 2;

    var col =
        x < (newfile.width >> 1) ^ y < (newfile.height >> 1) ? 0xe5 : 0xff;

    newfile.data[idx] = sobelData[idx];
    newfile.data[idx + 1] = sobelData[idx + 1];
    newfile.data[idx + 2] = sobelData[idx + 2];
    newfile.data[idx + 3] = sobelData[idx + 3];
  }
}

newfile.pack()
    .pipe(fs.createWriteStream("sobel.png"))
    .on("finish", function(err) {
      if (!err) {
        console.log("logrado :D");
      }
    });