Socket.io, saved image on server isn't opened - image

I'm trying to save image from canvas on server, but image isn't opened (isn't supported format).
Client:
const canvas = document.getElementById('canvas');
var sendData = () => {
const dataURL = canvas.toDataURL();
socket.emit('sendImage', dataURL.toString('base64'));
};
Server:
io.on('connection', function(socket) {
socket.on('sendImage', (imageData) => {
fs.writeFile(__dirname + '/image.png', imageData, function (err)
{
if (err) throw err;
console.log('It\'s saved!');
});
});
});

I found solution.
Client:
dataURL.toString('base64') has base64 encoded data in the format of
data:image/png;base64,/9j/4AAQSkZJRgABA…
So we need to get rid of the mime type and encoding information at the front.
var sendData = () => {
const dataURL = canvas.toDataURL().toString('base64');
const toSend = dataURL.split(',')[1];
socket.emit('sendImage', toSend);
};
Server:
Now we need to convert its buffer.
fs.writeFile(__dirname + '/image.png', Buffer.from(imageData, 'base64'), function
(err) {
if (err) throw err;
console.log('It\'s saved!');
});

Related

Tesseract.js throw Error(data) cannot read properties of undefined (reading '_malloc') in tesseract file

I'm trying to use tesseract to convert image to text by upload image to my web app but got the error in the tesseract create worker.js like _malloc is undefined in throw Error(data).
I'm using tesseract version 2.1.5,
and I wrote the code from the video in 2019, I think maybe tesseract is changed from that time.
This is the error
This is code in app.js
const express = require("express");
const app = express();
const fs = require("fs");
const multer = require("multer");
const {createWorker} = require("tesseract.js");
const worker = createWorker({
logger: m => console.log(m)
});
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./uploads");
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({ storage: storage}).single("fname");
app.set("view engine", "ejs");
app.get('/', (req,res) => {
res.render('index');
});
app.post('/upload', (req,res) => {
upload(req, res, err => {
fs.readFile(`./uploads/${req.file.originalname}`, (err, data) => {
if(err) return console.log("Error", err);
worker
.recognize('./uploads/op.png')
.then(result => {
res.send(result.txt);
})
.finally(() => worker.terminate());
});
});
});

Dialogflow v2 Actions on Google response timeout

Hi I have a timeout problem to get a json response; I am using google places API to look for the closest location.
Could anyone help me with this? Thanks.
const PlaceSearch = require("./node_modules/googleplaces/lib/NearBySearch.js");
const PlaceDetailsRequest = require("./node_modules/googleplaces/lib/PlaceDetailsRequest.js");
app.intent('Ask Location', conv => {conv.ask(new Permission({context: 'To start',permissions: 'DEVICE_PRECISE_LOCATION',}));});
app.intent('geolocation.intent', (conv,params,granted) =>{
if(granted){
var coordinates = conv.device.location.coordinates;
var location = [coordinates.latitude, coordinates.longitude];
var searchParameters = {
location: location,
name:'Store Name',
radius:10000
};
var config = {
apiKey:'#####',
outputFormat:'json'
};
var placeSearch = new PlaceSearch(config.apiKey, config.outputFormat);
var placeDetailsRequest = new PlaceDetailsRequest(config.apiKey, config.outputFormat);
placeSearch(searchParameters, function (error, search_response) {
if(search_response.status === 'OK'){
placeDetailsRequest({reference: search_response.results[0].reference}, function (error, details_response) {
conv.ask(`Your closest store is at ${details_response.result.formatted_address}.`);
});
}
});
}
});
I solved the issue using a request to Google API via URL; and using a promise.
const request = require("request");
app.input("geolocation.intent", conv => {
return new Promise((resolve, reject) => {
...
request(options, (error, response, body) => {
...
if (error) {
...
reject(...);
} else {
...
resolve(...);
}
}).then(result => {
const address = result.address;
conv.ask('Your closest store is...');
}).catch(error => {
conv.close('Error in Promise');
});
});
What I learned is that in Dialogflow API v2 you need to use promises when you make a request.

Display image on pug

I'm new to NodeJS world.
I tried to display image from mongodb using pug and node express.
Please see my code and guide me.
customer.pug
extend layouts
block content
h1.container #{title} of #{customer.full_name}
div.container
p Full Name: #{customer.full_name}
p Address: #{customer.address}
p Age: #{customer.age}
img.imageScr1(src=customer.profileimage, alt=customer.full_name)
app.js
const express = require('express');
const path = require('path');
const router = express.Router();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const fs = require('fs');
const multer = require('multer');
// set storage engine
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, './uploads/',)
},
filename: function (req, file, cb) {
cb(null, file.fieldname + Date.now() + path.extname(file.originalname));
}
});
// init upload
const upload = multer({
storage: storage
});
// Middlewares
// middleware for Assets - to set public for assets
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// route - homepage
app.get('/', function (req, res) {
Customer.find({}, null, function(err, customers) {
if(err){
console.log(err);
} else{
// customers.profileimage = '/' + customers.profileimage;
// console.log('image prefix::: ' + customer.profileimage);
res.render('index', {
title: 'Customer List',
customers: customers
});
}
});
});
app.post('/customer/add', upload.single('profileimage'), function (req, res) {
var customer = new Customer();
customer.full_name = req.body.full_name;
customer.address = req.body.address;
customer.age = req.body.age;
customer.profileimage = req.file.path;
customer.save(function (err) {
if(err){
console.log(err);
} else{
res.redirect('/');
}
});
});
I got following error when render customer.pug view.
error_console
I found that, if I add '\' before image path 'uploads\profileimage1520473825415.jpg', it displays image.
I tried many ways to do that did not work.
Please help me.
Cheers

How can I use NativeScript 3 to capture image and send to a remote server

I'm new to NativeScript and I'm trying to capture an image with the camera module (this works fine), and convert it to base64 (this is not working) and POST to server.
I've googled for days. Any help you can lend would be immensely appreciated.
I've tried this about 16 billion different ways and this is my current code:
viewModel.takePicture1 = function() {
camera.requestPermissions();
var isAvailable = camera.isAvailable();
console.log(isAvailable);
var options = { width: 640, keepAspectRatio: true, saveToGallery: false };
camera.takePicture().then(function (img) {
try{
var imageData = img.toBase64String("jpeg"); // fails here
console.log(imageData);
}catch(err){
console.log("Error: "+err);
}
http.request({
url: "http://[server address]/lab/ns_exp/upload_test.php",
method: "POST",
headers: { "Content-Type": "application/base64" },
content: imageData
}).then(function() {
console.log("Upload successful");
}).catch(function(e) {
console.log("Unsuccessful upload", e);
});
});
}//
Oh, I do want to make clear that I'm not using angular (obviously), so please don't provide an answer that does so. : ) (Vuejs Holdout)
The key here is that base64 needs to know that the image is a JPEG, and what quality the image should be. The code should look like this:
camera.takePicture(cameraOptions)
.then(imageAsset => {
imageSource.fromAsset(imageAsset).then(res => {
myImageSource = res;
var base64 = myImageSource.toBase64String("jpeg", 100);
Just in case someone finds this later and wonders about putting the image (UI) and/or the image (base64) into an observableArray, here is my complete function:
viewModel.takePhoto = function(){
var self = this;
camera.requestPermissions();
var cameraOptions = { width: 640, keepAspectRatio: true, saveToGallery: false };
camera.takePicture(cameraOptions)
.then(imageAsset => {
imageSource.fromAsset(imageAsset).then(res => {
myImageSource = res;
var base64 = myImageSource.toBase64String("jpeg", 100);
self.photoData.push({"data": base64});
var image = new imageModule.Image();
image.src = imageAsset;
self.photoUI.push({"src": image.src});
listView.refresh();
})
}).catch(function (err) {
console.log("Error -> " + err.message);
});
}

Loading image server node.js

im trying to load image and when I check on the browser if works, it say not found, any ideas of how to fixed.
Thank you
var http = require('http');
var body;
exports.handle = function(req, res) {
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': body.length
});
res.end(img, 'binary');
};
exports.init = function(cb) {
require('fs').readFile('./image.png', function(err, data) {
if (err) throw err;
body = data;
cb();
});
}

Resources