Reading png image from request using body-parser and Express
Asked Answered
A

2

6

I am sending the following request to my server using postman:

enter image description here

I try to access the image in my application using the following code:

app.js

var express = require('express');
var bodyParser = require('body-parser');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

app.use(bodyParser.raw({
  type: 'image/png',
  limit: '10mb'
}));

app.use('/', indexRouter);
app.use('/users', usersRouter);

module.exports = app;

index.js (router)

var express = require('express');
const router = express.Router();
var Jimp = require('jimp');

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});

router.post('/a', function(req, res) {
  var image = req.body;

  try{
      Jimp.read(image, (err, input) => {
        if (err) throw err;
        input.sepia();

        input.getBuffer(Jimp.AUTO, (err, output) => {
          if(err) throw err;

          res.writeHead(200, {'Content-Type': 'image/png' });
          return res.end(output, 'binary');
        });
      });
  }catch (err){
      return res.status(400).send(`Error: ${err.message}`).end();
  }
});

module.exports = router;

I was first using a form (with the help of express-fileupload library) to send the image and this worked fine, so I know the problem has to be somewhere before the line var image = req.body. For the Jimp functions (image processing library) to work, the image has to be a buffer representing the png image. When running console.log(image), the console outputs {}.

Can anybody show me a way to read the png as a buffer when it is sent as a Binary file?

Arise answered 21/11, 2018 at 16:25 Comment(0)
A
1

Nevermind, I just had to change the Content-Type header in my request to image/png -.-

Arise answered 21/11, 2018 at 16:56 Comment(0)
E
0

can you rewrite function with lib multer?

const multer  = require('multer')
const storage = multer.memoryStorage()
const upload = multer({ storage: storage })

router.post('/a', upload.single('image'), function(req, res, next) {    
  const image = req.file.buffer    
});

or with formidable?

var formidable = require('formidable' );

router.post('/a', (req, res) => {
  const form = new formidable.IncomingForm();
  form.parse(req, (error, fields, files) => {
    const image = files.image;
  })
});
Exudation answered 21/11, 2018 at 17:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.