简体   繁体   English

使用Node.js和GraphicsMagick将四个图像拼接在一起

[英]Tile four images together using Node.js and GraphicsMagick

I have four 256x256 px images: a.jpg, b.jpg, c.jpg and d.jpg. 我有四张256x256像素:a.jpg,b.jpg,c.jpg和d.jpg。 I would like to merge them together to produce 2x2 mosaic image. 我想将它们合并在一起以产生2x2马赛克图像。 The resulting image should be also 256x256 px. 生成的图像也应为256x256像素。

Like this: 像这样:

+---+---+
| a | b |
+---+---+
| c | d |
+---+---+

Using plain GraphicsMagick and command line this can be done with 使用普通的GraphicsMagick和命令行可以完成

gm convert -background black \
    -page +0+0      a.jpg \
    -page +256+0    b.jpg \
    -page +0+256    c.jpg \
    -page +256+256  d.jpg \
    -minify \
    -mosaic output.jpg

But the problem is, how to do this using GraphicsMagick within Node.js ? 但问题是,如何在Node.js中使用GraphicsMagick来做到这一点?

gm('a.jpg')
    .append('b.jpg')
    .append('c.jpg')
    .append('d.jpg')
    .write('output.jpg', function (err) {})
// Produces 1x4 mosaic with dimensions 256x1024 px, not what I wanted

Found the solution! 找到了解决方案! It seems that the public API of gm does not provide any proper methods for what I needed. 似乎gm的公共API没有为我需要的东西提供任何适当的方法。 The solution was to use not-so-public .in method which makes possible to insert custom GraphicsMagick arguments. 解决方案是使用不那么公开的.in方法,这样就可以插入自定义的GraphicsMagick参数。

The following code takes in four 256x256 images, merges them to 2x2 grid on 512x512 canvas, halves the size to 256x256 using fast linear interpolation and saves the result to output.jpg. 下面的代码包含四个256x256图像,在512x512画布上将它们合并为2x2网格,使用快速线性插值将大小减半为256x256,并将结果保存到output.jpg。

var gm = require('gm');

// a b c d  ->  ab
//              cd
gm()
    .in('-page', '+0+0')  // Custom place for each of the images
    .in('a.jpg')
    .in('-page', '+256+0')
    .in('b.jpg')
    .in('-page', '+0+256')
    .in('c.jpg')
    .in('-page', '+256+256')
    .in('d.jpg')
    .minify()  // Halves the size, 512x512 -> 256x256
    .mosaic()  // Merges the images as a matrix
    .write('output.jpg', function (err) {
        if (err) console.log(err);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM