Path: blob/master/node_modules/@jimp/plugin-blit/src/index.js
1126 views
import { throwError, isNodePattern } from '@jimp/utils';12export default () => ({3/**4* Blits a source image on to this image5* @param {Jimp} src the source Jimp instance6* @param {number} x the x position to blit the image7* @param {number} y the y position to blit the image8* @param {number} srcx (optional) the x position from which to crop the source image9* @param {number} srcy (optional) the y position from which to crop the source image10* @param {number} srcw (optional) the width to which to crop the source image11* @param {number} srch (optional) the height to which to crop the source image12* @param {function(Error, Jimp)} cb (optional) a callback for when complete13* @returns {Jimp} this for chaining of methods14*/15blit(src, x, y, srcx, srcy, srcw, srch, cb) {16if (!(src instanceof this.constructor)) {17return throwError.call(this, 'The source must be a Jimp image', cb);18}1920if (typeof x !== 'number' || typeof y !== 'number') {21return throwError.call(this, 'x and y must be numbers', cb);22}2324if (typeof srcx === 'function') {25cb = srcx;26srcx = 0;27srcy = 0;28srcw = src.bitmap.width;29srch = src.bitmap.height;30} else if (31typeof srcx === typeof srcy &&32typeof srcy === typeof srcw &&33typeof srcw === typeof srch34) {35srcx = srcx || 0;36srcy = srcy || 0;37srcw = srcw || src.bitmap.width;38srch = srch || src.bitmap.height;39} else {40return throwError.call(41this,42'srcx, srcy, srcw, srch must be numbers',43cb44);45}4647// round input48x = Math.round(x);49y = Math.round(y);5051// round input52srcx = Math.round(srcx);53srcy = Math.round(srcy);54srcw = Math.round(srcw);55srch = Math.round(srch);5657const maxWidth = this.bitmap.width;58const maxHeight = this.bitmap.height;59const baseImage = this;6061src.scanQuiet(srcx, srcy, srcw, srch, function(sx, sy, idx) {62const xOffset = x + sx - srcx;63const yOffset = y + sy - srcy;6465if (66xOffset >= 0 &&67yOffset >= 0 &&68maxWidth - xOffset > 0 &&69maxHeight - yOffset > 070) {71const dstIdx = baseImage.getPixelIndex(xOffset, yOffset);72const src = {73r: this.bitmap.data[idx],74g: this.bitmap.data[idx + 1],75b: this.bitmap.data[idx + 2],76a: this.bitmap.data[idx + 3]77};7879const dst = {80r: baseImage.bitmap.data[dstIdx],81g: baseImage.bitmap.data[dstIdx + 1],82b: baseImage.bitmap.data[dstIdx + 2],83a: baseImage.bitmap.data[dstIdx + 3]84};8586baseImage.bitmap.data[dstIdx] =87((src.a * (src.r - dst.r) - dst.r + 255) >> 8) + dst.r;88baseImage.bitmap.data[dstIdx + 1] =89((src.a * (src.g - dst.g) - dst.g + 255) >> 8) + dst.g;90baseImage.bitmap.data[dstIdx + 2] =91((src.a * (src.b - dst.b) - dst.b + 255) >> 8) + dst.b;92baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(93dst.a + src.a94);95}96});9798if (isNodePattern(cb)) {99cb.call(this, null, this);100}101102return this;103}104});105106107