Quickly integrate mobile device camera into web applications

Introduction

In recent years, with the popularity of smart mobile devices, websites must be designed with a balance of traditional desktop browsers (including the three most common systems Windows, macOS and Linux) and mobile device browsers (generally including iOS and Android). This article shares how to design a web application that takes into account desktop and mobile browsers.

Preparation

Download the following files.

Dynamic Web TWAIN v14.2 (.exe)

Mobile Browser Capture v2.0 (.zip)

Environment

Dynamic Web TWAIN can be used across desktop platforms.

Mobile Browser Capture currently supports only .NET & Java. We'll use Java in this article.

  • JDK: 1.8.0_172
  • Eclipse: Oxygen.3a Release (4.7.3a)
  • 64位Tomcat: Tomcat v9.0

Steps

Step 1 Create a Dynamic Web Application, name it AcquireFromPCsAndMobileDevices and select Apache Tomcat v9.0 as the runtime environment

Mobile-Browser-Capture-1.png

Step 2 Start from a sample

Unzip Mobile Browser Capture, copy src and WebContent from MobileBrowserCaptureSDK2.0\MobileBrowserCaptureSDK2.0\samples\javaDemo to application AcquireFromPCsAndMobileDevices and replace any conflicts.

Install Dynamic Web TWAIN and navigate to C:\Program Files (x86)\Dynamsoft\Dynamic Web TWAIN SDK 14.1 Trial. Copy Samples\Scan to AcquireFromPCsAndMobileDevices\WebContent.

In Eclipse, refresh to see the file changes.

Mobile-Browser-Capture-2.png

Step 3 Add a 'server' in Eclipse and add AcquireFromPCsAndMobileDevices to it. Then start Tomcat

Mobile-Browser-Capture-3.png

Check the application in the browser.

For mobile browser

http://localhost:8080/AcquireFromPCsAndMobileDevices/MobileBrowserCapture.html

For desktop browser

http://localhost:8080/AcquireFromPCsAndMobileDevices/Scan/CustomScan.html

Step 4 Try the page for mobile browser first

This page works both on desktop browsers and mobile browsers, and in desktop Chrome, it's like this

Mobile-Browser-Capture-4.png

Here you can click Show Video to use the webcam on the PC or click Grab Image to load a local file. We'll load a file.

Mobile-Browser-Capture-5.png

Once the file is loaded, extra features will show up as buttons to delete, upload, edit, download, etc.

Mobile-Browser-Capture-6.png

Open it in a mobile browser (assume the IP of the dev machine is 192.168.1.100)

http://192.168.1.100:8080/AcquireFromPCsAndMobileDevices/MobileBrowserCapture.html

The interface is like the following where you can click 'Grab Image' to take a picture or load a local file

Mobile-Browser-Capture-7.png

Once an image is loaded/captured

Mobile-Browser-Capture-9.png Mobile-Browser-Capture-10.png

Upload and press Redirect to see a list of the uploaded files.

Mobile-Browser-Capture-11.png Mobile-Browser-Capture-12.png

The uploaded files are saved in a path specified by System.getProperty("user.dir") plus a runtime user id. For example

C:\Program Files\eclipse-jee-oxygen-3a-win32-x86_64\eclipse\Dynamsoft_Upload\391008ba-aa9f-4564-a285-b44a42ec7864

The path can be changed in the following file.

AcquireFromPCsAndMobileDevices\WebContent\WEB-INF\web.xml

<context-param>
    <param-name>dynamsoft_upload</param-name>
    <param-value>D:\\uploadedimages\\</param-value>
</context-param>

This will then save the files in

D:\uploadedimages\391008ba-aa9f-4564-a285-b44a42ec7864

Step 5 Test the page meant for desktop

Open http://localhost:8080/AcquireFromPCsAndMobileDevices/Scan/CustomScan.html>. Acquire an image

Mobile-Browser-Capture-13.png

Step 6 Add a button to upload

HTML

<input type="button" value="Upload" onclick="Upload();" />

JavaScript

function Upload() {
    if (DWObject) {
        var strFullActionPagePath = location.href.substr(0, location.href.lastIndexOf('/') + 1) + 'upload.jsp';
        DWObject.HTTPUpload(strFullActionPagePath, [DWObject.CurrentImageIndexInBuffer], EnumDWT_ImageType.IT_JPG, EnumDWT_UploadDataFormat.Binary, "test.jpg", function(){}, function(errCode, errString){ console.log(errString);});
    }
}

JSP

<%@  page language="java" import="java.io.*,java.util.*,org.apache.commons.fileupload.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.*"%><%!
%><%
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);


// Set factory constraints
factory.setSizeThreshold(1000000000);// Sets the size threshold beyond which files are written directly to disk.

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Set overall request size constraint
upload.setSizeMax(-1);

// Parse the request
List<FileItem> items = upload.parseRequest(request);

// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
String _fields = "";
String fileName = "";
long sizeInBytes = 0;
String path = application.getRealPath(request.getRequestURI());
String dir = request.getServletContext().getInitParameter("dynamsoft_upload");
dir = dir.replace("\\\\","/");
String _temp_Name = dir + "files-uploaded-in-pc-browsers";
File _fieldsTXT = new File(_temp_Name);
if(!_fieldsTXT.exists())
{
    boolean result = _fieldsTXT.mkdirs();
    System.out.println("File create result:"+result);
}
while (iter.hasNext()) {
    FileItem item = iter.next();
    // Process a regular form field
    if (item.isFormField()) {
    }
    // Process a file upload
    else {
        String fieldName = item.getFieldName();
        fileName = item.getName();
        String contentType = item.getContentType();
        boolean isInMemory = item.isInMemory();
        sizeInBytes = item.getSize();
        if(fileName!=null && sizeInBytes!=0){
            File uploadedFile = new File(_temp_Name + "/" + fileName);
            if(!uploadedFile.exists())
            {
                boolean result = uploadedFile.createNewFile();
                System.out.println("File create result:"+result);
            }
            try {
                item.write(uploadedFile);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
%>

Step 7 Add code to detect the environment and redirect accordingly. Name the file common.js and place it under WebContent/js/

var dynamsoft = dynamsoft || {};
(function () {
    var ua = navigator.userAgent.toLowerCase(),
        _platform = navigator.platform.toLowerCase(),
        _bWin = (_platform == 'win32') || (_platform == 'win64') || (_platform == 'windows'),
        _nMSIE = ua.indexOf('msie'),
        _nTrident = ua.indexOf('trident'),
        _nRV = ua.indexOf('rv:'),
        _nEdge = ua.indexOf('edge'),
        _tmp = ua.match(/version\/([\d.]+).*safari/),
        _bSafari = _tmp ? !0 : !1,
        _nSafari = _tmp ? _tmp[1] : 0,
        _nFirefox = ua.indexOf('firefox'),
        _bFirefox = (_nFirefox != -1),
        _bEdge = _bWin && !_bFirefox && (_nEdge != -1),
        _indexOfChrome = ua.indexOf('chrome'),
        _bChrome = !_bEdge && (_indexOfChrome != -1),
        _bIE = _bWin && !_bFirefox && !_bEdge && !_bChrome && (_nMSIE != -1 || _nTrident != -1 || _nRV != -1),
        _strBrowserVersion = '',
        _mainVer = 0;
    var _deviceType,
        bIsIpad = ua.match(/ipad/i) == "ipad",
        bIsIphoneOs = ua.match(/iphone os/i) == "iphone os",
        bIsMidp = ua.match(/midp/i) == "midp",
        bIsUc7 = ua.match(/rv:1.2.3.4/i) == "rv:1.2.3.4",
        bIsUc = ua.match(/ucweb/i) == "ucweb",
        bIsAndroid = ua.match(/android/i) == "android",
        bIsCE = ua.match(/windows ce/i) == "windows ce",
        bIsWM = ua.match(/windows mobile/i) == "windows mobile";
    if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
        _deviceType = 'phone';
    } else {
        _deviceType = 'pc';
    }
    if (_bEdge) {
        _tmp = ua.slice(_nEdge + 5);
        _tmp = _tmp.slice(0, _tmp.indexOf(' '));
        _strBrowserVersion = _tmp;
    } else if (_bChrome) {
        _tmp = ua.slice(_indexOfChrome + 7);
        _tmp = _tmp.slice(0, _tmp.indexOf(' '));
        _strBrowserVersion = _tmp;
    } else if (_bFirefox) {// FF
        _tmp = ua.slice(_nFirefox + 8);
        _tmp = _tmp.slice(0, _tmp.indexOf(' '));
        _strBrowserVersion = _tmp;
    } else if (_bIE) {
        if (_nMSIE != -1) {
            // 'msie'
            _tmp = ua.slice(_nMSIE + 4);
            _tmp = _tmp.slice(0, _tmp.indexOf(';'));
            _strBrowserVersion = _tmp;
        } else if (_nRV != -1) {
            // 'rv:'
            _tmp = ua.slice(_nRV + 3);
            _tmp = _tmp.slice(0, _tmp.indexOf(';'));
            _tmp = _tmp.slice(0, _tmp.indexOf(')'));
            _strBrowserVersion = _tmp;
        } else if (_nTrident != -1) {
            // 'trident'
            _tmp = ua.slice(_nTrident + 7);
            _tmp = _tmp.slice(0, _tmp.indexOf(';'));
            _strBrowserVersion = _tmp;
        }
    } else if (_bSafari) {
        if (_tmp) {
            _strBrowserVersion = _tmp[1];
        }
    }
    if (_strBrowserVersion.indexOf('.') > -1)
        _mainVer = _strBrowserVersion.slice(0, _strBrowserVersion.indexOf('.')) * 1.0;
    dynamsoft.onlineNavInfo = {
        bWin: _bWin,
        bIE: _bIE,
        bEdge: _bEdge,
        bFirefox: _bFirefox,
        bChrome: _bChrome,
        bSafari: _bSafari,
        strVersion: _strBrowserVersion,
        mainVer: _mainVer,
        deviceType: _deviceType
    };
})();
var strHREF = window.location.href;
if (dynamsoft.onlineNavInfo.deviceType == 'pc') {
    if (strHREF.indexOf('CustomScan') == -1)
        window.location.replace(strHREF.substr(0, strHREF.lastIndexOf('AcquireFromPCsAndMobileDevices') + 30) + '/Scan/CustomScan.html');
} else {
    if (strHREF.indexOf('MobileBrowserCapture') == -1)
        window.location.replace(strHREF.substr(0, strHREF.lastIndexOf('AcquireFromPCsAndMobileDevices') + 30) + '/MobileBrowserCapture.html');
}

Step 8 Create a file index.jsp under WebContent with the following code

<%@ page session="false" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Capture Anywhere</title>
    </head>

    <body>
        <h1>Redirecting</h1>
    </body>
    <script type="text/javascript" src="js/common.js"></script>
</html>

Reference common.js in both MobileBrowserCapture.html and CustomScan.html

<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript" src="../js/common.js"></script>

Now when you navigate to http://192.168.1.100:8080/AcquireFromPCsAndMobileDevices/, you will land on the correct page meant for the browser being used.

results matching ""

    No results matching ""

    results matching ""

      No results matching ""