Home>Article>Web Front-end> Node+UDP implements image cropping function
This article will introduce to you howNodejsUDP implements the image cropping function. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "nodejs Tutorial"
Speaking of UDP, perhaps the most attractive thing is [UDP server], right? .
UDP server can be used for the (efficient) transmission of some special data, such as pictures, videos and audio information, etc.
I have seen some big guys using UDP to The main purpose of C server interaction is to send logical services that cannot be processed by PHP to other servers for processing through the UDP server.
So, is there such a requirement: We have two servers A and B. We want A to handle all business logic, while B only does database operations (such as updates).
There are multiple design ideas that can solve the above problem. The simplest one is to send a request through HTTP, pass the processed parameters of A to server B through HTTP, and then server B obtains the parameters and updates the database. . ——This method is very simple for Node.js, but HTTP is a TCP protocol. For our own two trustworthy servers, we prefer to use UDP to transmit the protocol to avoid unnecessary data transmission in TCP.
The next application we are going to introduce is to use Node.js to handle image upload and cutting (image processing), and display all processed image lists through the client, and this function will also be applied UDP module to achieve.
This application consists of two parts, one is the Web service function module for image uploading and the page display function after image processing; the other is It is the processing of pictures, mainly the cutting and saving of pictures. As a user, I hope it is a tool that allows me to upload a picture and specify the length and width to be cut. After processing by the system, it will return a cut picture to the user and return it to the page for display.
Based on the analysis of the above requirements, we transformed the above requirements into the system operation flow chart shown in Figure 4-5. Based on the application analysis, we will design two servers, one is a Web server and the other is an image processing server. The two interact through the UDP protocol:
Image upload page, mainly The image upload and preview function page; the image display page, which displays the images returned after image processing; the main function of the HTTP Web server is file upload and image display; the image processing server, which passes the data from the Web server to image processing through the UDP protocol Server, the image processing server returns the corresponding data to the Web server after performing certain processing.
According to the above analysis, the three functional modules that need to be implemented in this application are UDP Server side and UDP Client Terminal (Web Server) and Jade page.
So first we start with the implementation principle of the UDPServer code of the application (that is, the image processing server). As the server side of UDP, the image processing server needs to use the UDP module to implement the UDP server. Since the UDP server relies on image processing tools, an open source Node.js image processing tool in github - node -imagemagick will be used in the UDP service program. Assist in realizing image processing functions. Based on the above analysis, we simply designed the code framework of UDP Server. The code is as follows:
const dgram=require('dgram'); //UDPconst server=dgram.createSocket("udp4");server.on("message",function(msg,rinfo){ //监听消息事件后处理})server.on("listening",function(){ var address=server.address(); console.log("server listening "+address.address+":"+address.port);})server.bind("监听端口号");
You will find that UDP actually seems to be similar to socket.io? They all use a message flow monitoring mechanism. HTTP does not do this, so HTTP is rarely used to do these highly interactive things - this is of course related to their internal implementation.
After monitoring, it’s time to get down to business: we need a function to process images. The triggering time of this function must be after the event stream:
npm install imagemagick
It should be noted that when using this tool, the imagemagick-cli system tool software must be installed:sudo apt-get install imagemagick --fix -missing
(Otherwise an exception will be thrown during runtime)
/** url:图片源路径 width:图片压缩宽 height:图片压缩高 newName:图片处理后存储路径 **/function resizeImage(url,width,height,newName,callback){ var im=require('imagemagick'); im.resize({ srcPath: url, dstPath: newName, width: width, height: height }, function(err,stdout,stderr){ if(err){ callback(-1); }else{ callback(stdout); } })}
Then call in the onmessage callback function of udp:
server.on("message",function(msg,rinfo){ var imageObject=JSON.parse(msg); resizeImage(imageObject.url, imageObject.width, imageObject.height, imageObject.new_name, function(ret){ var retJson; if(ret==-1){ retJson={'code':-1,'msg':'some error in resize image','data':{}} }else{ retJson={'code':0,'msg':'success','data':{'name':imageObject.new_name}} } //将json对象转为json字符串 var retStr=JSON.stringify(retJson); //转为buffer对象,用于UDP传输 var message=new Buffer(retStr); server.send(message,0,message.length,rinfo.port,rinfo.address); })})
server.on("message", callback(msg, rinfo))
There are msg and rinfo parameters in the callback function, where msg is the message data sent by the client, and rinfo is the client information. The server uses the port port and IP address in the client information. address, just use server.send response data to the client. At this point we have implemented a UDP server for image processing. Next, we will introduce how the web server interacts with it.
npm install express jade formidable body-parser
const jade=require('jade');const express=require('express');const bodyParser=require('body-parser');const fs=require('fs');const VIEW=__dirname+"/view/";var app=express();app.set('view engine','jade');app.use(bodyParser.urlencoded({extended: true}))app.get('/',function(req,res,next){ //http响应文件上传页面 res.render(VIEW+'index.jade');};//文件上传处理逻辑app.post('/upload',function(req,res,next){ var now=Date.parse(new Date())/1000; var form=new formidable.IncomingForm(), fields=[], baseName=__dirname+'/uploadFile/'+now, imageName=baseName+'.png', //源图片路径 newName=baseName+'_small'+'.png', //新文件路径 pathName='/uploadFile/'+now+'_small'+'.png'; form.on('field',function(field,value){ fields.push([field,value]); }); form.parse(req,function(error,fields,files){ var size=''+fields.width+'x'+fields.height fs.renameSync(files.image.path,imageName); imageResize(fields.width, fields.height, imageName, newName,res); })};app.listen('监听端口号');
form.parse(request, [callback]) 该方法会转换请求中所包含的表单数据,callback会包含所有字段域和文件信息
文件上传功能同样是应用formidable 模块,当然这里还应用到其获取POST数据的方法。formidable 模块提供了获取field参数的API form.on的field 事件,监听POST数据传递。所有的POST数据都需要应用form.parse 进行解析,解析返回fields对象和文件对象files。根据获取的width和height,调用imageResize对图片进行相应的压缩处理。
然后去实现imageResize函数:imageResize函数的主要功能是应用UDP模块连接UDPServer,将相应的参数数据转化为json字符通过UDP协议传递到UDPServer,并将UDPServer响应的数据通过res.render直接返回显示到相应的页面
function imageResize(width,height,imagePath,newName,res){ var imageJson={ 'width':width, 'height':height, 'url':imagePath, 'new_name':newName }; var jsonStr=JSON.stringify(imageJson); var client=dgram.createSocket("udp4"); var message=new Buffer(jsonStr); client.send(message,0,message.length,Server端监听的端口号,"域名",function(){ client.on("message",function(msg,rinfo){ var retJson=JSON.parse(msg); if(retJson.code===0){ res.render(VIEW+'main.jade',{'url':pathName,'err':'ok'}); }else{ res.render(VIEW+'main.jade',{'url':'','err':'error'}); } }) })}
前端模板jade部分就先省去。。。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Node+UDP implements image cropping function. For more information, please follow other related articles on the PHP Chinese website!