我想将image1像素的一半替换为image2像素的前一半
var bodyParser = require('body-parser'),
express = require('express');
var app = express();
var image1 = "./img1.jpg";
var image2 = "./img2.jpg";
app.get("/",function(req,res){
});
app.listen(process.env.PORT || 3000, function() {
console.log('server is runing');
});
有没有办法遍历并获取image1像素并将其替换?
答案 0 :(得分:0)
假定两个图像的大小相同。您可以使用PureImage来实现。通过利用drawImage
,您可以控制要将图像绘制到其他图像上的位置。 drawImage
的工作方式与html5-canvas相同,并且可以最好地满足您的要求,因为您可以剪切图像并将该图像部分放置到另一图像的任何区域上。
此示例创建并返回一个新图像,其中包含image2
的上半部分和image1
的下半部分:
let bodyParser = require('body-parser'),
express = require('express'),
PImage = require('pureimage'),
fs = require('fs'),
app = express();
let image1 = "./img1.jpg";
let image2 = "./img2.jpg";
app.get("/", (req,res) => {
PImage.decodeJPEGFromStream(fs.createReadStream(image1)).then((image1) => {
// create newImage based on the size of image1
let newImage = PImage.make(image1.width,image1.height);
// get drawing context of newImage
let c = newImage.getContext('2d');
// 1. draw image1 on the whole canvas 1:1
c.drawImage(image1,
0, 0, image1.width, image1.height
);
PImage.decodeJPEGFromStream(fs.createReadStream(image2)).then((image2) => {
// 2. draw only upper half of image2 onto newImage
c.drawImage(image2,
0, 0, image2.width, image2.height/2, // get only upper half of image2 -> sourceX, sourceY, sourceWidth, sourceHeight
0, 0, newImage.width, newImage.height/2 // draw upper half of image2 onto upper half of newImage -> destinationX, destinationY, destinationWidth, destinationHeight
);
// 3. save newImage on filesystem and return it to client afterwards
let pth = __dirname+"/newImage.jpg";
PImage.encodeJPEGToStream(newImage,fs.createWriteStream(pth)).then(() => {
console.log("done writing");
res.sendFile(pth);
});
});
});
});
app.listen(process.env.PORT || 3000, () => console.log('server is runing'));