用node实现裁剪图片(jcrop插件)

需要引入的包(express、ejs、gm、)

app.js(需要用到gm工具)

var express = require("express");

var fs = require("fs");

var gm = require("gm");

var app = express();

//设置模板引擎ejs

app.set("view engine","ejs");

//设置静态文件,即设置static为前端根目录

app.use(express.static("./public"));

//设置中间件,即地址根目录默认执行index.ejs文件

app.get("/",function(req,res,next){

            res.render("index");

});

//设置路由,地址/cut,响应前端发来的请求

//这个页面需要接受几个get请求参数(文件名、w、h、x、y),记得引包fs和gm

app.get("/cut",function (req,res,next) {

            var filename = req.query.filename;

            var w = req.query.w;

            var h = req.query.h;

            var x = req.query.x;

            var y = req.query.y;

            //node服务器用gm剪切,记得引包fs和gm

            //这个不是静态文件,所以根目录用./

            gm("./picture/danny.jpg") .crop(w,h,x,y)

                                                    .resize(200,200,"!")

                                                    .write("./picture/dany2.jpg",function (err) {

                                                                if (err){ res.send("-1"); return; }

                                                                res.send("1"); });

app.listen(3000);

index.ejs

//页面要有一个裁剪的按钮,点击后发送给服务器数据

$("input").click(function () {

    var w =parseInt($(".jcrop-holder>div:first").css("width"));

    var h =parseInt($(".jcrop-holder>div:first").css("height"));

    var x =parseInt($(".jcrop-holder>div:first").css("left"));

    var y =parseInt($(".jcrop-holder>div:first").css("top"));

    $.get("/cut",{

        "w" :w,

        "h" :h,

        "x" :x,

        "y" :y

    },function(result){

        alert(result);

    });

});

你可能感兴趣的:(用node实现裁剪图片(jcrop插件))