Giter Site home page Giter Site logo

merge-images's Introduction

merge-images

Easily compose images together without messing around with canvas

Build Status Coverage Status npm npm GitHub Donate Bitcoin Donate Lightning Donate

Canvas can be kind of a pain to work with sometimes, especially if you just need a canvas context to do something relatively simple like merge some images together. merge-images abstracts away all the repetitive tasks into one simple function call.

Images can be overlaid on top of each other and repositioned. The function returns a Promise which resolves to a base64 data URI. Supports both the browser and Node.js.

Install

npm install --save merge-images

or for quick testing:

<script src="https://unpkg.com/merge-images"></script>

Usage

With the following images:

/body.png /eyes.png /mouth.png

You can do:

import mergeImages from 'merge-images';

mergeImages(['/body.png', '/eyes.png', '/mouth.png'])
  .then(b64 => document.querySelector('img').src = b64);
  // data:image/png;base64,iVBORw0KGgoAA...

And that would update the img element to show this image:

Positioning

Those source png images were already the right dimensions to be overlaid on top of each other. You can also supply an array of objects with x/y co-ords to manually position each image:

mergeImages([
  { src: 'body.png', x: 0, y: 0 },
  { src: 'eyes.png', x: 32, y: 0 },
  { src: 'mouth.png', x: 16, y: 0 }
])
  .then(b64 => ...);
  // data:image/png;base64,iVBORw0KGgoAA...

Using the same source images as above would output this:

Opacity

The opacity can also be tweaked on each image.

mergeImages([
  { src: 'body.png' },
  { src: 'eyes.png', opacity: 0.7 },
  { src: 'mouth.png', opacity: 0.3 }
])
  .then(b64 => ...);
  // data:image/png;base64,iVBORw0KGgoAA...

Dimensions

By default the new image dimensions will be set to the width of the widest source image and the height of the tallest source image. You can manually specify your own dimensions in the options object:

mergeImages(['/body.png', '/eyes.png', '/mouth.png'], {
  width: 128,
  height: 128
})
  .then(b64 => ...);
  // data:image/png;base64,iVBORw0KGgoAA...

Which will look like this:

Node.js Usage

Usage in Node.js is the same, however you'll need to also require node-canvas and pass it in via the options object.

const mergeImages = require('merge-images');
const { Canvas, Image } = require('canvas');

mergeImages(['./body.png', './eyes.png', './mouth.png'], {
  Canvas: Canvas,
  Image: Image
})
  .then(b64 => ...);
  // data:image/png;base64,iVBORw0KGgoAA...

One thing to note is that you need to provide a valid image source for the node-canvas Image rather than a DOM Image. Notice the above example uses a file path, not a relative URL like the other examples. Check the node-canvas docs for more information on valid Image sources.

API

mergeImages(images, [options])

Returns a Promise which resolves to a base64 data URI

images

Type: array
Default: []

Array of valid image sources for new Image().
Alternatively an array of objects with x/y co-ords and src property with a valid image source.

options

Type: object

options.format

Type: string
Default: 'image/png'

A DOMString indicating the image format.

options.quality

Type: number
Default: 0.92

A number between 0 and 1 indicating image quality if the requested format is image/jpeg or image/webp.

options.width

Type: number
Default: undefined

The width in pixels the rendered image should be. Defaults to the width of the widest source image.

options.height

Type: number
Default: undefined

The height in pixels the rendered image should be. Defaults to the height of the tallest source image.

options.Canvas

Type: Canvas
Default: undefined

Canvas implementation to be used to allow usage outside of the browser. e.g Node.js with node-canvas.

options.crossOrigin

Type: string
Default: undefined

The crossOrigin attribute that Image instances should use. e.g Anonymous to support CORS-enabled images.

License

MIT Β© Luke Childs

merge-images's People

Contributors

greenkeeper[bot] avatar lukechilds avatar tjenkinson avatar trevorblades avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

merge-images's Issues

test failure in local machine

Hi @lukechilds ! Thanks to your awesome merge-images package.

I forked and clone to my local machine and install dependencies and I run the test I got two failure test:

unit β€Ί mergeImages encodes jpeg format

  /Users/.../merge-images/test/unit.js:32

   31:
   32:     t.true(b64 === expectedB64);
   33:   });

  Value is not `true`:

  false

  b64 === expectedB64
  => false

  expectedB64
  => 'data:image/jpeg;base64,...
unit β€Ί mergeImages uses custom jpeg quality

  /Users/.../merge-images/test/unit.js:88

   87:
   88:   t.true(b64 === expectedB64);
   89: });

  Value is not `true`:

  false

  b64 === expectedB64
  => false

  expectedB64
  => 'data:image/jpeg;base64,...

I made images by the output encode data and try again test, I pass tests. Here is my PR, but its failure on Travis CI.

This is my environment:

OS: macOS 10.13.6
node: v9.8.0
npm: 5.6.0

Thanks! Have a good day.

Using non data urls when running in node

Thanks for this handy little library.

When running in node using node-canvas I'm wanting the result of the merge to be a buffer or a stream rather than a base64 encoded string. I think it would be possible to do this with an outputType option? The rules would be

  • If not provided defaults to dataURL
  • If running in browser, only dataURL is a permitted output type
  • Options include: dataURL, buffer, stream
  • If stream then based the canvas stream method is used based on mime type
    • image/png -> createPNGStream
    • image/jpeg -> createJPEGStream
    • application/pdf -> createPDFStream
    • else error

I'm happy to help with this feature, if it will be accepted/merged. πŸ˜„

How to resize image(s) width and height instead of cropping it

mergeImages([
  {src: 'xxxx'}, 
  {src: 'xxxxx'}, 
  {src: 'xxxxxx'}
  ], {crossOrigin: "Anonymous", width: 2550, height: 3300})
.then( b64 => {
  download(b64, "map.png");
});

I want to resize the image instead of cropping it. The first two images have the same size but the last one is the largest. I want to have them all in the same size for a proper position. The current width and height APIs crop from sides instead of resizing.

not working in pure js code

hello

i use this script but not worked for me

i work in pc local and i don't use any server and i use chrome browser

i have error : Uncaught SyntaxError: Cannot use import statement outside a module

`<script src="jquery-3.2.1.min.js"> </script>

<script src="https://unpkg.com/merge-images"></script>

<script> import mergeImages from 'merge-images'; mergeImages(['/body.png', '/eyes.png', '/mouth.png']) .then(b64 => document.querySelector('img').src = b64); // data:image/png;base64,iVBORw0KGgoAA... </script> `

Use existing elements rather than URL

Great script! I have images that are generated from SVG, not external URLs - so I have img elements I'd like to use with this - I tried converting your script to one that could use existing elements, without much luck. Do you have any tips?

thanks again!
Stacey

Not working nodejs

I have created the node app and here is my API

app.get('/',function(req,res){
mergeImages(['./public/images/T_4.gif','./public/images/e2.jpg'], {
Canvas: Canvas
})
.then((b64) => { console.log("hi")});
})

  1. After running the App , the function mergeImages is called and invoking indexjs in the back ground , but i am getting window is undefined in indexjs i.e
    var canvas = options.Canvas ? new options.Canvas() : window.document.createElement('canvas');

2.So i removed that line and set var canvas = options.Canvas now i am getting
error at var ctx = canvas[0].getContext('2d'); i.e getContext function is undefined.

Is this an issue with nodejs or this module is used only for client side scripting ? Please help me to fix the issue.

Thanks

Internet Explorer Possible Unhandled Promise Rejection: Error: Couldn't load image

Hello,
I downloaded the promise polyfill bookstore which fixed the problem of Promise is not defined, but this generated another error that Object does not support the assign method. I also fixed this, but now I have the error "Possible Unhandled Promise Rejection: Error: Couldn't load image".
It works in Firefox, Chrome but not in IE. I have been searching and it is related to the loading of base 64 images in IE. Any way to counter this problem?

Combine b64?

Hi Luke, thanks for a great lib!
This is more a question than an issue so feel free to close it right away:
I was wondering if this would allow me to combine two data URI into 1?

The use case being a drawing / animation application where I need to combine each animation frame's different layers into one frame.

/Nicolas

Merging images into a gif

Hi, has anyone bumped in the case where you need to merge multiple images, some of them are gif and would like the output result to be a gif?

Currently I'm getting a static image even though I specified the format to be image/gif

Thanks.

/

/

Request: Example for output into a image file

Hi!

Kinda noob in node/JS in general here, i'm trying to make a shitpostbot-like script, can you point me how can i merge two images (lets say two images from sources/ folder) into another file (eg final/output.png)?

I read the readme and from what i understand it return a base64 object, but i dont know how write the result in a image file.

Thanks in advance!

An in-range update of rollup-plugin-buble is breaking the build 🚨

The devDependency rollup-plugin-buble was updated from 0.19.6 to 0.19.8.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

rollup-plugin-buble is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 1 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

CORS issue

I am trying to merge two images from my firebase storage. I allowed cors on my bucket, but when trying to merge it I get:
Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

I'm not sure if I understand correctly, but shouldn't images from my firebase storage bucket be from the same domain?
Not sure why I get this error

Adding background to merged image

I need to merge several transparent images and then add a color background based on user selected hex code. Is it possible to do that somehow?

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Can I resize the each image one by one?

Hi thanks for your wonderful library.
I have a question of resizing images.

Can I resize the each image one by one like 'image1' below?

mergeImages([
      {src: image1, width: 421, height: 421},
      {src: image2}
])
.then(...)

Thank you a lot!

Image positioning not working?

I'm having trouble with positioning my images in a resulting stitched image:

const mergeImages = require('merge-images');
const { Canvas, Image } = require('canvas');

imgList =
[
  './assets/dice/d4b.png',
  './assets/dice/d5b.png',
  './assets/dice/d3r.png' 
]
//all these images are 67x67

mergeImages(
    imgList,
    { Canvas: Canvas, 
      Image: Image, 
      width: 201,
      height: 201
    },
    { src: imgList[0], x: 0, y: 0 },
    { src: imgList[1], x: 67, y: 67 },
    { src: imgList[2], x: 134, y: 134 }
)
    .then((img) => console.log(img));

I would understand that when I paste the resulting base64, I would get a 201x201 square, with the three images aligned diagonally, top to bottom, left to right, but all I'm getting is a white 201x201 square with only d3r.png (so the last applied image) in the top left.

image compression

I'm trying to merge two images from their base64, each one with around 1.6 mb but I'm getting a merged image with 160 kb. Is there anyway to reduce image compression?

An in-range update of rollup is breaking the build 🚨

Version 0.54.1 of rollup was just published.

Branch Build failing 🚨
Dependency rollup
Current Version 0.54.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

rollup is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ coverage/coveralls Coverage pending from Coveralls.io Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 4 commits.

  • 4bd7a0a 0.54.1
  • 77e3b44 Update changelog
  • 74de841 Merge pull request #1871 from KingHenne/more-ts-fixes
  • b413df4 Fix two more ts compiler errors based on emitted d.ts files

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Internet Explorer Promise is not Defined

Hello,
Sorry for my ignorance, but does your "merge-images" also work in Internet Explorer?
I'm asking this because I'm having the error(Promise is not defined) when merging the images.

var arrayImages = [];
      for (var i = 0; i < boundsheight; i += imgHeight) {
        for (var j = 0; j < boundswidth; j += imgWidth) {
          img = myDiagram.makeImage({
            scale: 1,
            background: "white",
            position: new go.Point(p.x + j, p.y + i),
            size: new go.Size(imgWidth, imgHeight),
            type: "image/png"
          });
          arrayImages.push({src:img.src,x:p.x + j,y:p.y + i});
        }
      }
      console.log(arrayImages);
      mergeImages(arrayImages).then(function(b64){ document.querySelector('img').src = b64});

window is not defined

Hey,
Can't figure out why i got this

image

my code is just

const mergeImages = require("merge-images");

mergeImages(...); // of course i didn't wrote ... but you understood ^^

Use with react native

Is it possible for this to work out of the box with react native? I have tried using both react native canvas as well as node canvas but both seem to have its share of issues. Is support for react native likely to be added in the future?

Discord.js trying to merge images throws an error

I'm trying to merge an image from a dir and a user's avatar the dir is right but i get error

(node:6028) UnhandledPromiseRejectionWarning: Error: Couldn't load image
    at img.onerror (C:\Users\aoshe\OneDrive\Desktop\amogus\node_modules\merge-images\dist\index.umd.js:39:46)
    at setSource (C:\Users\aoshe\OneDrive\Desktop\amogus\node_modules\canvas\lib\image.js:91:13)
    at Image.set (C:\Users\aoshe\OneDrive\Desktop\amogus\node_modules\canvas\lib\image.js:62:9)
    at C:\Users\aoshe\OneDrive\Desktop\amogus\node_modules\merge-images\dist\index.umd.js:41:12
    at new Promise (<anonymous>)
    at C:\Users\aoshe\OneDrive\Desktop\amogus\node_modules\merge-images\dist\index.umd.js:30:55
    at Array.map (<anonymous>)
    at C:\Users\aoshe\OneDrive\Desktop\amogus\node_modules\merge-images\dist\index.umd.js:30:24
    at new Promise (<anonymous>)
    at mergeImages (C:\Users\aoshe\OneDrive\Desktop\amogus\node_modules\merge-images\dist\index.umd.js:22:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:6028) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:6028) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

the code:

const mergeImages = require('merge-images')
const { Canvas, Image } = require('canvas');

module.exports = {
    name: 'avatar',
    description: 'avatar',
    async execute(message, args) {
        var url;

        mergeImages(['../../assets/colors/yellow.png', message.author.displayAvatarURL()], {
            Canvas: Canvas,
            Image: Image
          }).then(b64 => url = b64);
          

        message.reply(url);
    }
}

Provide a way to rotate images

Thanks for writing such an easy to use tool to merge images! It would be very useful if there was a way to rotate the input images.

Canvas node not working

I have a code which it seems the same as your example page

const mergeImages = require('merge-images');
const Canvas = require('canvas');

const sendMerged = function(email) {
    mergeImages(['../public/logo.png', '../public/710fb.png'], {
      Canvas: Canvas
    })
    .then //....

But I get the error

TypeError: options.Canvas is not a constructor
    at /Users/xxx/GIT/projects/abc/node_modules/merge-images/dist/index.umd.js:25:32

If I console log Canvas I have the following

{ Canvas: { [Function: Canvas] _registerFont: [Function: _registerFont] },
  Context2d: [Function: CanvasRenderingContext2D],
  CanvasRenderingContext2D: [Function: CanvasRenderingContext2D],
  CanvasGradient: [Function: CanvasGradient],
  CanvasPattern: [Function: CanvasPattern],
  Image: { [Function: Image] MODE_IMAGE: 1, MODE_MIME: 2 },
  ImageData: [Function: ImageData],
  //...
}

So I tried to change the code above to

//...
const Canvas = require('canvas').Canvas; //This is against the canvas documentation example
//...

After this change it seems to be fine with the constructor but it fails the line after with

TypeError: Image is not a constructor
    at /Users/xxx/GIT/projects/abc/node_modules/merge-images/dist/index.umd.js:39:13

I wonder if it's a bug with the new version of a dependency (I noticed you don't pin them).
Do your test run a new npm install? is this functionality tested?
Thanks a lot

Optional image crossOrigin="anonymous";

Please give an option to set crossOrigin attribute for the source images.

This is solve the problem while converting canvas to b64
"Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported."

Test broken

Saw drqwerty coming up with a nice rotate option PR #84 , but it doesn't seem to merge properly. Any updates on that? Should be a problem with canvas installation. Thanks

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1

Should be a problem with .travis.yml

question using html? works somewhat on chrome, not at all on safari...

Hi, sorry to bother... I need to display images I produce in julia from tiles and this library seemed great but I am not fluent in javascript. in chrome I get an image but they seem to be overlaid. on safari I get tainted canvas error.... Do you have any suggestion for making this work?:

<script src="https://unpkg.com/merge-images"></script> <script> mergeImages([ { src: 'https://tile.openstreetmap.org/7/63/42.png', x: 0, y: 0 }, { src: 'https://tile.openstreetmap.org/7/64/42.png', x: 256, y: 0 }, { src: 'https://tile.openstreetmap.org/7/64/43.png', x: 254, y: 256 }, { src: 'https://tile.openstreetmap.org/7/63/43.png', x: 0, y: 256 } ]) .then(b64 => document.querySelector('img').src = b64); </script>

I'm using merge-images in a discord bot so it is throwing an error on node js

UnhandledPromiseRejectionWarning: Error: Couldn't load image
    at img.onerror (~/Desktop/Discord/node_modules/merge-images/dist/index.umd.js:39:46)
    at setSource (~/Desktop/Discord/node_modules/canvas/lib/image.js:91:13)
    at ~/Desktop/Discord/node_modules/canvas/lib/image.js:59:11
    at ~/Desktop/Discord/node_modules/simple-get/index.js:89:7
    at IncomingMessage.<anonymous> (/Users/mac-guy/Desktop/Discord/node_modules/simple-concat/index.js:7:13)
    at Object.onceWrapper (events.js:421:28)
    at IncomingMessage.emit (events.js:327:22)
    at IncomingMessage.EventEmitter.emit (domain.js:485:12)
    at endReadableNT (_stream_readable.js:1224:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:70029) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:70029) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I have installed Canvas node module but I'm still getting this error. Here's the code:

const mergeImages = require('merge-images');
const { Canvas, Image } = require('canvas');
const { Client, MessageAttachment } = require('discord.js');
const Bot = new Client();

const BOT_TOKEN = "token";

Bot.login(BOT_TOKEN);

Bot.on(
    'ready', () => 
    {
        console.log("Bot is now online!");
    }
);

Bot.on(
    'message', message =>
    {
        if (message.content == "!avatar")
        {
            var url;

            mergeImages(['https://imgur.com/GGo99Gz.png', message.author.displayAvatarURL()], {
                Canvas: Canvas,
                Image: Image
              }).then(b64 => url = b64);
              

            message.reply(url);
        }
    }
);
  
Bot.login(BOT_TOKEN);

I actually want to send the image but that's irrelevant to this issue so I just tested by sending the message and it's throwing that error before it so what could be the issue?

An in-range update of coveralls is breaking the build 🚨

The devDependency coveralls was updated from 3.0.3 to 3.0.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

coveralls is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 5 commits.

  • 8ac4325 version bump
  • 9d9c227 Bump extend from 3.0.1 to 3.0.2 (#226)
  • 33119a7 Bump js-yaml from 3.11.0 to 3.13.1 (#225)
  • f5549c7 Bump handlebars from 4.1.0 to 4.1.2 (#224)
  • 4df732b Style fix (#211)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of rollup is breaking the build 🚨

Version 0.59.3 of rollup was just published.

Branch Build failing 🚨
Dependency rollup
Current Version 0.59.2
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

rollup is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 3 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Is calling mergeImages inside Google Maps ImageMapType getTileUrl possible?

This is definitely not a bug, but I'd like to understand if this library somehow could be used in this scenario?
The code below does not work, but rather gives the error
GET http://localhost:3000/[object%20Promise] 404 (Not Found)

`_addOverLay: function () {
this.overlayLayer = new google.maps.ImageMapType({
getTileUrl: function (tile, zoom) {
return mergeImages(['/a.png', '/b.png']).then(b64 => {
return b64
})
},
tileSize: new google.maps.Size(256, 256)
});

    this.gMap.overlayMapTypes.insertAt(0, this.overlayLayer);
},`

a.png and b.png are just examples here, they will later be dynamically assigned so moving the mergeImages call outside of getTileUrl is not an option for me. I've tried the same using async/await with the same outcome. I'm guessing getTileUrl can't handle an async call inside it, or am I doing something clearly wrong with the promise?

Update @types

Seems that @types/merge-images are slightly outdated (default export e.g.). Wouldn't it make more sense to port them into merge-images directly to keep them updated or rewrite the code to TypeScript then rollup can take care of that using the TypeScript compiler option.

TypeError: options.Canvas is not a constructor

I am running node, and am attempting to merge two images with this code:

const mergeImages = require('merge-images');
const Canvas = require('canvas');

mergeImages(["img1.png", "img2.png"],
     {
        Canvas: Canvas
      })
      .then(b64 => function()
      {
      //Do stuff
      });

However, the above gives an error:

(node:19271) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: options.Canvas is not a constructor

I saw this, but after changing my code to const Canvas = require('canvas').Canvas;, like was suggested, I got another error:
TypeError: Image is not a constructor
Like was suggested in the issue above, I tried downgrading to canvas 1.6.13, but that resulted in:
ReferenceError: window is not defined

Not sure if it's me, merge-images. or canvas that's causing the issue.

getting "window is not defined" error with nodejs.

Getting "ReferenceError: window is not defined" when using with nodejs. Below given is my approach.

var mergeImages = require("merge-images");

mergeImages([
 { src: image1.buffer },
 { src: image2.buffer }
]).then(b64 => {
 console.log(b64);
});

How can I fit Images with the 2nd image frame?

Having issues with 1st parameter image. If the image is wider than 2nd image it's not fitting well.
How can I solve that?
I tried mergeImages([{ src: '../test.jpeg', width: 635, height: 700 },{ src: '../frame-1.png', x: 0, y: 0 }],{width: 635, height: 1125})

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.