This article mainly introduces the example of using gm circular cropping and compositing pictures under Nodejs. Now I share it with you and give you a reference.
When it comes to image processing under Nodejs, the first thing that comes to mind is gm. The bottom layer of gm can be GraphicsMagic (which is actually the origin of gm), or it can be ImageMagick (in fact, GraphicsMagic itself was also split from ImageMagic and is now independent. ). Although these two tools themselves are not JS implementations, so they require additional installation. However, this tool is very common and may have been pre-installed in the Linux system, and the installation is also very convenient, so there is no need to give up just because it is a "third party". Although these two software are just the bottom layer and do not need to be concerned about, the author found in practice that GraphicsMagic must be used, so here I only introduce the installation and use of GraphicsMagics.
GaphicsMagic Installation
GraphicsMagic official website is: http://www.graphicsmagick.org/
The official website and most tutorials online teach how to Compile, but I personally think it can be installed directly through the software library, such as
apt-get install graphicsmagic
If you want to learn to use GraphicsMagic from the command line, you can read here: http://www.jb51.net/LINUXjishu/120332.html
gm installation under Nodejs
gm is a node library, so it can be installed with npm
npm install gm
Official document: http://aheckmann.github. io/gm/
Principle of circular clipping
gm is an encapsulation of GraphicsMagic, so in theory, all functions of GraphicsMagic can be implemented in the form of interfaces through gm. GM itself does not support circular clipping (at least I don't know how to achieve it), which also means that its underlying layer does not directly support it.
The more commonly used functions of gm are: scaling, square cropping, and format conversion.
So the core of circular cropping in this tutorial is to use SVG to construct a circular picture through svg, and then convert it into png through gm, that is, use svg to transform the picture format.
SVG can be used to crop circular images. There are two ways to achieve circular cropping found on the Internet
1. Define a circle through clip-path
path, and then set clip-path in the style of the image, that is, through this way, image cropping is achieved. In theory, it is "cropping" in the true sense
<svg> <defs> <clipPathid="clipPath"> <circlecx="5"cy="5"r="5"/> </clipPath> </defs> <imagestyle="clip-path: url(#clipPath);"href="{{icon_img}}" rel="external nofollow" rel="external nofollow" x="0"y="0"width="10"height="10"/> </svg>
If you use clip-path, you can see this tutorial
However, there is no problem with this configuration in the browser, but I found that after converting it to png through gm, the style has no effect and is still square.
2. First define a pattern through the circle tag
<svg> <defs> <patternpatternUnits="userSpaceOnUse"id="raduisImage"x="0"y="0"width="10"height="10"> <imagehref="{{icon_img}}" rel="external nofollow" rel="external nofollow" x="0"y="0"width="10"height="10"/> </pattern> </defs> <circlecx="5"cy="5"r="5"fill="url(#raduisImage)"></circle> </svg>
, which is the original picture, then create a circle and fill it with the pattern just defined.
Principles of compositing pictures
If you understand the above-mentioned cropping principles, compositing will become simple. Just put the pictures you want to combine together in svg format. Although gm itself supports image synthesis, using compose or mosaic (see this tutorial for details), it feels not as clear as svg.
Note that the author tried to add text through svg, but found that Chinese characters could not be recognized, so it can still be added through gm. The font needs to be set when adding (see the next chapter for details on code implementation)
If you want to embed two circular pictures in a large picture, you need to set two patterns. Here is a rule of thumb:
The x and y of the pattern are set to 0. 0
The width and height of the pattern are set the same as the canvas
The x and y of the image are set to its "actual position", that is Corresponding to cx-r and cy-r of circle, r is cut because cx and cy refer to the center of the circle, while x and y are the positions of the upper left corner of the figure.
Code implementation
const gm = require('gm') const fs = require('fs') let templateSVG = "/path/to/original.svg" let outputSVG = "/path/to/repalced.svg" let input = "/path/to/icon.png" let font = "/path/to/font.ttf" let fontColor = "white" let fontSize = 10 fs.readFile(templateSVG,'utf-8',function(err,data){ if (err) throw err var d = data.replace('{{icon_img}}',input) fs.writeFile(outputSVG,d,function(err){ if (err) throw err gm(outputSVG) .font(font) .fill(fontColor) .fontSize(fontSize) .drawText(textPosition[0], textPosition[1], text)// .write(output,function(err){ if(err) cb(err) // next }) }) })
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement custom global methods in vue
How to implement global registration and local registration in vue components
How to modify the project name through the vue-cli webpack project
The above is the detailed content of Use gm cropping to synthesize pictures under Nodejs. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.