- Creating a Barcode Scanner using Android Studio
- What is this article about
- Prerequisite
- Let’s write some code
- Scan Barcodes with ML Kit on Android
- Before you begin
- Input image guidelines
- 1. Configure the barcode scanner
- Kotlin
- 2. Prepare the input image
- Using a media.Image
- Kotlin
- Kotlin
- Kotlin
- Using a file URI
- Kotlin
- Using a ByteBuffer or ByteArray
- Kotlin
- Using a Bitmap
- Kotlin
- 3. Get an instance of BarcodeScanner
- Kotlin
- 4. Process the image
- Kotlin
- 5. Get information from barcodes
- Kotlin
- Tips to improve real-time performance
- Как создать приложение для считывания штрих-кода на андроид
Creating a Barcode Scanner using Android Studio
Step by step guide to building a barcode scanning application using Android Studio.
What is this article about
This article will guide you through creating an android application using which you can make use of your mobile camera to scan a barcode and read the data in them.
Prerequisite
- The latest version of Android Studio installed. ( download from here )
- A mobile device to test the application. (you can make use of the inbuild android emulator but in some pc, it may cause some issues.)
- Knowledge of java or any object-oriented programing language.
Let’s write some code
- Create a new application in android studio and name it Barcode Scanner.
- Open up your app-level Gradle file and add the below dependency there.
3. Now hit on Sync now button and wait for the build to complete. Once the build is complete open up your manifest file and add the necessary permissions.
also, add the metadata field in your manifest file, inside the application tag and above the activity tag.
here’s a full view of my manifest file
4. Now you have set up all the dependency needed for the barcode scanner to work and all the permission necessary. Let’s build the UI for the app.
5. Open your activity_main.xml file and write the below code inside.
Now your view should look something like this
here we have something called a sufaceview in android and a textview field to display the text scanned by the barcode.
SurfaceView: It provides a dedicated drawing surface embedded inside the view hierarchy.
You have completed the UI code for the Barcode App, now let’s write the java code to make wonders happen.
6. Open MainActivity.java file and you will see the following code.
let’s add some code of our own
7. First, we need to bind the views.
8. Now we will write the method to scan the image for a barcode.
this method will help us scan and display the text in the textview we created in the XML file.
9. The complete java code will look something like this.
Now try scanning this barcode and you will see the value that is embedded in the barcode in the textview.
The final screen should something like this.
Источник
Scan Barcodes with ML Kit on Android
You can use ML Kit to recognize and decode barcodes.
There are two ways to integrate barcode scanning: by bundling the model as part of your app, or by using an unbundled model that depends on Google Play Services. If you select the unbundled model, your app will be smaller, however the bundled model has performance advantages over the unbundled model. See the table below for details.
Feature | Unbundled | Bundled |
---|---|---|
Implementation | Model is dynamically downloaded via Google Play Services. | Model is statically linked to your app at build time. |
App size | About 600 KB size increase. | About 3.2 MB size increase. |
Initialization time | Might have to wait for model to download before first use. | Model is available immediately. |
Performance | V1 model. | V3 model is faster and more accurate. V3 model detects more correct results from bad-quality inputs and have more stable bounding boxes in streaming mode. Recall is improved by 17.1%. |
- Play around with the sample app to see an example usage of this API.
- See the Material Design showcase app for an end-to-end implementation of this API.
Before you begin
- In your project-level build.gradle file, make sure to include Google’s Maven repository in both your buildscript and allprojects sections.
- Add the dependencies for the ML Kit Android libraries to your module’s app-level gradle file, which is usually app/build.gradle . Choose one of the following dependencies based on your needs:
For bundling the model with your app:
For using the model in Google Play Services:
If you choose to use the model in Google Play Services, you can configure your app to automatically download the model to the device after your app is installed from the Play Store. To do so, add the following declaration to your app’s AndroidManifest.xml file:
If you don’t enable install-time model downloads, the model is downloaded the first time you run the scanner. Requests you make before the download has completed produce no results.
Input image guidelines
For ML Kit to accurately read barcodes, input images must contain barcodes that are represented by sufficient pixel data.
The specific pixel data requirements are dependent on both the type of barcode and the amount of data that’s encoded in it, since many barcodes support a variable size payload. In general, the smallest meaningful unit of the barcode should be at least 2 pixels wide, and for 2-dimensional codes, 2 pixels tall.
For example, EAN-13 barcodes are made up of bars and spaces that are 1, 2, 3, or 4 units wide, so an EAN-13 barcode image ideally has bars and spaces that are at least 2, 4, 6, and 8 pixels wide. Because an EAN-13 barcode is 95 units wide in total, the barcode should be at least 190 pixels wide.
Denser formats, such as PDF417, need greater pixel dimensions for ML Kit to reliably read them. For example, a PDF417 code can have up to 34 17-unit wide «words» in a single row, which would ideally be at least 1156 pixels wide.
Poor image focus can impact scanning accuracy. If your app isn’t getting acceptable results, ask the user to recapture the image.
For typical applications, it’s recommended to provide a higher resolution image, such as 1280×720 or 1920×1080, which makes barcodes scannable from a larger distance away from the camera.
However, in applications where latency is critical, you can improve performance by capturing images at a lower resolution, but requiring that the barcode make up the majority of the input image. Also see Tips to improve real-time performance.
1. Configure the barcode scanner
For example, to detect only Aztec code and QR codes, build a BarcodeScannerOptions object as in the following example:
Kotlin
The following formats are supported:
- Code 128 ( FORMAT_CODE_128 )
- Code 39 ( FORMAT_CODE_39 )
- Code 93 ( FORMAT_CODE_93 )
- Codabar ( FORMAT_CODABAR )
- EAN-13 ( FORMAT_EAN_13 )
- EAN-8 ( FORMAT_EAN_8 )
- ITF ( FORMAT_ITF )
- UPC-A ( FORMAT_UPC_A )
- UPC-E ( FORMAT_UPC_E )
- QR Code ( FORMAT_QR_CODE )
- PDF417 ( FORMAT_PDF417 )
- Aztec ( FORMAT_AZTEC )
- Data Matrix ( FORMAT_DATA_MATRIX )
Note: For a Data Matrix code to be recognized, the code must intersect the center point of the input image. Consequently, only one Data Matrix code can be recognized in an image.
2. Prepare the input image
You can create an InputImage object from different sources, each is explained below.
Using a media.Image
To create an InputImage object from a media.Image object, such as when you capture an image from a device’s camera, pass the media.Image object and the image’s rotation to InputImage.fromMediaImage() .
If you use the CameraX library, the OnImageCapturedListener and ImageAnalysis.Analyzer classes calculate the rotation value for you.
Kotlin
If you don’t use a camera library that gives you the image’s rotation degree, you can calculate it from the device’s rotation degree and the orientation of camera sensor in the device:
Kotlin
Then, pass the media.Image object and the rotation degree value to InputImage.fromMediaImage() :
Kotlin
Using a file URI
To create an InputImage object from a file URI, pass the app context and file URI to InputImage.fromFilePath() . This is useful when you use an ACTION_GET_CONTENT intent to prompt the user to select an image from their gallery app.
Kotlin
Using a ByteBuffer or ByteArray
To create an InputImage object from a ByteBuffer or a ByteArray , first calculate the image rotation degree as previously described for media.Image input. Then, create the InputImage object with the buffer or array, together with image’s height, width, color encoding format, and rotation degree:
Kotlin
Using a Bitmap
To create an InputImage object from a Bitmap object, make the following declaration:
Kotlin
The image is represented by a Bitmap object together with rotation degrees.
3. Get an instance of BarcodeScanner
Kotlin
4. Process the image
Kotlin
5. Get information from barcodes
Kotlin
Tips to improve real-time performance
If you want to scan barcodes in a real-time application, follow these guidelines to achieve the best framerates:
Don’t capture input at the camera’s native resolution. On some devices, capturing input at the native resolution produces extremely large (10+ megapixels) images, which results in very poor latency with no benefit to accuracy. Instead, only request the size from the camera that’s required for barcode detection, which is usually no more than 2 megapixels.
If scanning speed is important, you can further lower the image capture resolution. However, bear in mind the minimum barcode size requirements outlined above.
If you are trying to recognize barcodes from a sequence of streaming video frames, the recognizer might produce different results from frame to frame. You should wait until you get a consecutive series of the same value to be confident you are returning a good result.
The Checksum digit is not supported for ITF and CODE-39.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Как создать приложение для считывания штрих-кода на андроид
[wpanchor этом уроке научимся создавать приложение для чтения штрих-кодов и QR-кодов с использованием стандартной библиотеки Mobile Vision API.
Еще с выпуском Google Play services версии 7.8 разработчики добавили интерфейсы Mobile Vision, которые обеспечивают API для обнаружения штрих-кода. Они считывают и декодируют множество различных типов штрих-кодов, быстро, легко и локально.
Классы для обнаружения и анализа штрих-кодов доступны в пространстве имен com.google.android.gms.vision.barcode. Основной рабочей лошадкой является класс BarcodeDetector. Он выполняет обработку объектов Frame и возвращает массив штрих-кодов SparseArray .
Тип Barcode представляет собой единый общепризнанный штрих-код и его значение. В случае 1D штрих-кодов, таких как коды UPC, это будет просто номер, который закодирован в штрих-коде. Его значение доступно в поле rawValue, в то время как тип штрих-кода (то есть его кодировку) можно найти в поле format.
Для 2D штрих-кодов, которые содержат структурированные данные, такие как QR-коды — в поле valueFormat устанавливается определенный тип значения, соответствующего полю данных. Так, например, если обнаружен тип URL , то поле valueFormat вернет константу URL, а объект Barcode.UrlBookmark будет содержать значение URL-адреса. Помимо URL-адресов, существует множество различных типов данных, которые QR-код может хранить. Например, почтовый адрес, дату и время события календаря, мероприятие в календаре, информацию контакта, номер телефона, местоположение на карте и другие данные, полный список которых приводится в документации. Ссылки на документацию здесь.
Использование в приложении Mobile Vision API позволяет считывать штрих-коды в любом положении.
Важно отметить, что синтаксический разбор всех штрих-кодов выполняется локально, поэтому вам не нужно использовать соединение с сервером для чтения данных из кода. Например, при считывании линейного штрих-кода PDF-417, который может вместить до 1 КБ текста, можно сразу же получить всю закодированную в нем информацию.
Итак, для разработки приложения нам понадобится:
- Среда разработки Android Studio
- Смартфон на Android 4.2.2 или более поздней версии
- Последняя версия Android SDK, включая компонент SDK tools. Вы можете получить его с помощью Android SDK Manager в Android Studio.
- Google Play Services SDK. Вы можете получить его также в Android SDK Manager в Android Studio.
Создаем новый проект в Android Studio. При создании выбираем шаблон Empty Activity.
На следующем шаге нужно убедиться, что ваше приложение может использовать службы Google Play, в состав которых входит Mobile Vision API. Для этого нужно обновить файл build.gradle вашего проекта.
В секции зависимостей должны быть такие строки. Обновите Gradle при необходимости.
Службы Google Play часто обновляются, и чтобы получить последнюю версию, в Android Studio выберите инструменты > Android > SDK Manager.
Затем найдите строчку для сервисов Google Play и убедитесь, что у вас установлена версия 26 и выше. Если нет — установите компонент.
Теперь создадим пользовательский интерфейс.
В Android Studio выберите папку «res» и откройте ее вложенную папку «layout». Здесь вы увидите «activity_main.xml». Откройте его в редакторе макетов.
Вы можете видеть, что ваш макет содержит текстовое поле
. Нужно изменить макет, как показано ниже. Теперь здесь будет кроме текстового поля также кнопка и изображение. Для всех экранных компонентов прописываем идентификаторы, чтобы потом обращаться к ним в коде.
По нажатию на кнопку будет происходить загрузка и обработка изображения штрих-кода, которое будет отображаться в ImageView. После завершения обработки штрих-кода информация, считанная из него, будет отображаться в TextView.
Обычно приложения для считывания штрих-кодов получают изображение с камеры устройства, или обрабатывают превью камеры. Для реализации этого потребуется достаточно много кода, и в конце урока я покажу пример реализации такого приложения. Чтобы упростить этот пример, мы обработаем готовое изображение qr-кода, которое уже присутствует в вашем приложении.
Вот пример изображения qr-кода, которое вы можете скачать отсюда.
Назовите его qr.png и добавьте в папку проекта res/drawable.Android Studio обеспечит доступ к файлу в качестве ресурса с идентификатором: R.drawable.qr
Теперь перейдем к написанию кода приложения.
В файле MainActivity.java в методе onCreate добавьте следующий код.
Это настраивает обработчик событий (onClick), срабатывающий когда пользователь нажимает кнопку. Остальной код напишем в методе onClick.
Начнем с загрузки изображения штрих-кода. Сначала находим ImageView по идентификатору. Затем используется BitMapFactory для декодирования ресурса R.drawable.qr в растровое изображение. Полученное растровое изображение передаем ImageView.
Далее создаем экземпляр класса BarcodeDetector, используя Builder и настраиваем его на поиск QR-кодов и матрицы данных (есть много других типов штрих-кодов, которые он мог бы найти).
Вполне возможно, что первый раз наш детектор штрих-код сработает, когда служба Google Play еще не будет готова для обработки штрих-кодов. Поэтому мы должны проверить, что наш детектор работает, прежде чем использовать его. Если нет, нам придется ждать окончания загрузки или сообщить пользователям, что нужно найти подключение к Интернету или освободить место на устройстве. Прежде чем мы обратимся к текстовому полю, нужно объявить и найти его выше в методе onCreate.
Теперь допишем метод вывода сообщения.
Теперь, когда наш детектор создан и мы знаем, что он работает, создаем кадр из растрового изображения и передаем его детектору. Тот возвращает нам массив штрих-кодов SparseArray.
Обратите внимание, что Mobile Vision API способен обнаруживать несколько штрих-кодов в одном кадре. В этом случае массив SparseArray будет заполнен несколькими записями.
Обычно на этом этапе нужно пробежать по массиву SparseArray и обработать каждый штрих-код отдельно. Нужно предусмотреть возможность, что штрих-кодов может быть несколько, или ни одного. В нашем случае мы знаем, что у нас есть только 1 штрих-код, и можем прописать жесткий код для него. Для этого мы берем штрих-код, называемый «thisCode», который будет первым элементом в массиве. Затем присваиваем значение его поля rawValue текстовому полю textView — и все.
Теперь все, что вам нужно сделать, это запустить приложение.
Запускать лучше на реальном устройстве. На эмуляторе работать не будет, потому что на эмуляторах по умолчанию отсутствует сервис Google Play.
Вот приложение запустилось на устройстве, жмем кнопку. Если вы используете изображение штрих-кода qr.png, вы увидите в текстовом поле данные, закодированные в QR-код — это адрес нашего сайта fandroid.info.
Это был простой пример приложения, демонстрирующий работу Mobile Vision API. Но полноценный сканер штрих-кодов должен получать изображение с камеры устройства, или обрабатывать превью камеры.
Разработчики подготовили пример такого приложения на Github, вы можете скачать его код по ссылке.
Клонируйте или скачайте проект, и откройте в Android Studio модуль barcode-reader.
При запуске приложения из этого проекта мы можем увидеть, как оно работает. Первоначально открывается стартовый экран, на котором можно включить автофокус или вспышку. Кнопка считывания штрих-кода запускает камеру. Приложение отслеживает появление штрих-кодов на превью и рисует рамки на обнаруженных штрих-кодах. При нажатии на область обнаруженного штрих-кода превью закрывается, передавая при этом данные обнаруженного штрих-кода в текстовое поле на стартовом экране. Подробнее смотрите в видео.
Это приложение также использует Mobile Vision API. Но при рассмотрении проекта в Android Studio можно увидеть, что кода здесь побольше, чем в нашем простом примере.
Приложение состоит из восьми классов. Три из них отвечают за интерфейс и работу с камерой.
- Класс CameraSource предоставляет управление камерой для получения предварительного просмотра.
- Класс CameraSourcePreview отвечает за отображение превью на экране.
- Класс GraphicOverlay отображает графические объекты поверх связанного предварительного просмотра камеры.
- Класс MainActivity отображает стартовое окно с настройками и кнопкой запуска сканирования, и получает данные штрих-кода для размещения в TextView.
- Класс BarcodeTrackerFactory реализует паттерн «Фабрика» и используется для создания трекеров штрих-кода — по одному для каждого штрих-кода.
- Класс BarcodeGraphicTracker это трекер, который используется для обнаружения штрих-кодов на экране, и их отслеживания для наложения графики, а также удаления графики, когда штрих-код покидает зону видимости.
- Класс BarcodeGraphic используется для отрисовки экземпляра накладываемого на штрих-код изображения с учетом его положения, размера и идентификатора.
- Класс BarcodeCaptureActivity — это активити, которое запускается при нажатии кнопки считывания штрих-кода в стартовом окне приложения. Это активити отображает превью камеры и определяет штрих-коды на нем, выполнzет их считывание и наложение графических рамок на каждый штрих-код с помощью вышеперечисленных классов.
Я не буду в рамках этого урока углубляться в более подробное объяснение кода от разработчиков, а оставлю это вам в качестве домашнего задания. Тем более что код прекрасно документирован, каждый класс и метод содержит комментарии на английском языке. Читать и разбираться в таком коде очень полезно, особенно начинающему разработчику.
Источник