Created
September 30, 2019 15:26
-
-
Save salekh/ff93b39b580137290dae6715da704576 to your computer and use it in GitHub Desktop.
Typescript version of lukechilds/merge-images that works with canvas2.6.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Canvas from 'canvas'; | |
import { Image } from 'canvas'; | |
import axios from 'axios'; | |
export class MediaOperations { | |
// Defaults | |
public defaultOptions: any = { | |
format: 'image/png', | |
quality: 0.92, | |
width: 100, | |
height: 100, | |
Canvas: undefined | |
}; | |
public async mergeImages(sources: any[], options: any): Promise<string> { | |
const canvas: Canvas.Canvas = new Canvas.Canvas(this.defaultOptions.width, this.defaultOptions.height); | |
options = { ...this.defaultOptions, ...options }; | |
if (options.Canvas) { | |
options.quality *= 100; | |
} | |
return this.loadImages(sources) | |
.then((images: any[]) => { | |
const ctx = canvas.getContext('2d'); | |
// Set canvas dimensions | |
const getSize = (dim: string) => Math.max(...images.map(image => image.img[dim])); | |
canvas.width = getSize('width'); | |
canvas.height = getSize('height'); | |
// Draw images to canvas | |
images.forEach(image => { | |
ctx.globalAlpha = image.opacity ? image.opacity : 1; | |
return ctx.drawImage(image.img, image.x || 0, image.y || 0); | |
}); | |
if (options.Canvas && options.format === 'image/jpeg') { | |
// Resolve data URI for node-canvas jpeg async | |
return new Promise(resolve => { | |
canvas.toDataURL(options.format, { | |
quality: options.quality, | |
progressive: false | |
}, (err: any, jpeg: unknown) => { | |
if (err) { | |
throw err; | |
} | |
resolve(<string>jpeg); | |
}); | |
}); | |
} | |
return canvas.toDataURL(options.format, options.quality); | |
}); | |
} | |
public async loadImages(sources: any[]): Promise<any> { | |
// tslint:disable-next-line: no-unnecessary-local-variable | |
const images = sources.map((source) => { | |
if (source.constructor.name !== 'Object') { | |
source = { src: source }; | |
} | |
const img = new Image(); | |
const returnObject: any = { ...source, img }; | |
img.src = source.src; | |
return returnObject; | |
}); | |
return images; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment