We now live in an age where you no longer need to buy a $400 printer to scan documents. Tools like Adobe Scan and CamScanner allow you to do it straight from your phone!
Web developers are constantly pushing the limits of what can be accomplished on the web. Now, you can create a mobile document scanner with Javascript!
Let's make one ourselves.
Introduction
We will be using jscanify to do this.
The goal is to convert this image:
To this:
Setting up the environment
We'll be doing this in a web environment. If you want to do this server side or with React, jscanify supports it too (you'll need to check the documentation though).
<html>
<body>
<script src="https://docs.opencv.org/4.7.0/opencv.js"></script>
<script src="https://cdn.jsdelivr.net/gh/ColonelParrot/jscanify@master/src/jscanify.min.js"></script>
</body>
</html>
Getting the image and scanning
Now, let's load an image and scan it:
<html>
<body>
<script src="https://docs.opencv.org/4.7.0/opencv.js"></script>
<script src="https://cdn.jsdelivr.net/gh/ColonelParrot/jscanify@master/src/jscanify.min.js"></script>
<img src="https://colonelparrot.github.io/jscanify/images/test/test.png" crossorigin="anonymous" id="image" />
<script>
cv.onRuntimeInitialized = function() {
function scan() {
const scanner = new jscanify()
const scanned = scanner.extractPaper(image, 386, 500)
document.body.appendChild(scanned)
}
image.onload = scan
if (image.complete) {
scan()
}
}
</script>
</body>
</html>
We execute the code when OpenCV has loaded by waiting for the onRuntimeInitialized
event. Once loaded, we initialize jscanify
to create the scanner, and with one line, extract the paper with the extractPaper
method. The parameters in the method are the width and height respectively.
So that's it! It's that easy :)
Top comments (2)
Nice one! Thanks for sharing.
This will do for basic scanning needs, but if you're looking for special features like auto-capture, user guidance, or cropping, I'd recommend commercial solutions like Scanbot SDK (full disclosure: I'm part of the team).
I'll link to our JavaScript Document Scanner tutorial here in case you're interested in trying it out!
How can I adjust corner points before highlighting & extracting the image? Let me know if you have any ideas for implementation.