يمكنك استخدام ML Kit للتعرّف على الرموز الشريطية وفك ترميزها.
الميزة | غير مجمَّعة | مُجمَّعة |
---|---|---|
التنفيذ | يتم تنزيل النموذج بشكل ديناميكي من خلال "خدمات Google Play". | يتم ربط النموذج بشكل ثابت بتطبيقك في وقت الإنشاء. |
حجم التطبيق | زيادة في الحجم تبلغ حوالي 200 كيلوبايت | زيادة في الحجم تبلغ حوالي 2.4 ميغابايت |
وقت الإعداد | قد تحتاج إلى الانتظار إلى أن يتم تنزيل النموذج قبل استخدامه للمرة الأولى. | يتوفّر النموذج على الفور. |
جرّبه الآن
- يمكنك تجربة التطبيق النموذجي للاطّلاع على مثال على كيفية استخدام واجهة برمجة التطبيقات هذه.
- يمكنك الاطّلاع على تطبيق عرض Material Design لمعرفة كيفية تنفيذ واجهة برمجة التطبيقات هذه بشكل شامل.
قبل البدء
في ملف
build.gradle
على مستوى المشروع، احرص على تضمين مستودع Maven الخاص بـ Google في كل من القسمَينbuildscript
وallprojects
.أضِف العناصر التابعة لمكتبات ML Kit على Android إلى ملف Gradle على مستوى التطبيق في الوحدة، والذي يكون عادةً
app/build.gradle
. اختَر إحدى التبعيات التالية بناءً على احتياجاتك:لتضمين النموذج مع تطبيقك:
dependencies { // ... // Use this dependency to bundle the model with your app implementation 'com.google.mlkit:barcode-scanning:17.3.0' }
لاستخدام النموذج في "خدمات Google Play"، يجب استيفاء الشروط التالية:
dependencies { // ... // Use this dependency to use the dynamically downloaded model in Google Play Services implementation 'com.google.android.gms:play-services-mlkit-barcode-scanning:18.3.1' }
إذا اخترت استخدام النموذج في "خدمات Google Play"، يمكنك ضبط تطبيقك لتنزيل النموذج تلقائيًا على الجهاز بعد تثبيت تطبيقك من "متجر Play". لإجراء ذلك، أضِف البيان التالي إلى ملف
AndroidManifest.xml
في تطبيقك:<application ...> ... <meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="barcode" > <!-- To use multiple models: android:value="barcode,model2,model3" --> </application>
يمكنك أيضًا التحقّق بشكل صريح من توفّر النموذج وطلب تنزيله من خلال ModuleInstallClient API في "خدمات Google Play".
إذا لم تفعِّل عمليات تنزيل النماذج في وقت التثبيت أو لم تطلب تنزيلًا صريحًا، سيتم تنزيل النموذج عند تشغيل الماسح الضوئي للمرة الأولى. لن يؤدي تقديم طلبات قبل اكتمال عملية التنزيل إلى عرض أي نتائج.
إرشادات حول الصورة المدخَلة
-
لكي يتمكّن ML Kit من قراءة الرموز الشريطية بدقة، يجب أن تحتوي الصور المدخلة على رموز شريطية ممثّلة ببيانات بكسل كافية.
تعتمد متطلبات بيانات البكسل المحدّدة على نوع الرمز الشريطي وكمية البيانات المرمّزة فيه، لأنّ العديد من الرموز الشريطية تتيح حمولة متغيرة الحجم. بشكل عام، يجب أن يكون عرض أصغر وحدة ذات معنى في الرمز الشريطي بكسلَين على الأقل، وأن يكون ارتفاعها بكسلَين بالنسبة إلى الرموز الثنائية الأبعاد.
على سبيل المثال، تتكوّن الرموز الشريطية EAN-13 من أشرطة ومساحات بعرض وحدة واحدة أو وحدتَين أو 3 وحدات أو 4 وحدات، لذا من المفترض أن تحتوي صورة الرمز الشريطي EAN-13 على أشرطة ومساحات بعرض 2 و4 و6 و8 بكسل على الأقل. بما أنّ الرمز الشريطي EAN-13 يبلغ عرضه 95 وحدة إجمالاً، يجب أن يبلغ عرض الرمز الشريطي 190 بكسل على الأقل.
تتطلّب التنسيقات الأكثر كثافة، مثل PDF417، أبعادًا أكبر لوحدات البكسل كي يتمكّن ML Kit من قراءتها بشكل موثوق. على سبيل المثال، يمكن أن يتضمّن رمز PDF417 ما يصل إلى 34 "كلمة" بعرض 17 وحدة في صف واحد، ويجب أن يبلغ عرضه 1156 بكسل على الأقل.
-
يمكن أن يؤثر عدم وضوح الصورة في دقة الفحص. إذا لم يحصل تطبيقك على نتائج مقبولة، اطلب من المستخدم إعادة التقاط الصورة.
-
بالنسبة إلى التطبيقات العادية، ننصحك بتقديم صورة بدقة أعلى، مثل 1280x720 أو 1920x1080، ما يتيح إمكانية فحص الرموز الشريطية من مسافة أكبر من الكاميرا.
ومع ذلك، في التطبيقات التي يكون فيها وقت الاستجابة مهمًا، يمكنك تحسين الأداء من خلال التقاط الصور بدقة أقل، ولكن مع اشتراط أن يشكّل الرمز الشريطي الجزء الأكبر من صورة الإدخال. يمكنك أيضًا الاطّلاع على نصائح لتحسين الأداء في الوقت الفعلي.
1. ضبط إعدادات الماسح الضوئي للرموز الشريطية
إذا كنت تعرف تنسيقات الرموز الشريطية التي تتوقّع قراءتها، يمكنك تحسين سرعة أداة رصد الرموز الشريطية من خلال ضبطها على رصد هذه التنسيقات فقط.على سبيل المثال، لاكتشاف رمز Aztec ورموز الاستجابة السريعة فقط، أنشئ عنصر BarcodeScannerOptions
كما في المثال التالي:
Kotlin
val options = BarcodeScannerOptions.Builder() .setBarcodeFormats( Barcode.FORMAT_QR_CODE, Barcode.FORMAT_AZTEC) .build()
Java
BarcodeScannerOptions options = new BarcodeScannerOptions.Builder() .setBarcodeFormats( Barcode.FORMAT_QR_CODE, Barcode.FORMAT_AZTEC) .build();
تتوفّر التنسيقات التالية:
- Code 128 (
FORMAT_CODE_128
) - Code 39 (
FORMAT_CODE_39
) - الرمز 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
) - رمز الاستجابة السريعة (
FORMAT_QR_CODE
) - PDF417 (
FORMAT_PDF417
) - Aztec (
FORMAT_AZTEC
) - Data Matrix (
FORMAT_DATA_MATRIX
)
بدءًا من الإصدار 17.1.0 من النموذج المجمّع والإصدار 18.2.0 من النموذج غير المجمّع، يمكنك أيضًا استدعاء enableAllPotentialBarcodes()
لعرض جميع الرموز الشريطية المحتملة حتى إذا تعذّر فك تشفيرها. ويمكن استخدام هذه المعلومات لتسهيل عملية الرصد، مثلاً من خلال تكبير الصورة بالكاميرا للحصول على صورة أوضح لأي رمز شريطي في المربّع المحيط الذي تم عرضه.
Kotlin
val options = BarcodeScannerOptions.Builder() .setBarcodeFormats(...) .enableAllPotentialBarcodes() // Optional .build()
Java
BarcodeScannerOptions options = new BarcodeScannerOptions.Builder() .setBarcodeFormats(...) .enableAllPotentialBarcodes() // Optional .build();
Further on, starting from bundled library 17.2.0 and unbundled library 18.3.0, a new feature called auto-zoom has been introduced to further enhance the barcode scanning experience. With this feature enabled, the app is notified when all barcodes within the view are too distant for decoding. As a result, the app can effortlessly adjust the camera's zoom ratio to the recommended setting provided by the library, ensuring optimal focus and readability. This feature will significantly enhance the accuracy and success rate of barcode scanning, making it easier for apps to capture information precisely.
To enable auto-zooming and customize the experience, you can utilize the
setZoomSuggestionOptions()
method along with your
own ZoomCallback
handler and desired maximum zoom
ratio, as demonstrated in the code below.
Kotlin
val options = BarcodeScannerOptions.Builder() .setBarcodeFormats(...) .setZoomSuggestionOptions( new ZoomSuggestionOptions.Builder(zoomCallback) .setMaxSupportedZoomRatio(maxSupportedZoomRatio) .build()) // Optional .build()
Java
BarcodeScannerOptions options = new BarcodeScannerOptions.Builder() .setBarcodeFormats(...) .setZoomSuggestionOptions( new ZoomSuggestionOptions.Builder(zoomCallback) .setMaxSupportedZoomRatio(maxSupportedZoomRatio) .build()) // Optional .build();
zoomCallback
is required to be provided to handle whenever the library
suggests a zoom should be performed and this callback will always be called on
the main thread.
The following code snippet shows an example of defining a simple callback.
Kotlin
fun setZoom(ZoomRatio: Float): Boolean { if (camera.isClosed()) return false camera.getCameraControl().setZoomRatio(zoomRatio) return true }
Java
boolean setZoom(float zoomRatio) { if (camera.isClosed()) { return false; } camera.getCameraControl().setZoomRatio(zoomRatio); return true; }
maxSupportedZoomRatio
is related to the camera hardware, and different camera
libraries have different ways to fetch it (see the javadoc of the setter
method). In case this is not provided, an
unbounded zoom ratio might be produced by the library which might not be
supported. Refer to the
setMaxSupportedZoomRatio()
method
introduction to see how to get the max supported zoom ratio with different
Camera libraries.
When auto-zooming is enabled and no barcodes are successfully decoded within
the view, BarcodeScanner
triggers your zoomCallback
with the requested
zoomRatio
. If the callback correctly adjusts the camera to this zoomRatio
,
it is highly probable that the most centered potential barcode will be decoded
and returned.
A barcode may remain undecodable even after a successful zoom-in. In such cases,
BarcodeScanner
may either invoke the callback for another round of zoom-in
until the maxSupportedZoomRatio
is reached, or provide an empty list (or a
list containing potential barcodes that were not decoded, if
enableAllPotentialBarcodes()
was called) to the OnSuccessListener
(which
will be defined in step 4. Process the image).
2. Prepare the input image
To recognize barcodes in an image, create anInputImage
object
from either a Bitmap
, media.Image
, ByteBuffer
, byte array, or a file on
the device. Then, pass the InputImage
object to the
BarcodeScanner
's process
method.
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
private class YourImageAnalyzer : ImageAnalysis.Analyzer { override fun analyze(imageProxy: ImageProxy) { val mediaImage = imageProxy.image if (mediaImage != null) { val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees) // Pass image to an ML Kit Vision API // ... } } }
Java
private class YourAnalyzer implements ImageAnalysis.Analyzer { @Override public void analyze(ImageProxy imageProxy) { Image mediaImage = imageProxy.getImage(); if (mediaImage != null) { InputImage image = InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees()); // Pass image to an ML Kit Vision API // ... } } }
إذا لم تستخدم مكتبة كاميرا تمنحك درجة دوران الصورة، يمكنك احتسابها من درجة دوران الجهاز واتجاه مستشعر الكاميرا في الجهاز:
Kotlin
private val ORIENTATIONS = SparseIntArray() init { ORIENTATIONS.append(Surface.ROTATION_0, 0) ORIENTATIONS.append(Surface.ROTATION_90, 90) ORIENTATIONS.append(Surface.ROTATION_180, 180) ORIENTATIONS.append(Surface.ROTATION_270, 270) } /** * Get the angle by which an image must be rotated given the device's current * orientation. */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Throws(CameraAccessException::class) private fun getRotationCompensation(cameraId: String, activity: Activity, isFrontFacing: Boolean): Int { // Get the device's current rotation relative to its "native" orientation. // Then, from the ORIENTATIONS table, look up the angle the image must be // rotated to compensate for the device's rotation. val deviceRotation = activity.windowManager.defaultDisplay.rotation var rotationCompensation = ORIENTATIONS.get(deviceRotation) // Get the device's sensor orientation. val cameraManager = activity.getSystemService(CAMERA_SERVICE) as CameraManager val sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION)!! if (isFrontFacing) { rotationCompensation = (sensorOrientation + rotationCompensation) % 360 } else { // back-facing rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360 } return rotationCompensation }
Java
private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 0); ORIENTATIONS.append(Surface.ROTATION_90, 90); ORIENTATIONS.append(Surface.ROTATION_180, 180); ORIENTATIONS.append(Surface.ROTATION_270, 270); } /** * Get the angle by which an image must be rotated given the device's current * orientation. */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private int getRotationCompensation(String cameraId, Activity activity, boolean isFrontFacing) throws CameraAccessException { // Get the device's current rotation relative to its "native" orientation. // Then, from the ORIENTATIONS table, look up the angle the image must be // rotated to compensate for the device's rotation. int deviceRotation = activity.getWindowManager().getDefaultDisplay().getRotation(); int rotationCompensation = ORIENTATIONS.get(deviceRotation); // Get the device's sensor orientation. CameraManager cameraManager = (CameraManager) activity.getSystemService(CAMERA_SERVICE); int sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION); if (isFrontFacing) { rotationCompensation = (sensorOrientation + rotationCompensation) % 360; } else { // back-facing rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360; } return rotationCompensation; }
بعد ذلك، مرِّر العنصر media.Image
وقيمة درجة التدوير إلى InputImage.fromMediaImage()
:
Kotlin
val image = InputImage.fromMediaImage(mediaImage, rotation)
Java
InputImage image = InputImage.fromMediaImage(mediaImage, rotation);
استخدام معرّف الموارد المنتظم (URI) للملف
لإنشاء عنصر InputImage
من معرّف URI لملف، مرِّر سياق التطبيق ومعرّف URI للملف إلى
InputImage.fromFilePath()
. ويكون ذلك مفيدًا عند استخدام ACTION_GET_CONTENT
intent لطلب أن يختار المستخدم صورة من تطبيق المعرض.
Kotlin
val image: InputImage try { image = InputImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
Java
InputImage image; try { image = InputImage.fromFilePath(context, uri); } catch (IOException e) { e.printStackTrace(); }
استخدام ByteBuffer
أو ByteArray
لإنشاء عنصر InputImage
من ByteBuffer
أو ByteArray
، عليك أولاً حساب درجة دوران الصورة كما سبق توضيحه بشأن إدخال media.Image
.
بعد ذلك، أنشئ الكائن InputImage
باستخدام المخزن المؤقت أو المصفوفة، بالإضافة إلى ارتفاع الصورة وعرضها وتنسيق ترميز الألوان ودرجة التدوير:
Kotlin
val image = InputImage.fromByteBuffer( byteBuffer, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 ) // Or: val image = InputImage.fromByteArray( byteArray, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 )
Java
InputImage image = InputImage.fromByteBuffer(byteBuffer, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 ); // Or: InputImage image = InputImage.fromByteArray( byteArray, /* image width */480, /* image height */360, rotation, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 );
استخدام Bitmap
لإنشاء عنصر InputImage
من عنصر Bitmap
، عليك إجراء التصريح التالي:
Kotlin
val image = InputImage.fromBitmap(bitmap, 0)
Java
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
يتم تمثيل الصورة بكائن Bitmap
مع درجات التدوير.
3- الحصول على مثيل من BarcodeScanner
Kotlin
val scanner = BarcodeScanning.getClient() // Or, to specify the formats to recognize: // val scanner = BarcodeScanning.getClient(options)
Java
BarcodeScanner scanner = BarcodeScanning.getClient(); // Or, to specify the formats to recognize: // BarcodeScanner scanner = BarcodeScanning.getClient(options);
4. معالجة الصورة
مرِّر الصورة إلى طريقةprocess
:
Kotlin
val result = scanner.process(image) .addOnSuccessListener { barcodes -> // Task completed successfully // ... } .addOnFailureListener { // Task failed with an exception // ... }
Java
Task<List<Barcode>> result = scanner.process(image) .addOnSuccessListener(new OnSuccessListener<List<Barcode>>() { @Override public void onSuccess(List<Barcode> barcodes) { // Task completed successfully // ... } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Task failed with an exception // ... } });
5- الحصول على معلومات من الرموز الشريطية
في حال نجاح عملية التعرّف على الرمز الشريطي، يتم تمرير قائمة من عناصرBarcode
إلى أداة معالجة النجاح. يمثّل كل عنصر Barcode
رمزًا شريطيًا تم رصده في الصورة. يمكنك الحصول على إحداثيات المربّع المحيط لكل رمز شريطي في صورة الإدخال، بالإضافة إلى البيانات الأولية المرمّزة بواسطة الرمز الشريطي. بالإضافة إلى ذلك، إذا تمكّن قارئ الرموز الشريطية من تحديد نوع البيانات
المشفّرة بواسطة الرمز الشريطي، يمكنك الحصول على عنصر يحتوي على البيانات التي تم تحليلها.
على سبيل المثال:
Kotlin
for (barcode in barcodes) { val bounds = barcode.boundingBox val corners = barcode.cornerPoints val rawValue = barcode.rawValue val valueType = barcode.valueType // See API reference for complete list of supported types when (valueType) { Barcode.TYPE_WIFI -> { val ssid = barcode.wifi!!.ssid val password = barcode.wifi!!.password val type = barcode.wifi!!.encryptionType } Barcode.TYPE_URL -> { val title = barcode.url!!.title val url = barcode.url!!.url } } }
Java
for (Barcode barcode: barcodes) { Rect bounds = barcode.getBoundingBox(); Point[] corners = barcode.getCornerPoints(); String rawValue = barcode.getRawValue(); int valueType = barcode.getValueType(); // See API reference for complete list of supported types switch (valueType) { case Barcode.TYPE_WIFI: String ssid = barcode.getWifi().getSsid(); String password = barcode.getWifi().getPassword(); int type = barcode.getWifi().getEncryptionType(); break; case Barcode.TYPE_URL: String title = barcode.getUrl().getTitle(); String url = barcode.getUrl().getUrl(); break; } }
نصائح لتحسين الأداء في الوقت الفعلي
إذا كنت تريد مسح الرموز الشريطية في تطبيق يعمل في الوقت الفعلي، اتّبِع الإرشادات التالية لتحقيق أفضل معدّلات عرض اللقطات:
-
عدم تسجيل الإدخال بدقة الكاميرا الأصلية في بعض الأجهزة، يؤدي تسجيل الإدخال بدقة العرض الأصلية إلى إنشاء صور كبيرة جدًا (أكثر من 10 ميغابكسل)، ما يؤدي إلى حدوث تأخير كبير جدًا بدون أي فائدة من حيث الدقة. بدلاً من ذلك، اطلب فقط الحجم المطلوب من الكاميرا لرصد الرموز الشريطية، والذي لا يتجاوز عادةً 2 ميغابكسل.
إذا كانت سرعة المسح الضوئي مهمة، يمكنك خفض دقة التقاط الصور بشكل أكبر. ومع ذلك، يُرجى مراعاة الحد الأدنى لمتطلبات حجم الرمز الشريطي الموضّحة أعلاه.
إذا كنت تحاول التعرّف على الرموز الشريطية من سلسلة من لقطات فيديو يتم بثها، قد يعرض برنامج التعرّف نتائج مختلفة من لقطة إلى أخرى. عليك الانتظار إلى أن تحصل على سلسلة متتالية من القيمة نفسها لتتأكّد من أنّك تعرض نتيجة جيدة.
لا يتوفّر رقم المجموع الاختباري لتنسيقي ITF وCODE-39.
- إذا كنت تستخدم واجهة برمجة التطبيقات
Camera
أوcamera2
، عليك تقييد عدد طلبات البيانات من أداة الرصد. إذا توفّر إطار فيديو جديد أثناء تشغيل أداة رصد الحركة، تجاهِل الإطار. يمكنك الاطّلاع على فئةVisionProcessorBase
في نموذج تطبيق البدء السريع للحصول على مثال. - في حال استخدام واجهة برمجة التطبيقات
CameraX
، احرص على ضبط استراتيجية الضغط الخلفي على القيمة التلقائيةImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
. يضمن ذلك تسليم صورة واحدة فقط لتحليلها في كل مرة. إذا تم إنتاج المزيد من الصور عندما يكون المحلّل مشغولاً، سيتم إسقاطها تلقائيًا ولن يتم وضعها في قائمة انتظار للتسليم. بعد إغلاق الصورة التي يتم تحليلها من خلال استدعاء ImageProxy.close()، سيتم عرض أحدث صورة تالية. - إذا كنت تستخدم ناتج أداة رصد الوجوه لتراكب الرسومات على صورة الإدخال، احصل أولاً على النتيجة من "حزمة تعلُّم الآلة"، ثم اعرض الصورة والتراكب في خطوة واحدة. ويتم عرض هذا المحتوى على مساحة العرض مرة واحدة فقط لكل إطار إدخال. يمكنك الاطّلاع على الفئتين
CameraSourcePreview
وGraphicOverlay
في تطبيق العيّنة للبدء السريع للحصول على مثال. - إذا كنت تستخدم Camera2 API، التقط الصور بتنسيق
ImageFormat.YUV_420_888
. إذا كنت تستخدم الإصدار القديم من Camera API، التقط الصور بتنسيقImageFormat.NV21
.
إنّ محتوى هذه الصفحة مرخّص بموجب ترخيص Creative Commons Attribution 4.0 ما لم يُنصّ على خلاف ذلك، ونماذج الرموز مرخّصة بموجب ترخيص Apache 2.0. للاطّلاع على التفاصيل، يُرجى مراجعة سياسات موقع Google Developers. إنّ Java هي علامة تجارية مسجَّلة لشركة Oracle و/أو شركائها التابعين.
تاريخ التعديل الأخير: 2025-09-04 (حسب التوقيت العالمي المتفَّق عليه)