本文介绍了在Node.js中使用gm调整大小并合成两个或更多图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个图像,例如在img(大小为1024x768)文件夹(img1.png和img2.png)下,我需要调整img2的大小(例如300x300),然后将img1放在x和y中(例如100、200)从img1的左上方开始.最终结果应为1024x768尺寸的图像.

Given two images, say under img (in size of 1024x768) folder (img1.png and img2.png), I need to resize img2 (say 300x300) and put on img1 in x and y (say 100, 200) from top left of img1. The end result should be 1024x768 size image.

使用gm( https://github.com/aheckmann/gm )进行了以下尝试:

Using gm (https://github.com/aheckmann/gm), tried this:

gm('./img/img1.png')
.composite('./img/img2.png')
.geometry('300x300+100+200')
.write('resultGM.png', (err) => {
  if (err) console.log(err);
});

预期(由于整个操作过程中的连锁)会产生300x300的图像.然后我尝试了这个:

Expectedly (because of chain on whole operation) it produces 300x300 image.Then I tried this:

gm('./img/img1.png')
.composite(
  gm('./img/img2.png')
  .geometry('300x300+100+200')
)
.write('resultGM.png', (err) => {
  if (err) console.log(err);
});

希望复合函数接受缓冲区,但没有机会,它仅接受文件路径,并给出错误.在花费2-3个小时并阅读了几篇文章之后(只能在此处找到一些讨论:,并在此处:(实际上这没有回答问题),我找不到任何解决方案可以使用流或缓冲区在内存中执行此操作.可以在写入临时文件时执行此操作.是否有任何机构可以找到内存调整大小和动态合并图像的解决方案?

hoping composite function accepts buffer, but no chance, it only accepts file path, and it gives error. After spending 2-3 hours and reading few posts (only could find some discussions here: How to do composite with gm node.js? and here: Combine two gm objects while resizing one of them in graphicsMagick for NodeJS (this one doesn't answer the question in fact), I couldn't find any solution to do this operation in memory using streams or buffer. It's possible to do while writing to a temporary file. Is there any body out there who could find a solution for in memory resize and merge images on the fly?

推荐答案

使用ImageMagick代替GraphicMagic;

Using ImageMagick instead of GraphicMagic;

经过几个小时的搜索,我终于找到了如何使用gm合并两个调整大小的图像并重新排序图层位置(上方,下方等)的方法.

After a few hours of searching finally i have figured out how to merge two images resizing and re-ordering layer positions (over, under, etc.) using gm.

让我们先看一下这张图片:

Let's have a look this image first:

几分钟后,打开ImageMagick的撰写帮助页面,我看到了DstOver定位的用法.

After a few minutes digging up ImageMagick's compose help page, i saw the usage of DstOver positioning.

http://www.imagemagick.org/Usage/compose/#dstover

因此,我在下面尝试了此代码,它的工作原理很吸引人!

So, i have tried this code below and it worked like a charm!

imageMagick(background)
    .composite(image)
    .in('-compose', 'Dst_Over')
    .in('-geometry', '253x253+15+15')
    .write(output, function (err) {
    if (err) console.error(err);
        else console.log('Compose OK!');
    });

这篇关于在Node.js中使用gm调整大小并合成两个或更多图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 07:33