diff --git a/barcode/arabic/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/arabic/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..b7499b9b5 --- /dev/null +++ b/barcode/arabic/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-08-12 +description: مثال مولد الباركود يوضح كيفية إنشاء باركود بحجم بكسل دقيق. تعلم ضبط عرض + الوحدة، ارتفاع الشريط وإنشاء باركودات بلانيت. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: ar +lastmod: 2026-08-12 +og_description: يوضح مثال مولد الباركود كيفية إنشاء باركود بأبعاد بكسل دقيقة. اتبع + هذا الدليل للتحكم في عرض الوحدة وارتفاع الشريط لأكواد Planet و RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: مثال على مولد الباركود – تخصيص حجم البكسل في C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: مثال على مولد الباركود – دليل خطوة بخطوة لأحجام البكسل المخصصة +url: /ar/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# مثال مولد الباركود – دليل خطوة‑بخطوة لأحجام البكسل المخصصة + +إذا كنت بحاجة إلى **barcode generator example** يتيح لك التحكم في كل بكسل، يوضح لك هذا الدليل بالضبط كيفية القيام بذلك. ستتعلم كيفية ضبط عرض الوحدة، تعريف ارتفاع شريط ثابت، وإنشاء كل من باركود Planet وRM4SCC بأبعاد يمكن التنبؤ بها. + +معظم المطورين يواجهون صعوبة في “كيفية توليد صور الباركود” التي تبدو متطابقة على كل شاشة أو طابعة. تحل مقتطفات الشيفرة أدناه هذه المشكلة من خلال إظهار معلمات مستوى البكسل لمكتبة Aspose.BarCode for .NET، بحيث يمكنك إنتاج مخرجات ثابتة دون تخمين. + +## ما ستتعلمه + +* كيفية تثبيت حزمة NuGet المطلوبة. +* كيفية توليد باركود Planet مع ارتفاع يُحسب تلقائيًا. +* كيفية توليد باركود Planet بارتفاع صريح قدره 100 بكسل. +* كيفية توليد باركود RM4SCC باستخدام نفس الارتفاع الصريح. +* لماذا **barcode pixel size** مهم لموثوقية القراءة. +* نصائح لاستكشاف المشكلات الشائعة عند توليد صور باركود Planet. + +كل ما تحتاجه هو .NET 6 أو أحدث، بيئة تطوير C# أساسية، واتصال بالإنترنت لجلب حزمة NuGet. + +--- + +## مثال مولد الباركود – إعداد بيئة التطوير + +قبل كتابة أي شيفرة، تأكد من أن مكتبة Aspose.BarCode متاحة لمشروعك. + +### تثبيت حزمة Aspose.BarCode + +افتح الطرفية في مجلد مشروعك وشغّل: + +```bash +dotnet add package Aspose.BarCode +``` + +يضيف الأمر أحدث نسخة مستقرة من **Aspose.BarCode** إلى ملف `csproj` الخاص بك. بعد انتهاء الاستعادة، يمكنك البدء في استخدام الفئة `BarcodeGenerator`. + +> **نصيحة احترافية:** استهدف .NET 6 أو .NET 7 للاستفادة من أحدث تحسينات الأداء ومعالجة UTF‑8 الافتراضية. + +### إضافة توجيهات `using` اللازمة + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +هذه المساحات الاسم تُظهر الفئة `BarcodeGenerator` والعدد `BarCodeImageFormat` المستخدم لاحقًا في الدليل. + +--- + +## كيفية توليد باركود بحجم بكسل مخصص + +الخطوات الثلاث التالية توضح مثال **barcode generator example** الكامل. كل خطوة تبني على السابقة، بحيث يمكنك نسخ‑لصق الكتلة بالكامل إلى تطبيق كونسول وتشغيله دون تعديل. + +### الخطوة 1 – توليد باركود Planet مع ارتفاع يُحسب تلقائيًا + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**لماذا يعمل هذا:** +*خاصية `XDimension` تُحدد عرض وحدة الباركود الواحدة (أصغر عنصر أسود أو أبيض). عندما تُهمل `BarHeight`، تحسب المكتبة ارتفاعًا يحافظ على نسبة الأبعاد القياسية لرموز Planet.* + +**الناتج المتوقع:** ملف PNG اسمه `PlanetAuto.png` يحتوي على باركود Planet نظيف. ارتفاعه يتكيف مع عرض الوحدة البالغ 4 بكسل، عادةً حوالي 60 بكسل لحمولة مكوّنة من ستة أحرف. + +### الخطوة 2 – توليد باركود Planet بارتفاع صريح قدره 100 بكسل + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**لماذا قد تحتاج ذلك:** +أحيانًا يتطلب جهاز المسح ارتفاعًا أدنى للشرائط لضمان اكتشاف موثوق. بتعيين `BarHeight.Pixels`، تضمن أن كل صورة مُولَّدة تفي بهذا المتطلب، بغض النظر عن طول البيانات المشفرة. + +**الناتج المتوقع:** `PlanetHeight100.png` يعرض نفس البيانات كما في السابق، لكن الشرائط ارتفاعها بالضبط 100 بكسل، مما يمنحك سيطرة كاملة على الحجم البصري. + +### الخطوة 3 – توليد باركود RM4SCC بنفس الارتفاع الصريح + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**لماذا هذا مهم:** +`EncodeTypes.RM4SCC` هو باركود خطي مكدس يُستخدم في اللوجستيات. مطابقة ارتفاعه مع باركود Planet يبسط المعالجة الدفعية عندما تظهر كلتا الرموز على نفس الملصق. + +**الناتج المتوقع:** `RM4SCCHeight100.png` يعرض باركود RM4SCC بحجم مثالي، مطابق للارتفاع الصريح 100 بكسل الذي ضبطته لرمز Planet. + +> **التحقق من النتيجة:** افتح كل ملف PNG في عارض صور وتأكد من أن الشرائط السوداء عرضها بالضبط 4 بكسل، وأن الارتفاع حيث حُدد هو 100 بكسل. يمكنك أيضًا تمرير الملفات إلى تطبيق ماسح باركود للتأكد من أنها تُفكّ الشيفرة إلى “123456”. + +--- + +## فهم حجم بكسل الباركود وارتفاع الشريط + +### ما هو **barcode pixel size**؟ + +*حجم البكسل* يشير إلى عدد البكسلات الفعلية على الشاشة أو الطابعة التي تمثل وحدة واحدة (`XDimension`). كلما زاد حجم البكسل، زاد حجم الباركود، مما قد يسهل القراءة على الماسحات منخفضة الدقة لكنه يستهلك مساحة أكبر على الملصق. + +### كيف يؤثر `BarHeight` على قابلية القراءة؟ + +خاصية `BarHeight` تتحكم في الطول العمودي للشرائط. المعايير لمعظم الباركودات أحادية البعد (بما فيها Planet وRM4SCC) توصي بارتفاع أدنى 10 مم عند الطباعة بدقة 300 dpi، وهو ما يساوي تقريبًا 118 بكسل. ضبط ارتفاع أقل من ذلك قد يسبب أخطاء قراءة، خاصةً على كاميرات الهواتف المحمولة. + +### متى تدع المكتبة تحسب الارتفاع تلقائيًا؟ + +إذا كنت تولد باركودات للعرض على الشاشة فقط، فإن الحساب التلقائي يحافظ على نسبة الأبعاد ويقلل الحاجة إلى تعديل يدوي. بالنسبة للملصقات المطبوعة التي يجب أن تلتزم بمواصفات ISO الصارمة، يجب عليك **تعيين ارتفاع الشريط صراحة**. + +--- + +## المشكلات الشائعة وأفضل الممارسات عند توليد باركود Planet + +| المشكلة | السبب | الحل | +|---------|-------|------| +| الشرائط تبدو رفيعة جدًا أو سميكة | ترك `XDimension` على القيمة الافتراضية (1 بكسل) على شاشات عالية الدقة | ضبط `XDimension.Pixels` إلى ما لا يقل عن 3‑4 لتحسين الوضوح | +| الماسح لا يستطيع قراءة الرمز | `BarHeight` صغير جدًا بالنسبة لبُعد تركيز الماسح | استخدم `BarHeight.Pixels` ≥ 100 لمعظم الماسحات المحمولة | +| الصورة مشوشة بعد التكبير | حفظها كـ JPEG يضيف تشويشًا نتيجة الضغط | احفظها كـ PNG (`BarCodeImageFormat.Png`) للحصول على إخراج بلا فقد | +| نوع الباركود غير متوقع | قيمة خاطئة في تعداد `EncodeTypes` | تأكد من استخدام `EncodeTypes.Planet` لرمز Planet | + +### نصيحة احترافية حول الأداء + +عند توليد آلاف الباركودات في مهمة دفعة، أعد استخدام كائن `BarcodeGenerator` واحد فقط وقم بتغيير `CodeText` ومعلمات الحجم بين عمليات الحفظ. هذا يتجنب تخصيص كائنات داخلية متكررة ويمكن أن يقلل زمن التنفيذ حتى 30 ٪. + +--- + +## مثال كامل يعمل – جمع كل شيء معًا + +أنشئ مشروع كونسول جديد (`dotnet new console -n BarcodeDemo`) واستبدل محتوى `Program.cs` بما يلي: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +شغّل البرنامج باستخدام `dotnet run`. بعد التنفيذ ستجد ثلاثة ملفات PNG في مجلد المشروع، كلٌ يوضح سيناريو مختلف من **barcode generator example**. + +--- + +## الخطوات التالية والمواضيع ذات الصلة + +* **كيفية توليد باركود بصيغ أخرى** – استكشف `EncodeTypes.Code128`، `EncodeTypes.QR`، و`EncodeTypes.DataMatrix` للاحتياجات ثنائية الأبعاد. +* **دمج الباركودات في ملفات PDF** – اجمع Aspose.BarCode مع Aspose.PDF لوضع الباركود مباشرةً على قوالب الفواتير. +* **حجم باركود ديناميكي بناءً على إدخال المستخدم** – احسب + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مصدر يتضمن أمثلة شيفرة كاملة مع شروحات خطوة‑بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/arabic/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/arabic/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..90034468f --- /dev/null +++ b/barcode/arabic/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: قم بتكوين تخطيط الباركود Databar في بايثون بسرعة. تعلّم كيفية تعيين الأعمدة + والصفوف وحفظ الصور باستخدام مكتبة مولّد الباركود. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: ar +lastmod: 2026-08-12 +og_description: قم بتكوين تخطيط الباركود Databar في بايثون للتحكم في الأعمدة والصفوف + وإخراج الصورة. اتبع هذا الدليل للحصول على حل جاهز للتنفيذ. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: تكوين تخطيط الباركود Databar في بايثون – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: تكوين تخطيط الباركود Databar في بايثون – دليل خطوة بخطوة +url: /ar/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تكوين تخطيط الباركود Databar في بايثون – دليل خطوة بخطوة + +إذا كنت بحاجة إلى **configure Databar barcode layout in Python**، فهذا الدليل يشرح لك العملية بالكامل. ستتعرف على كيفية ضبط عدد الأعمدة أو الصفوف لباركود Databar Expanded Stacked وكيفية حفظ الصورة الناتجة باستدعاء واحد لمكتبة مولد الباركود. + +التحكم في التخطيط أمر أساسي عندما تقوم بدمج الباركود على عبوات ضيقة، إيصالات، أو شاشات الهواتف المحمولة. في الأقسام أدناه سنغطي الاستيرادات المطلوبة، خيارَي التخطيط (الأعمدة والصفوف)، وأفضل الممارسات لحفظ صورة PNG نظيفة. + +## ما ستحتاجه + +* Python 3.8 أو أحدث +* `aspose.barcode` (أو أي حزمة توليد باركود متوافقة) مثبتة + ```bash + pip install aspose-barcode + ``` +* صلاحية كتابة في مجلد سيتم تخزين ملفات PNG فيه + +لا توجد أدوات خارجية إضافية مطلوبة—المكتبة تتعامل مع التصيير، التحجيم، وترميز الصورة داخليًا. + +## كيفية تكوين تخطيط الباركود Databar في بايثون + +جوهر الحل هو الفئة `BarcodeGenerator`. تقبل تعداد `EncodeTypes` الذي يحدد نوع الباركود—في هذه الحالة `EncodeTypes.DatabarExpandedStacked`. بعد إنشاء المولد يمكنك تعديل التخطيط عن طريق ضبط خصائص `columns` أو `rows` في كائن معلمة `data_bar`. + +### الخطوة 1: استيراد الفئات المطلوبة + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +هذه الاستيرادات تمنحك الوصول إلى المولد، التعداد لأنواع Databar، وثابت صيغة صورة PNG. + +### الخطوة 2: إنشاء مولد باركود لـ Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*لماذا هذه الخطوة؟* +`EncodeTypes.DatabarExpandedStacked` يخبر المكتبة بإنتاج رموز **Databar Expanded Stacked**، التي تدعم سلاسل رقمية أطول مع الحفاظ على بصمة مدمجة. الوسيط الثاني هو البيانات التي سيتم ترميزها؛ يمكن أن تكون أي سلسلة تفي بمواصفات Databar. + +### الخطوة 3: ضبط عدد الأعمدة (تخطيط أفقي) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** هي العبارة المفتاحية لهذه العملية. عندما تزيد عدد الأعمدة، ينتشر الباركود أفقيًا، مما قد يكون مفيدًا للملصقات العريضة. المكتبة تعيد حساب عرض الوحدة تلقائيًا للحفاظ على حجم إجمالي ثابت. + +#### نصيحة احترافية +الحد الأقصى لعدد الأعمدة في Databar Expanded Stacked هو 8. ضبط قيمة أعلى من الحد سيقيدها إلى الحد الأقصى، ولكن من الأفضل التحقق من صحة الإدخال مسبقًا. + +### الخطوة 4: حفظ صورة الباركود بتخطيط الأعمدة + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** هو الإجراء الذي يكتب الباركود المصدَّر إلى القرص. PNG صيغة غير مضغوطة، مما يحافظ على الحواف الحادة المطلوبة للمسح الموثوق. + +### الخطوة 5: إنشاء مولد ثانٍ لنفس نوع الباركود (تخطيط صفوف) + +إذا كنت تفضل تكدسًا عموديًا، فستعمل مع الصفوف بدلاً من الأعمدة. الكود أدناه يعيد استخدام نفس القيمة لكنه ينشئ نسخة جديدة من `BarcodeGenerator` لتجنب خلط إعدادات الأعمدة والصفوف. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### الخطوة 6: ضبط عدد الصفوف (تخطيط عمودي) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** ترتب وحدات الباركود عموديًا. تخطيط من ثلاثة صفوف يقلل ارتفاع كل مجموعة فردية، مما يجعل الباركود مناسبًا للإيصالات الضيقة أو شاشات الهواتف المحمولة. + +#### حالة خاصة +إذا ضبطت `rows` إلى 1، فإن المكتبة تُنشئ Databar صفًا واحدًا (ما يعادل Databar القياسي). القيم الأقل من 1 تُتجاهل وتُعاد إلى الإعداد الافتراضي (صف واحد). + +### الخطوة 7: حفظ صورة الباركود بتخطيط الصفوف + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +مرة أخرى، نحن **save barcode image** باستخدام PNG للحفاظ على وضوح النتيجة. + +## مثال كامل قابل للتنفيذ + +جمع كل الأجزاء معًا يمنحك سكريبت مستقل يمكنك إدراجه في أي مشروع بايثون. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**الناتج المتوقع** + +تشغيل السكريبت ينشئ ملفين PNG: + +* `output/ExpandedCols4.png` – باركود ممتد عبر أربعة أعمدة +* `output/ExpandedRows3.png` – باركود مضغوط في ثلاثة صفوف + +يمكن فتح كلتا الصورتين في أي عارض صور أو استيرادهما مباشرةً إلى فواتير PDF، قوالب الملصقات، أو صفحات الويب. + +## الأسئلة الشائعة واستكشاف الأخطاء وإصلاحها + +| السؤال | الإجابة | +|----------|--------| +| *ماذا لو كان الباركود غير واضح؟* | زيادة دقة الصورة عن طريق ضبط `barcode_generator.parameters.image_width` و `image_height` قبل استدعاء `save`. | +| *هل يمكنني استخدام صيغ صور أخرى؟* | نعم. استبدل `BarCodeImageFormat.Png` بـ `Jpeg` أو `Bmp` أو `Gif` حسب الحاجة. | +| *هل هناك حد لطول البيانات؟* | Databar Expanded Stacked يدعم حتى 74 حرفًا رقميًا. تجاوز الحد يرفع استثناء `ArgumentException`. | +| *كيف يمكنني تغيير لون المقدمة؟* | استخدم `barcode_generator.parameters.barcode.color = Color.Blue` (استورد `System.Drawing.Color`). | +| *هل يمكنني دمج الأعمدة والصفوف؟* | لا. الـ API يعامل الأعمدة والصفوف كأنماط تخطيط متعارضة. اختر أحدهما لكل مثال باركود. | + +## الخطوات التالية + +الآن بعد أن يمكنك **configure Databar barcode layout**، فكر في استكشاف المواضيع ذات الصلة التالية: + +* **إضافة تسميات نصية** – استخدم `barcode_generator.parameters.barcode.code_text` لعرض القيمة المشفرة أسفل الصورة. +* **دمج الباركود في PDF** – اجمع PNG المُولد مع `aspose.pdf` لإنشاء مستندات قابلة للطباعة. +* **تحجيم ديناميكي** – احسب عدد الأعمدة أو الصفوف المثالي بناءً على أبعاد الملصق أثناء التشغيل. +* **معالجة دفعات** – كرر عبر ملف CSV لأكواد المنتجات لتوليد مكتبة من صور الباركود تلقائيًا. + +جرّب قيمًا مختلفة للأعمدة والصفوف لترى كيف تؤثر على موثوقية المسح على أجهزتك المستهدفة. كلما اختبرت أكثر، كلما فهمت أفضل التوازنات بين حجم الباركود، قابليته للقراءة، وقيود المساحة. + +--- + +*برمجة سعيدة! إذا وجدت هذا الدليل مفيدًا، شاركه مع زملائك أو اترك تعليقًا حول تحديات التخطيط التي واجهتها.* + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة شفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Create barcode image c# – Configure Codablock F Rows & Columns](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [One-Dimensional Databar Barcode Height Adjustment](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/arabic/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/arabic/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..bfd1de1e5 --- /dev/null +++ b/barcode/arabic/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,228 @@ +--- +category: general +date: 2026-08-12 +description: إنشاء صورة الباركود في C# باستخدام BarCodeGenerator. تعلّم كيفية توليد + DataBar، التحكم في حجم صورة الباركود، وإنشاء عدة باركودات بكفاءة. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: ar +lastmod: 2026-08-12 +og_description: إنشاء صورة الباركود في C# باستخدام BarCodeGenerator. يوضح هذا الدليل + خطوة بخطوة كيفية إنشاء رموز DataBar، وضبط حجم صورة الباركود، وإنتاج عدة باركودات. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: إنشاء صورة باركود في C# – دليل BarCodeGenerator الكامل +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: إنشاء صورة باركود في C# باستخدام BarCodeGenerator +url: /ar/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء صورة باركود في C# باستخدام BarCodeGenerator + +إذا كنت بحاجة إلى **إنشاء صورة باركود** في تطبيق .NET، يوضح لك هذا الدليل بالضبط كيفية القيام بذلك باستخدام فئة `BarCodeGenerator`. سواءً كنت تبني نظام نقاط بيع تجزئة أو أداة تتبع مخزون، ستتعلم كيفية إنشاء رموز DataBar، والتحكم في حجم صورة الباركود، وإنتاج عدة باركودات في تشغيل واحد. + +ستكتشف أيضًا كيف يتيح لك API **barcode generator c#** تعديل الأبعاد، وتبديل صيغ الإخراج، ومعالجة الحالات الخاصة مثل سلاسل البيانات غير الصالحة. بنهاية الدليل يمكنك بثقة **إنشاء عدة باركودات** دون كتابة كود متكرر. + +## المتطلبات المسبقة + +- .NET 6.0 أو أحدث مثبت +- بيئة تطوير (Visual Studio، Rider، أو VS Code) +- حزمة NuGet Aspose.BarCode for .NET (أو أي مكتبة متوافقة توفر `BarCodeGenerator`) + +```bash +dotnet add package Aspose.BarCode +``` + +## ما يغطيه هذا الدليل + +1. إعداد مثيل **barcode generator c#** لتشفير DataBar Omni‑directional. +2. تعديل **حجم صورة الباركود** عن طريق تغيير X‑dimension وارتفاع الشريط. +3. استخدام حلقة **إنشاء عدة باركودات** بأارتفاعات مختلفة. +4. حفظ الصور كملفات PNG والتحقق من النتيجة. + +![Create barcode image example](barcode-example.png){alt="مثال على إنشاء صورة باركود"} + +## الخطوة 1: تهيئة المُولد – أساسيات إنشاء صورة الباركود + +الخطوة الأولى هي إنشاء كائن `BarCodeGenerator` باستخدام الترميز المطلوب. للحصول على رمز DataBar Omni‑directional تستخدم `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**لماذا هذا مهم:** إنشاء المُولد يحدد قواعد الترميز وبيانات الحمولة. إذا تجاهلت قيمة `EncodeTypes` الصحيحة، ستنتج المكتبة باركود غير مدعوم أو ستطرح استثناءً. + +## الخطوة 2: ضبط X‑dimension وارتفاع الشريط – التحكم في حجم صورة الباركود + +الحجم البصري للباركود يتحكم فيه معاملان: + +| Parameter | ما يتحكم فيه | النطاق المعتاد | +|-----------|--------------|----------------| +| `x_dimension.pixels` | عرض أصغر وحدة (النقطة) | 1 – 4 px | +| `bar_height.pixels` | ارتفاع الشرائط العمودية | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**نصيحة احترافية:** X‑dimension أصغر ينتج صورة ذات دقة أعلى ولكن قد يكون من الصعب مسحها على طابعات منخفضة الجودة. اضبط القيمة بناءً على جهاز المسح المستهدف. + +## الخطوة 3: حفظ أول باركود – إنشاء صورة باركود بارتفاع 30 px + +الآن يمكنك توليد الصورة وكتابتها إلى القرص. طريقة `Save` تقبل مسار ملف وتعداد صيغة الصورة. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**النتيجة المتوقعة:** ملف PNG باسم `Databar30.png` يظهر في `C:\Barcodes`. فتح الملف يظهر رمز DataBar Omni‑directional بنمط واضح وعالي التباين. + +## الخطوة 4: تغيير الارتفاع وتوليد صور إضافية – إنشاء عدة باركودات + +لـ **إنشاء عدة باركودات** بأبعاد مختلفة تحتاج فقط إلى تعديل خاصية `BarHeight` واستدعاء `Save` مرة أخرى. هذا يتجنب إعادة إنشاء المُولد، مما يوفر الذاكرة ووقت المعالج. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**لماذا هذا يعمل:** كائن `BarCodeGenerator` يحتفظ بجميع إعدادات التكوين. تعديل خاصية واحدة يحدث محرك الرسم للنداء التالي لـ `Save`، مما يتيح لك **إنشاء عدة باركودات** بكفاءة. + +## الخطوة 5: متقدم – كيفية توليد DataBar ببيانات مخصصة + +المثال أعلاه يستخدم حمولة GS1 ثابتة. في السيناريوهات الواقعية غالبًا ما تحتاج إلى تضمين معرفات منتجات متغيرة. المكتبة تقبل أي سلسلة تتطابق مع مواصفات DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**نقطة رئيسية:** ضبط `generator.CodeText` يحدث البيانات المشفرة دون إعادة إنشاء الكائن. هذا هو النمط الموصى به لـ **how to generate databar** عند التعامل مع مجموعات بيانات كبيرة. + +## الخطوة 6: التحقق وحل المشكلات – التأكد من صحة حجم صورة الباركود + +بعد توليد الصور، قد ترغب في التأكد برمجياً من أن الأبعاد تطابق توقعاتك. فئة `Image` من `System.Drawing` يمكنها قراءة الملف وإبلاغ حجمه. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +إذا لم يعكس الارتفاع القيمة التي ضبطتها، تحقق من: + +- **X‑dimension**: قيمة صغيرة جدًا قد تتسبب في تقريب الارتفاع من قبل المُعالج. +- **Image format**: بعض الصيغ (مثل JPEG) تطبق ضغطًا قد يغيّر أبعاد البكسل عند الحفظ. PNG يحافظ على الأبعاد الدقيقة. + +## الخطوة 7: أفضل الممارسات لحجم صورة الباركود والأداء + +| التوصية | السبب | +|----------------|--------| +| احتفظ بـ `x_dimension.pixels` بين 2 – 3 px لمعظم الماسحات. | يوفر توازنًا بين قابلية القراءة وحجم الملف. | +| استخدم PNG للإخراج غير الفاقد عندما سيتم طباعة الصورة. | يضمن أبعادًا دقيقة وحوافًا حادة. | +| أعد استخدام كائن `BarCodeGenerator` واحد عند توليد العديد من الباركودات. | يقلل من عبء تخصيص الكائنات. | +| تحقق من صحة سلسلة الإدخال وفقًا لمعيار GS1 قبل تعيينها إلى `CodeText`. | يمنع الاستثناءات أثناء التشغيل والقراءات غير الصالحة. | +| احفظ الصور المولدة في مجلد مخصص مع تسمية واضحة (مثال: `Databar_{GTIN}.png`). | يبسط المعالجة اللاحقة ومسارات التدقيق. | + +## مثال كامل يعمل + +فيما يلي البرنامج الكامل الذي يدمج جميع الخطوات من التهيئة حتى التحقق. انسخ الكود إلى مشروع وحدة تحكم جديد وشغّله. + + + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة تعمل مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [إنشاء صورة باركود – قسيمة GS1 UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [إنشاء صورة باركود DotCode – الصفوف والأعمدة (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [كيفية إنشاء منطقة هادئة للباركود ITF-14 باستخدام Aspose.BarCode لـ .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/arabic/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/arabic/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..ffc8b3924 --- /dev/null +++ b/barcode/arabic/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-08-12 +description: أنشئ شريط بيانات متعدد الاتجاهات باستخدام بايثون وتعلم كيفية إنشاء صورة + باركود بايثون باستخدام Aspose.BarCode. اتبع الدليل خطوة بخطوة للحصول على حل كامل. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: ar +lastmod: 2026-08-12 +og_description: أنشئ شريط بيانات متعدد الاتجاهات باستخدام بايثون وقم بإنشاء صورة باركود + بايثون في دقائق. يوضح هذا الدرس مثالًا كاملاً قابلاً للتنفيذ. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: إنشاء شريط بيانات متعدد الاتجاهات – دليل بايثون كامل +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: إنشاء صورة شريط بيانات وشيفرة شريطية متعددة الاتجاهات في بايثون +url: /ar/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء Omni-directional Databar وصورة الباركود في Python + +إذا كنت بحاجة إلى **create omni directional databar** في مشروع Python، يوضح لك هذا الدليل كيفية القيام بذلك وأيضًا كيفية **create barcode image python** باستخدام مكتبة Aspose.BarCode. ستحصل على برنامج جاهز للتنفيذ ينتج ملفين PNG بأبعاد نسبية مختلفة. + +إنشاء DataBar يتبع مواصفات Omni‑directional هو طلب شائع لتطبيقات التجزئة واللوجستيات. يغطي الدرس التثبيت، تكوين X‑dimension، ضبط نسبة العرض إلى الارتفاع، وحفظ الصور النهائية. لا توجد خدمات خارجية مطلوبة؛ كل شيء يعمل محليًا. + +## ما ستحتاجه + +قبل أن تبدأ، تأكد من أن لديك: + +* Python 3.8 أو أحدث مثبت على جهازك. +* الوصول إلى الطرفية أو موجه الأوامر. +* صلاحية كتابة في المجلد الذي سيتم حفظ صور الباركود فيه. + +الاعتماد الوحيد من طرف ثالث هو **Aspose.BarCode for Python via .NET**, الذي يدعم نوع Omni‑directional DataBar مباشرةً. + +## الخطوة 1: تثبيت Aspose.BarCode للـ Python + +توفر Aspose.BarCode الفئة `BarcodeGenerator` المستخدمة في مثال الشيفرة. قم بتثبيت الحزمة باستخدام `pip`: + +```bash +pip install aspose-barcode +``` + +تتضمن الحزمة الروابط اللازمة لوقت تشغيل .NET، لذا لا تحتاج إلى تثبيت .NET SDK بشكل منفصل. + +## الخطوة 2: استيراد المكتبة وإنشاء المولد + +السطر الأول من البرنامج ينشئ مولدًا لـ stacked Omni‑directional DataBar. يتم استخدام قيمة GTIN‑14 `(01)12345678901231` كبيانات تجريبية. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*لماذا هذه الخطوة مهمة*: الثابت `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` يخبر المكتبة بترميز القيمة كـ Omni‑directional DataBar، وهو التنسيق المطلوب من قبل العديد من ماسحات نقاط البيع. + +## الخطوة 3: ضبط X‑dimension (عرض الوحدة) + +تحدد X‑dimension عرض أصغر وحدة شريط. قيمة `2` بكسل تنتج باركود واضحًا وقابلًا للقراءة دون حجم ملف مفرط. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*لماذا هذه الخطوة مهمة*: ضبط X‑dimension يتيح لك موازنة قابلية القراءة وأبعاد الصورة. قد يؤدي X‑dimension صغير جدًا إلى ظهور ضعيف على الطابعات منخفضة الدقة. + +## الخطوة 4: تكوين نسبة العرض إلى الارتفاع وحفظ الصورة الأولى + +نسبة العرض إلى الارتفاع تؤثر على ارتفاع DataBar الكلي بالنسبة لعرضه. نسبة `15` تخلق نمطًا بصريًا مدمجًا. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **نصيحة احترافية**: استخدم `pathlib.Path` لبناء مسار الإخراج، والذي ينشئ المجلدات المفقودة تلقائيًا. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## الخطوة 5: تغيير نسبة العرض إلى الارتفاع لنمط بصري ثانٍ وحفظ صورة أخرى + +تغيير نسبة العرض إلى الارتفاع إلى `30` ينتج باركودًا أطول قد يتطلبه بعض أجهزة الماسحات المحددة. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*لماذا هذه الخطوة مهمة*: تجار التجزئة المختلفون وأجهزة المسح لديها قيود حجم مختلفة. توفير كلتا النسبتين في برنامج واحد يتيح لك إنشاء النمط الدقيق الذي تحتاجه دون تكرار الشيفرة. + +## البرنامج الكامل – create omni directional databar و create barcode image python + +فيما يلي المثال الكامل القابل للتنفيذ الذي يدمج جميع الخطوات السابقة. احفظه باسم `generate_databar.py` وشغّله باستخدام `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### النتيجة المتوقعة + +تشغيل البرنامج ينشئ الملفات التالية: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +كلا الصورتين تعرضان Omni‑directional DataBar صالح يمكن مسحه بواسطة معدات التجزئة القياسية. + +![مثال على إنشاء شريط بيانات Omni-directional وصورة باركود في Python](example_databar.png "إنشاء شريط بيانات Omni-directional وصورة باركود في Python") + +*الصورة أعلاه هي عنصر نائب يوضح ملفي PNG المحفوظين.* + +## معالجة المشكلات الشائعة + +| المشكلة | السبب | الحل | +|-------|--------|-----| +| `ImportError: No module named aspose` | لم يتم تثبيت Aspose.BarCode أو تم تثبيته في بيئة مختلفة. | فعّل البيئة الافتراضية الصحيحة وشغّل `pip install aspose-barcode`. | +| `PermissionError` when saving | البرنامج يفتقر إلى صلاحية الكتابة للمجلد المستهدف. | اختر دليلًا تملكه أو شغّل البرنامج بصلاحيات مناسبة. | +| Barcode does not scan | X‑dimension منخفض جدًا أو نسبة العرض إلى الارتفاع غير متوافقة مع الماسح. | زد قيمة `x_dimension.pixels` إلى 3 أو 4، واختبر قيمًا مختلفة لـ `aspect_ratio` (مثلاً 20، 25). | +| Missing .NET runtime | Aspose.BarCode يعتمد على وقت تشغيل .NET على Windows/Linux. | ثبّت أحدث وقت تشغيل .NET من موقع Microsoft؛ توثيق الحزمة يوفر إرشادات خاصة بالمنصات. | + +## توسيع المثال + +يمكنك تعديل البرنامج لتوليد متغيرات DataBar أخرى (مثل `DATABAR_STACKED`، `DATABAR_EXPANDED`). استبدل الثابت `EncodeTypes` وفقًا لذلك: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +إذا كنت بحاجة إلى تضمين الباركود في PDF، يمكن لـ Aspose.PDF للـ Python استيراد ملف PNG مباشرةً أو يمكنك استخدام طريقة `save` مع `BarCodeImageFormat.Pdf`. + +## الخلاصة + +أظهر هذا الدرس كيفية **create omni directional databar** وكيفية **create barcode image python** باستخدام Aspose.BarCode. لديك الآن برنامج كامل وقابل لإعادة الإنتاج يولد ملفي PNG بأبعاد نسبية مختلفة، ويتعامل مع المشكلات الشائعة، ويمكن توسيعه لتنسيقات باركود أخرى. + +بعد ذلك، استكشف إنشاء رموز QR، إضافة الباركود إلى فواتير PDF، أو أتمتة المعالجة الدفعية لكاتالوجات الكبيرة للمنتجات. كل من هذه المواضيع يبني على نمط `BarcodeGenerator` نفسه الموضح هنا. برمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +- [إنشاء صورة باركود – قسيمة GS1 UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [إنشاء صورة باركود DotCode – الصفوف والأعمدة (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [كيفية إنشاء صورة باركود وعرضها في Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/arabic/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/arabic/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..8a0c75f68 --- /dev/null +++ b/barcode/arabic/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: كيفية إنشاء الباركود بسرعة باستخدام بايثون. تعلم كيفية إنشاء باركود من + البيانات وتصدير صورة الباركود باستخدام مكتبة واحدة. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: ar +lastmod: 2026-08-12 +og_description: كيفية إنشاء الباركود في بايثون باستخدام Aspose.BarCode. اتبع هذا الدليل + لإنشاء باركود من البيانات وتصدير صورة الباركود بصيغة PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: كيفية إنشاء الباركود في بايثون – دليل سريع وموثوق +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: كيفية إنشاء الباركود في بايثون – دليل خطوة بخطوة كامل +url: /ar/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية إنشاء الباركود في بايثون – دليل خطوة بخطوة كامل + +إذا كنت بحاجة إلى **كيفية إنشاء باركود** في تطبيق بايثون، فإن هذا الدليل يوضح لك الشيفرة الدقيقة التي تحتاجها. ستتعلم **إنشاء باركود من البيانات**، تعديل مظهره، و**تصدير صورة الباركود** كملف PNG—كل ذلك في أقل من عشر أسطر من الشيفرة. + +إنشاء باركود قد يبدو كمسألة منفصلة عن باقي منطق عملك، لكن باستخدام مكتبة واحدة يمكنك إبقاء العملية مدمجة مع قاعدة الشيفرة الحالية. في الأقسام التالية سترى مثالًا كاملاً قابلاً للتنفيذ، وتفهم لماذا كل سطر مهم، وتكتشف التغييرات الشائعة مثل تعديل عرض الوحدة أو رسم باركود كإطار فقط. + +## كيفية إنشاء باركود باستخدام مكتبة Aspose.BarCode + +توفر مكتبة Aspose.BarCode للبايثون (عبر .NET) واجهة برمجة تطبيقات بسيطة للعديد من الرموز، بما في ذلك باركود Planet المستخدم في هذا الدليل. قبل أن تبدأ، تأكد من تثبيت الحزمة: + +```bash +pip install aspose-barcode +``` + +> **نصيحة احترافية:** استخدم بيئة افتراضية لتجنب تعارض الإصدارات مع المشاريع الأخرى. + +### 1. استيراد الفئات المطلوبة + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +هذه الاستيرادات تمنحك الوصول إلى فئة المُولد، وتعداد أنواع الباركود، وتعداد صيغ الصورة المستخدم عند حفظ النتيجة. + +### 2. إنشاء باركود من البيانات + +الخطوة الأولى هي **إنشاء باركود من البيانات**. يأخذ مُنشئ `BarcodeGenerator` نوع الرمز والسلسلة الخام التي تريد ترميزها. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +القيمة `EncodeTypes.Planet` تختار باركود Planet، بينما `"123456"` هي الحمولة التي ستظهر في الصورة النهائية. + +### 3. ضبط البُعد X (عرض الوحدة) + +البُعد X يتحكم في عرض كل وحدة من الباركود (الشريط الرفيع). ضبطه على 4 بكسل يعطي صورة واضحة وقابلة للقراءة دون جعل الملف كبيرًا جدًا. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **لماذا هذا مهم:** بُعد X أكبر يحسن موثوقية القراءة على الطابعات منخفضة الدقة، بينما قيمة أصغر تقلل حجم الملف للاستخدام على الويب. + +### 4. تصدير صورة الباركود (نمط ممتلئ) + +الآن يمكنك **تصدير صورة الباركود** باستخدام طريقة `save`. المثال يحفظ ملف PNG، لكن يمكنك اختيار JPEG أو BMP أو TIFF بتغيير تعداد `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +الملف `PlanetFilled.png` يحتوي على باركود Planet ممتلئ بالكامل، جاهز للطباعة أو الإدراج في ملف PDF. + +### 5. إنشاء مُولد ثانٍ لباركود بإطار فقط + +إذا كنت بحاجة إلى نسخة بإطار فقط (أشرطة فارغة)، يجب إنشاء مُولد جديد لأن علم `filled_bars` لا يمكن تغييره بعد حفظ الصورة. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. تطبيق نفس إعداد البُعد X + +عند إنشاء مُولد ثانٍ، يجب تكرار أي إعدادات بصرية تريد الحفاظ عليها متسقة. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. إلغاء تعبئة الأشرطة لباركود بإطار + +ضبط `filled_bars` إلى `False` يخبر المُعالج برسم إطارات كل وحدة فقط، مما ينتج صورة أخف يمكن أن تكون مفيدة لأغراض التصميم. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. تصدير صورة الباركود بإطار + +أخيرًا، **تصدير صورة الباركود** مرة أخرى، هذه المرة حفظ النسخة بإطار. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +الآن لديك ملفا PNG: أحدهما بأشرطة صلبة (`PlanetFilled.png`) والآخر بإطارات فقط (`PlanetEmpty.png`). + +## تصدير صورة الباركود بصيغ أخرى (اختياري) + +طريقة `save` تدعم عدة صيغ. لتصدير كـ JPEG بجودة 90 %: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +إذا كنت بحاجة إلى خلفية شفافة للاستخدام على الويب، اختر PNG مع قناة ألفا: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## التغييرات الشائعة وحالات الحافة + +| السيناريو | التغيير المطلوب | مقتطف الشيفرة | +|----------|----------------|--------------| +| **رمز مختلف** (مثال: QR) | استخدام قيمة `EncodeTypes` مختلفة | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **لون المقدمة المخصص** | تعيين `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **دقة أعلى** | زيادة DPI عبر `image_width` و `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **سلاسل بيانات طويلة** | التأكد من أن طول البيانات يتوافق مع مواصفات الرمز | تحقق من الطول قبل إنشاء المُولد | + +> **احذر من:** تقديم بيانات تتجاوز الحد الأقصى للطول للرمز المختار يسبب استثناءً أثناء التشغيل. دائمًا تحقق من طول السلسلة أو امسك `ArgumentException`. + +## مثال كامل قابل للتنفيذ + +فيما يلي السكربت الكامل الذي يمكنك نسخه‑لصقه في ملف باسم `generate_planet_barcode.py`. عدل `YOUR_DIRECTORY` إلى مجلد موجود على جهازك. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +تشغيل هذا السكربت ينتج ملفي PNG في الدليل المحدد. تحقق من النتيجة بفتح الصور في أي عارض صور؛ يجب أن يعرض كلاهما باركود Planet يشفّر السلسلة `123456`. + +## الخلاصة + +أنت الآن تعرف **كيفية إنشاء باركود** في بايثون باستخدام Aspose.BarCode، وكيفية **إنشاء باركود من البيانات**، وكيفية **تصدير صورة الباركود** بنمطين: ممتلئ وإطار فقط. النمط نفسه ينطبق على رموز أخرى، صيغ صور مختلفة، وتخصيصات بصرية، مما يمنحك أساسًا مرنًا لأي ميزة متعلقة بالباركود في تطبيقك. + +### الخطوات التالية + +- استكشف رموزًا أخرى مثل QR أو Code‑128 أو DataMatrix عن طريق استبدال `EncodeTypes.Planet` بالقيمة المطلوبة. +- دمج ملفات PNG المُولدة في تقارير PDF باستخدام مكتبات مثل `ReportLab` أو `PyPDF2`. +- جرب قيم X‑dimension ديناميكية لتكييف حجم الباركود بناءً على دقة الشاشة أو DPI الطابعة. + +برمجة سعيدة، ولا تتردد في تعديل المثال ليناسب متطلبات مشروعك! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مصدر يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية إنشاء صورة باركود في جافا باستخدام Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [كيفية إنشاء باركود جافا – دليل التكوين الكامل](/barcode/english/java/barcode-configuration/) +- [كيفية إنشاء صور باركود code128 في جافا باستخدام Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/chinese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/chinese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..78a4cc169 --- /dev/null +++ b/barcode/chinese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-08-12 +description: 条形码生成器示例,展示如何生成具有精确像素尺寸的条形码。学习设置模块宽度、条码高度并创建 Planet 条码。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: zh +lastmod: 2026-08-12 +og_description: 条形码生成器示例演示了如何生成具有精确像素尺寸的条形码。请按照本指南控制 Planet 和 RM4SCC 码的模块宽度和条码高度。 +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: 条形码生成器示例 – 在 C# 中自定义像素大小 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: 条形码生成器示例——自定义像素尺寸的逐步指南 +url: /zh/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 条形码生成器示例 – 自定义像素尺寸的分步指南 + +如果你需要一个 **条形码生成器示例**,能够控制每个像素,本指南将完整演示如何实现。你将学习设置模块宽度、定义固定条码高度,并生成 Planet 和 RM4SCC 条码,确保尺寸可预测。 + +大多数开发者在“如何生成条形码”图像时都会遇到在不同屏幕或打印机上显示不一致的问题。下面的代码片段通过公开 Aspose.BarCode for .NET 库的像素级参数,帮助你在不猜测的情况下生成一致的输出。 + +## 你将学到 + +* 如何安装所需的 NuGet 包。 +* 如何生成高度自动计算的 Planet 条码。 +* 如何生成高度明确为 100 像素的 Planet 条码。 +* 如何使用相同的明确高度生成 RM4SCC 条码。 +* 为什么 **条形码像素尺寸** 对扫描可靠性很重要。 +* 生成 Planet 条码图像时常见问题的排查技巧。 + +你只需要 .NET 6 或更高版本、基本的 C# 开发环境以及用于获取 NuGet 包的网络连接。 + +--- + +## 条形码生成器示例 – 搭建开发环境 + +在编写任何代码之前,确保 Aspose.BarCode 库已添加到你的项目中。 + +### 安装 Aspose.BarCode 包 + +在项目文件夹的终端中运行: + +```bash +dotnet add package Aspose.BarCode +``` + +该命令会将最新稳定版的 **Aspose.BarCode** 添加到你的 `csproj` 中。恢复完成后,即可开始使用 `BarcodeGenerator` 类。 + +> **专业提示:** 目标设为 .NET 6 或 .NET 7,以获得最新的性能提升和默认的 UTF‑8 处理。 + +### 添加必要的 `using` 指令 + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +这些命名空间公开了后续教程中使用的 `BarcodeGenerator` 类和 `BarCodeImageFormat` 枚举。 + +--- + +## 如何使用自定义像素尺寸生成条形码 + +以下三个步骤完整演示 **条形码生成器示例**。每一步都基于前一步,你可以将整段代码复制粘贴到控制台应用中,直接运行。 + +### 步骤 1 – 生成高度自动计算的 Planet 条码 + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**工作原理:** +*`XDimension` 属性定义单个条码模块(最小的黑白单元)的宽度。当省略 `BarHeight` 时,库会计算一个保持 Planet 码标准宽高比的高度。* + +**预期输出:** 一个名为 `PlanetAuto.png` 的 PNG 文件,包含清晰的 Planet 条码。其高度会随 4 像素的模块宽度自动适配,通常约为 60 像素(对应六字符负载)。 + +### 步骤 2 – 生成高度明确为 100 像素的 Planet 条码 + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**为何需要这样做:** +有时扫描设备要求最小条码高度以确保可靠检测。通过设置 `BarHeight.Pixels`,你可以保证每张生成的图像都满足该要求,无论编码数据长度如何。 + +**预期输出:** `PlanetHeight100.png` 显示与前一步相同的数据,但条码高度恰好为 100 像素,让你完全掌控视觉尺寸。 + +### 步骤 3 – 使用相同的明确高度生成 RM4SCC 条码 + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**意义所在:** +`EncodeTypes.RM4SCC` 是物流中使用的堆叠线性条码。将其条码高度与 Planet 条码保持一致,可简化同一标签上出现多种符号时的批处理工作。 + +**预期输出:** `RM4SCCHeight100.png` 展示尺寸完美的 RM4SCC 条码,高度与 Planet 条码设定的 100 像素保持一致。 + +> **结果验证:** 在图像查看器中打开每个 PNG,确认黑条宽度恰为 4 像素,且在你指定的情况下高度为 100 像素。也可以将文件导入条码扫描应用,确保解码结果为 “123456”。 + +--- + +## 理解条形码像素尺寸与条码高度 + +### 什么是 **条形码像素尺寸**? + +*像素尺寸* 指的是在屏幕或打印机上表示单个模块(`XDimension`)所需的实际像素数量。更大的像素尺寸会生成更大的条码,低分辨率扫描仪更易读取,但会占用更多标签空间。 + +### `BarHeight` 如何影响可读性? + +`BarHeight` 属性控制条码的垂直长度。大多数 1‑D 条码(包括 Planet 和 RM4SCC)的标准建议在 300 dpi 打印时最小高度为 10 mm,约合 118 像素。低于此高度可能导致读取错误,尤其在移动摄像头上更为明显。 + +### 何时让库自动计算高度? + +如果仅用于屏幕显示,自动计算可保持宽高比一致,减少手动调节的工作量。对于必须符合严格 ISO 规范的印刷标签,建议 **显式设置条码高度**。 + +--- + +## 生成 Planet 条码时的常见陷阱与最佳实践 + +| 陷阱 | 产生原因 | 解决方案 | +|------|----------|----------| +| 条码过细或过粗 | 高分辨率显示器上 `XDimension` 保持默认(1 像素) | 将 `XDimension.Pixels` 设置为至少 3‑4,以提升可视清晰度 | +| 扫描仪无法读取 | `BarHeight` 对扫描仪焦距太小 | 对大多数移动扫描仪使用 `BarHeight.Pixels` ≥ 100 | +| 缩放后图像模糊 | 保存为 JPEG 会产生压缩伪影 | 使用 PNG (`BarCodeImageFormat.Png`) 保存,确保无损 | +| 条码类型意外 | 使用了错误的 `EncodeTypes` 枚举值 | 确认使用 `EncodeTypes.Planet` 生成 Planet 符号 | + +### 性能小技巧 + +在批量生成数千条条码时,复用同一个 `BarcodeGenerator` 实例,仅在保存前更改 `CodeText` 和尺寸参数。这样可避免重复分配内部渲染对象,执行时间可降低约 30 %。 + +--- + +## 完整示例 – 综合所有步骤 + +创建一个新控制台项目(`dotnet new console -n BarcodeDemo`),并将 `Program.cs` 内容替换为以下代码: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +使用 `dotnet run` 运行程序。执行完毕后,你将在项目文件夹中看到三个 PNG 文件,分别演示了不同的 **条形码生成器示例** 场景。 + +--- + +## 后续步骤与相关主题 + +* **如何生成其他格式的条码** – 探索 `EncodeTypes.Code128`、`EncodeTypes.QR` 与 `EncodeTypes.DataMatrix`,满足 2‑D 需求。 +* **在 PDF 中嵌入条码** – 将 Aspose.BarCode 与 Aspose.PDF 结合,直接在发票模板上放置条码。 +* **基于用户输入的动态条码尺寸** – 计算 + +## 接下来该学习什么? + +以下教程与本指南紧密相关,帮助你进一步掌握 API 功能并在项目中尝试不同实现方式,每篇都提供完整可运行的代码示例和逐步说明。 + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/chinese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/chinese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..a01e911bf --- /dev/null +++ b/barcode/chinese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,251 @@ +--- +category: general +date: 2026-08-12 +description: 在 Python 中快速配置 Databar 条形码布局。学习如何设置列、行,并使用条形码生成库保存图像。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: zh +lastmod: 2026-08-12 +og_description: 在 Python 中配置 Databar 条形码布局,以控制列、行和图像输出。按照本指南获取可直接运行的解决方案。 +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: 在 Python 中配置 Databar 条码布局 — 完整教程 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: 在 Python 中配置 Databar 条码布局 – 步骤指南 +url: /zh/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中配置 Databar 条形码布局 – 步骤指南 + +如果您需要在 Python 中**配置 Databar 条形码布局**,本指南将带您完成整个过程。您将看到如何为 Databar Expanded Stacked 条形码设置列数或行数,以及如何通过一次调用条形码生成库来保存生成的图像。 + +在窄包装、收据或移动屏幕上嵌入条形码时,控制布局至关重要。以下章节我们将介绍所需的导入、两种布局选项(列和行),以及保存干净 PNG 图像的最佳实践。 + +## 您需要的条件 + +* Python 3.8 或更高版本 +* 已安装 `aspose.barcode`(或任何兼容的条形码生成包) + ```bash + pip install aspose-barcode + ``` +* 对存放 PNG 文件的文件夹具有写入权限 + +无需额外的外部工具——库内部处理渲染、缩放和图像编码。 + +## 如何在 Python 中配置 Databar 条形码布局 + +解决方案的核心是 `BarcodeGenerator` 类。它接受一个 `EncodeTypes` 枚举,用于标识条形码符号——本例中为 `EncodeTypes.DatabarExpandedStacked`。创建生成器后,您可以通过设置 `data_bar` 参数对象的 `columns` 或 `rows` 属性来调整布局。 + +### 步骤 1:导入所需类 + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +这些导入为您提供对生成器、Databar 类型枚举以及 PNG 图像格式常量的访问。 + +### 步骤 2:为 Databar Expanded Stacked 创建条形码生成器 + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*为什么要这一步?* +`EncodeTypes.DatabarExpandedStacked` 告诉库生成 **Databar Expanded Stacked** 符号,该符号支持更长的数字字符串,同时保持紧凑的占用空间。第二个参数是要编码的数据;它可以是符合 Databar 规范的任意字符串。 + +### 步骤 3:设置列数(水平布局) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** 是此操作的关键短语。当您增加列数时,条形码会水平展开,这对宽标签很有用。库会自动重新计算模块宽度,以保持整体尺寸一致。 + +#### 专业提示 +Databar Expanded Stacked 的最大列数为 8。设置超过此限制的值会被限制为最大值,但最好事先验证输入。 + +### 步骤 4:使用列布局保存条形码图像 + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** 是将渲染的条形码写入磁盘的操作。PNG 为无损格式,可保留可靠扫描所需的锐利边缘。 + +### 步骤 5:为相同条形码类型创建第二个生成器(行布局) + +如果您更喜欢垂直堆叠,则使用行而非列。下面的代码重新使用相同的值,但创建了一个全新的 `BarcodeGenerator` 实例,以避免混合列和行设置。 + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### 步骤 6:设置行数(垂直布局) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** 将条形码模块垂直排列。三行布局降低了每个堆叠的高度,使条形码适用于窄收据或移动屏幕。 + +#### 边缘情况 +如果将 `rows` 设置为 1,库会生成单行 Databar(等同于标准 Databar)。小于 1 的值会被忽略并重置为默认值(1 行)。 + +### 步骤 7:使用行布局保存条形码图像 + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +同样,我们使用 PNG **save barcode image** 以保持输出清晰。 + +## 完整可运行示例 + +将所有部分组合在一起,您将得到一个可自行运行的脚本,可直接放入任何 Python 项目中。 + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**预期输出** + +运行脚本会生成两个 PNG 文件: + +* `output/ExpandedCols4.png` – 条形码横跨四列 +* `output/ExpandedRows3.png` – 条形码压缩为三行 + +两张图像均可在任何图像查看器中打开,或直接导入 PDF 发票、标签模板或网页中。 + +## 常见问题与故障排除 + +| Question | Answer | +|----------|--------| +| *如果条形码看起来模糊怎么办?* | 在调用 `save` 之前,通过设置 `barcode_generator.parameters.image_width` 和 `image_height` 来提高图像分辨率。 | +| *我可以使用其他图像格式吗?* | 可以。根据需要将 `BarCodeImageFormat.Png` 替换为 `Jpeg`、`Bmp` 或 `Gif`。 | +| *数据长度有上限吗?* | Databar Expanded Stacked 支持最多 74 个数字字符。超出限制会抛出 `ArgumentException`。 | +| *如何更改前景颜色?* | 使用 `barcode_generator.parameters.barcode.color = Color.Blue`(导入 `System.Drawing.Color`)。 | +| *我可以同时使用列和行吗?* | 不能。API 将列和行视为互斥的布局模式。每个条形码实例只能选择其一。 | + +## 后续步骤 + +既然您已经能够**配置 Databar 条形码布局**,可以考虑探索以下相关主题: + +* **添加文本标题** – 使用 `barcode_generator.parameters.barcode.code_text` 在图像下方显示编码值。 +* **在 PDF 中嵌入条形码** – 将生成的 PNG 与 `aspose.pdf` 结合,创建可打印文档。 +* **动态尺寸** – 在运行时根据标签尺寸计算最佳列数或行数。 +* **批量处理** – 遍历包含产品代码的 CSV,自动生成条形码图像库。 + +尝试不同的列值和行值,观察它们对目标设备扫描可靠性的影响。测试越多,您就越能理解条形码尺寸、可读性和空间限制之间的权衡。 + +--- + +*祝编码愉快!如果您觉得本教程有帮助,请与团队成员分享或留下关于布局挑战的评论。* + +## 接下来您应该学习什么? + +以下教程涵盖与本指南紧密相关的主题,基于所示技术进行扩展。每个资源都包含完整的可运行代码示例和逐步解释,帮助您掌握更多 API 功能,并在项目中探索替代实现方案。 + +- [创建 DotCode 条形码图像 – 行与列 (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [创建条形码图像 C# – 配置 Codablock F 行与列](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [一维 Databar 条形码高度调整](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/chinese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/chinese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..1e24ccd78 --- /dev/null +++ b/barcode/chinese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-08-12 +description: 使用 BarCodeGenerator 在 C# 中创建条形码图像。了解如何生成 DataBar、控制条形码图像尺寸,以及高效创建多个条形码。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: zh +lastmod: 2026-08-12 +og_description: 使用 BarCodeGenerator 在 C# 中创建条形码图像。本教程逐步演示如何生成 DataBar 条码、调整条码图像尺寸以及生成多个条码。 +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: 在 C# 中创建条形码图像 – 完整的 BarCodeGenerator 指南 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: 使用 BarCodeGenerator 在 C# 中创建条形码图像 +url: /zh/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 BarCodeGenerator 在 C# 中创建条形码图像 + +如果您需要在 .NET 应用程序中**创建条形码图像**,本指南将向您展示如何使用 `BarCodeGenerator` 类完成此操作。无论您是在构建零售 POS 系统还是库存跟踪工具,您都将学习生成 DataBar 符号、控制条形码图像大小,以及一次性生成多个条形码。 + +您还将了解 **barcode generator c#** API 如何让您微调尺寸、切换输出格式,并处理诸如无效数据字符串等边缘情况。教程结束时,您能够自信地**创建多个条形码**,而无需编写重复代码。 + +## 前提条件 + +在开始之前,请确保您已具备: + +- 已安装 .NET 6.0 或更高版本 +- 开发环境(Visual Studio、Rider 或 VS Code) +- Aspose.BarCode for .NET NuGet 包(或任何提供 `BarCodeGenerator` 的兼容库) + +您可以使用以下方式添加该包: + +```bash +dotnet add package Aspose.BarCode +``` + +## 本教程涵盖的内容 + +1. 为 DataBar Omni‑directional 编码设置 **barcode generator c#** 实例。 +2. 通过更改 X‑dimension 和条形高度来调整 **barcode image size**。 +3. 使用循环**创建多个条形码**,高度各不相同。 +4. 将图像保存为 PNG 文件并验证输出。 + +所有代码片段均为完整可直接复制粘贴到新控制台项目中的示例。 + +![Create barcode image example](barcode-example.png){alt="创建条形码图像示例"} + +## 第 1 步:初始化生成器 – 条形码图像基础 + +第一步是使用所需的符号实例化 `BarCodeGenerator`。对于 DataBar Omni‑directional 符号,使用 `EncodeTypes.DatabarOmniDirectional`。 + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**为什么这很重要:** 实例化生成器会定义编码规则和数据负载。如果省略正确的 `EncodeTypes` 值,库将生成不受支持的条形码或抛出异常。 + +## 第 2 步:配置 X‑dimension 和条形高度 – 控制条形码图像大小 + +条形码的视觉尺寸由两个参数决定: + +| 参数 | 控制内容 | 常见范围 | +|-----------|------------------|---------------| +| `x_dimension.pixels` | 最小模块(“点”)的宽度 | 1 – 4 px | +| `bar_height.pixels` | 垂直条的高度 | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**专业提示:** 较小的 X‑dimension 能产生更高分辨率的图像,但在低质量打印机上可能更难扫描。请根据目标扫描设备调整该值。 + +## 第 3 步:保存第一张条形码 – 为 30 px 高度创建条形码图像 + +现在可以生成图像并写入磁盘。`Save` 方法接受文件路径和图像格式枚举。 + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**预期结果:** 在 `C:\Barcodes` 中出现名为 `Databar30.png` 的 PNG 文件。打开文件后可看到 DataBar Omni‑directional 符号,图案清晰、对比度高。 + +## 第 4 步:更改高度并生成额外图像 – 创建多个条形码 + +要**创建多个条形码**并使用不同尺寸,只需修改 `BarHeight` 属性后再次调用 `Save`。这样可以避免重新实例化生成器,从而节省内存和 CPU 时间。 + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**为何可行:** `BarCodeGenerator` 对象保存所有配置状态。更改单个属性会更新渲染引擎,以便在下次 `Save` 调用时生成新的图像,从而高效**创建多个条形码**。 + +## 第 5 步:进阶 – 如何使用自定义数据生成 DataBar + +上面的示例使用了静态 GS1 负载。在实际场景中,您通常需要嵌入可变的产品标识符。库接受任何符合 DataBar 规范的字符串。 + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**关键点:** 设置 `generator.CodeText` 会在不重新创建对象的情况下更新编码数据。这是处理大数据集时推荐的**how to generate databar**模式。 + +## 第 6 步:验证与排查 – 确保条形码图像尺寸正确 + +生成图像后,您可能希望通过代码程序化确认尺寸是否符合预期。`System.Drawing` 中的 `Image` 类可以读取文件并报告其大小。 + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +如果高度未反映您设置的值,请检查: + +- **X‑dimension**:过小的数值可能导致渲染器对高度进行四舍五入。 +- **图像格式**:某些格式(如 JPEG)在保存时会进行压缩,可能改变像素尺寸。PNG 能保留精确尺寸。 + +## 第 7 步:条形码图像大小与性能的最佳实践 + +| 建议 | 原因 | +|----------------|--------| +| 将 `x_dimension.pixels` 保持在 2 – 3 px 之间,以适配大多数扫描仪。 | 在可读性和文件大小之间取得平衡。 | +| 打印时使用 PNG 进行无损输出。 | 确保尺寸精确且边缘锐利。 | +| 生成大量条形码时复用同一个 `BarCodeGenerator` 实例。 | 减少对象分配开销。 | +| 在将字符串赋给 `CodeText` 前,先依据 GS1 标准进行验证。 | 防止运行时异常和无效扫描。 | +| 将生成的图像存放在专用文件夹,并使用清晰的命名约定(例如 `Databar_{GTIN}.png`)。 | 简化后续处理和审计追踪。 | + +## 完整工作示例 + +下面是完整的程序示例,涵盖从初始化到验证的所有步骤。将代码复制到新建的控制台项目中并运行。 + + + +## 接下来您应该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助您进一步掌握 API 功能并在项目中探索替代实现方式。每个资源均提供完整的可运行代码示例和逐步解释。 + +- [生成条形码图像 – GS1 优惠券 UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [创建 DotCode 条形码图像 – 行与列 (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [如何使用 Aspose.BarCode for .NET 为 ITF-14 创建条形码安静区](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/chinese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/chinese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..4250266c8 --- /dev/null +++ b/barcode/chinese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-08-12 +description: 使用 Python 创建全方向 DataBar 条码,并学习如何使用 Aspose.BarCode 在 Python 中生成条码图像。请按照分步指南获取完整解决方案。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: zh +lastmod: 2026-08-12 +og_description: 使用 Python 创建全方向 DataBar 并在几分钟内生成条形码图像。本教程展示了完整的可运行示例。 +og_image_alt: example of create omni directional databar barcode image in Python +og_title: 创建全向数据条 – 完整 Python 指南 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: 在 Python 中创建全向数据条码和条形码图像 +url: /zh/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中创建全向 DataBar 和条形码图像 + +如果您需要在 Python 项目中 **创建全向 DataBar**,本指南将向您展示如何实现,并且还会教您如何使用 Aspose.BarCode 库 **在 Python 中创建条形码图像**。您将获得一个可直接运行的脚本,生成两个不同宽高比的 PNG 文件。 + +生成符合全向规范的 DataBar 是零售和物流应用的常见需求。教程涵盖了安装、X 维度的配置、宽高比的调整以及最终图像的保存。无需任何外部服务,全部在本地完成。 + +## 您需要准备的内容 + +在开始之前,请确保您拥有: + +* 已在机器上安装 Python 3.8 或更高版本。 +* 可使用的终端或命令提示符。 +* 对保存条形码图像的文件夹拥有写入权限。 + +唯一的第三方依赖是 **Aspose.BarCode for Python via .NET**,它开箱即支持全向 DataBar 类型。 + +## 第一步:安装 Aspose.BarCode for Python + +Aspose.BarCode 提供了示例代码中使用的 `BarcodeGenerator` 类。使用 `pip` 安装该包: + +```bash +pip install aspose-barcode +``` + +该包已包含必要的 .NET 运行时绑定,无需单独安装 .NET SDK。 + +## 第二步:导入库并创建生成器 + +脚本的第一行创建了一个用于堆叠全向 DataBar 的生成器。示例数据使用 GTIN‑14 值 `(01)12345678901231`。 + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*此步骤的重要性*:`EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` 常量告诉库将数值编码为全向 DataBar,这正是许多 POS 扫描仪所要求的格式。 + +## 第三步:设置 X 维度(模块宽度) + +X 维度定义了最小条模块的宽度。`2` 像素的值能够生成清晰、易读的条形码,同时保持文件大小适中。 + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*此步骤的重要性*:调整 X 维度可以在可读性和图像尺寸之间取得平衡。X 维度过小可能在低分辨率打印机上显示不佳。 + +## 第四步:配置宽高比并保存第一张图像 + +宽高比影响 DataBar 相对于宽度的整体高度。宽高比设为 `15` 可产生紧凑的视觉效果。 + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **小技巧**:使用 `pathlib.Path` 构建输出路径,能够自动创建缺失的目录。 + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## 第五步:更改宽高比以获得第二种视觉样式并保存另一张图像 + +将宽高比切换为 `30` 可生成更高的条形码,这在某些扫描硬件中可能是必需的。 + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*此步骤的重要性*:不同零售商和扫描设备对尺寸有不同限制。在同一脚本中提供两种宽高比,可在不复制代码的情况下生成所需的精确样式。 + +## 完整脚本 – 在 Python 中创建全向 DataBar 和条形码图像 + +下面是整合了上述所有步骤的可运行示例。将其保存为 `generate_databar.py` 并使用 `python generate_databar.py` 运行。 + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### 预期输出 + +运行脚本后会生成以下文件: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +两张图像均显示了可被标准零售设备扫描的有效全向 DataBar。 + +![example of create omni directional databar barcode image in Python](example_databar.png "create omni directional databar barcode image python") + +*上图为占位示例,展示了两个已保存的 PNG 文件。* + +## 常见问题处理 + +| 问题 | 原因 | 解决方案 | +|-------|--------|-----| +| `ImportError: No module named aspose` | 未安装 Aspose.BarCode 或安装在了不同的环境中。 | 激活正确的虚拟环境并运行 `pip install aspose-barcode`。 | +| 保存时出现 `PermissionError` | 脚本对目标文件夹没有写入权限。 | 选择您拥有权限的目录,或以适当的权限运行脚本。 | +| 条形码无法扫描 | X 维度过低或宽高比与扫描仪不兼容。 | 将 `x_dimension.pixels` 提升至 3 或 4,并尝试不同的 `aspect_ratio`(如 20、25)。 | +| 缺少 .NET 运行时 | Aspose.BarCode 在 Windows/Linux 上依赖 .NET 运行时。 | 从 Microsoft 官方网站安装最新的 .NET 运行时;包文档提供了平台特定的指导。 | + +## 扩展示例 + +您可以将脚本改为生成其他 DataBar 变体(例如 `DATABAR_STACKED`、`DATABAR_EXPANDED`),只需相应更换 `EncodeTypes` 常量: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +如果需要将条形码嵌入 PDF,Aspose.PDF for Python 可以直接导入 PNG 文件,或者使用 `save` 方法并指定 `BarCodeImageFormat.Pdf`。 + +## 结论 + +本教程演示了如何使用 Aspose.BarCode **创建全向 DataBar** 以及 **在 Python 中创建条形码图像**。您现在拥有一个完整、可复现的脚本,能够生成两种不同宽高比的 PNG 文件,处理常见问题,并可扩展到其他条码格式。 + +接下来,您可以尝试生成 QR 码、将条形码添加到 PDF 发票中,或为大型产品目录实现批量处理。所有这些主题都基于本指南中展示的 `BarcodeGenerator` 模式。祝编码愉快! + +## 接下来您可以学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,提供完整的可运行代码示例和逐步解释,帮助您掌握更多 API 功能并在项目中探索替代实现方案。 + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to create barcode image and render it in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/chinese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/chinese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..59dc45ada --- /dev/null +++ b/barcode/chinese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,251 @@ +--- +category: general +date: 2026-08-12 +description: 如何使用 Python 快速生成条形码。学习从数据创建条形码并使用单一库导出条形码图像。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: zh +lastmod: 2026-08-12 +og_description: 如何使用 Aspose.BarCode 在 Python 中生成条形码。请按照本指南从数据创建条形码并将条形码图像导出为 PNG。 +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: 如何在 Python 中生成条形码——快速可靠的指南 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: 如何在 Python 中生成条形码——完整的逐步指南 +url: /zh/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 Python 中生成条形码 – 完整分步指南 + +如果您需要在 Python 应用程序中 **如何生成条形码**,本教程将展示您所需的完整代码。您将学习 **从数据创建条形码**、调整其外观,以及 **导出条形码图像** 为 PNG 文件——全部代码不超过十行。 + +生成条形码看似与业务逻辑无关,但只需一个库即可将其流程直接嵌入现有代码库。接下来的章节中,您将看到一个完整、可运行的示例,了解每行代码的意义,并发现常见的变体,例如更改模块宽度或绘制仅轮廓的条形码。 + +## 如何使用 Aspose.BarCode 库生成条形码 + +Aspose.BarCode for Python(通过 .NET)提供了简洁的 API,支持多种符号体系,包括本指南使用的 Planet 条形码。开始之前,请确保已安装该包: + +```bash +pip install aspose-barcode +``` + +> **专业提示:** 使用虚拟环境可以避免与其他项目的版本冲突。 + +### 1. 导入所需类 + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +这些导入让您可以访问生成器类、条形码类型枚举以及保存结果时使用的图像格式枚举。 + +### 2. 从数据创建条形码 + +第一步是 **从数据创建条形码**。`BarcodeGenerator` 构造函数接受符号体系和要编码的原始字符串。 + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +`EncodeTypes.Planet` 选择 Planet 条形码,而 `"123456"` 则是最终图像中显示的有效负载。 + +### 3. 调整 X 维度(模块宽度) + +X 维度控制每个条形码模块(细条)的宽度。将其设为 4 像素可获得清晰、易读的图像,同时不会使文件过大。 + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **为什么重要:** 较大的 X 维度可提升低分辨率打印机的扫描可靠性,而较小的数值则可在网页使用时减小文件体积。 + +### 4. 导出条形码图像(实心样式) + +现在可以使用 `save` 方法 **导出条形码图像**。示例保存为 PNG 文件,您也可以通过更改 `BarCodeImageFormat` 枚举来选择 JPEG、BMP 或 TIFF。 + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +文件 `PlanetFilled.png` 包含完整实心的 Planet 条形码,可直接用于打印或嵌入 PDF。 + +### 5. 为仅轮廓条形码创建第二个生成器 + +如果需要仅轮廓版本(空心条),必须创建新生成器,因为在图像保存后 `filled_bars` 标志无法再切换。 + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. 应用相同的 X 维度设置 + +创建第二个生成器时,需要再次设置所有希望保持一致的视觉参数。 + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. 为轮廓条形码禁用实心条 + +将 `filled_bars` 设置为 `False` 告诉渲染器仅绘制每个模块的轮廓,生成的图像更轻,可用于设计需求。 + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. 导出轮廓条形码图像 + +最后,再次 **导出条形码图像**,这次保存的是轮廓版本。 + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +现在您拥有两个 PNG 文件:一个实心条(`PlanetFilled.png`),一个仅轮廓条(`PlanetEmpty.png`)。 + +## 以其他格式导出条形码图像(可选) + +`save` 方法支持多种格式。以 90% 质量导出 JPEG: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +如果需要用于网页的透明背景,请选择带 alpha 通道的 PNG: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## 常见变体和边缘情况 + +| 场景 | 需要的更改 | 代码片段 | +|----------|---------------|--------------| +| **不同符号体系**(例如 QR) | 使用不同的 `EncodeTypes` 值 | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **自定义前景色** | 设置 `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **更高分辨率** | 通过 `image_width` 和 `image_height` 增加 DPI | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **大数据字符串** | 确保数据长度符合符号体系规范 | 在创建生成器前验证长度 | + +> **注意:** 提供超出所选符号体系最大长度的数据会抛出运行时异常。请始终验证字符串长度或捕获 `ArgumentException`。 + +## 完整可运行示例 + +下面是完整脚本,您可以复制粘贴到名为 `generate_planet_barcode.py` 的文件中。将 `YOUR_DIRECTORY` 替换为您机器上实际存在的文件夹路径。 + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +运行此脚本后,会在指定目录生成两个 PNG 文件。使用任意图像查看器打开它们,您应看到编码字符串 `123456` 的 Planet 条形码。 + +## 结论 + +现在您已经掌握了 **如何在 Python 中生成条形码**,了解了 **从数据创建条形码** 的方法,并能够 **导出条形码图像**(实心和轮廓两种样式)。相同的模式同样适用于其他符号体系、图像格式和视觉自定义,为您在应用程序中实现任何条形码相关功能提供了灵活的基础。 + +### 后续步骤 + +* 通过将 `EncodeTypes.Planet` 替换为其他值,探索 QR、Code‑128、DataMatrix 等符号体系。 +* 使用 `ReportLab` 或 `PyPDF2` 等库将生成的 PNG 文件嵌入 PDF 报告。 +* 试验动态 X 维度值,以根据屏幕分辨率或打印机 DPI 自动调整条形码大小。 + +祝编码愉快,欢迎根据项目需求自由改进示例! + +## 接下来您应该学习什么? + +以下教程涵盖与本指南紧密相关的主题,帮助您进一步掌握 API 功能并探索替代实现方式: + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/czech/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/czech/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..aa16aa5a5 --- /dev/null +++ b/barcode/czech/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,296 @@ +--- +category: general +date: 2026-08-12 +description: Příklad generátoru čárových kódů, který ukazuje, jak generovat čárový + kód s přesnou velikostí pixelu. Naučte se nastavit šířku modulu, výšku čáry a vytvořit + Planet čárové kódy. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: cs +lastmod: 2026-08-12 +og_description: Ukázka generátoru čárových kódů demonstruje, jak vytvořit čárový kód + s přesnými rozměry v pixelech. Postupujte podle tohoto návodu, abyste ovládali šířku + modulu a výšku čáry pro kódy Planet a RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: příklad generátoru čárových kódů – přizpůsobení velikosti pixelu v C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Příklad generátoru čárových kódů – krok za krokem průvodce pro vlastní velikosti + pixelů +url: /cs/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# příklad generátoru čárových kódů – krok za krokem průvodce pro vlastní velikosti pixelů + +Pokud potřebujete **příklad generátoru čárových kódů**, který vám umožní ovládat každý pixel, tento průvodce vám přesně ukáže, jak na to. Naučíte se nastavit šířku modulu, definovat pevnou výšku pruhu a generovat jak čárové kódy Planet, tak RM4SCC s předvídatelnými rozměry. + +Většina vývojářů má potíže s tím, „jak generovat obrázky čárových kódů“, které vypadají stejně na každé obrazovce nebo tiskárně. Níže uvedené úryvky kódu tento problém řeší tím, že odhalí parametry na úrovni pixelů knihovny Aspose.BarCode pro .NET, takže můžete vytvářet konzistentní výstup bez hádání. + +## Co se naučíte + +* Jak nainstalovat požadovaný NuGet balíček. +* Jak vygenerovat Planet čárový kód s automaticky vypočtenou výškou. +* Jak vygenerovat Planet čárový kód s explicitní výškou 100 pixelů. +* Jak vygenerovat RM4SCC čárový kód pomocí stejné explicitní výšky. +* Proč **velikost pixelu čárového kódu** ovlivňuje spolehlivost skenování. +* Tipy pro řešení běžných problémů při generování obrázků Planet čárových kódů. + +Stačí vám .NET 6 nebo novější, základní vývojové prostředí C# a internetové připojení pro stažení NuGet balíčku. + +--- + +## barcode generator example – nastavení vývojového prostředí + +Než napíšete jakýkoli kód, ujistěte se, že knihovna Aspose.BarCode je ve vašem projektu dostupná. + +### Instalace balíčku Aspose.BarCode + +Otevřete terminál ve složce projektu a spusťte: + +```bash +dotnet add package Aspose.BarCode +``` + +Příkaz přidá nejnovější stabilní verzi **Aspose.BarCode** do vašeho `csproj`. Po dokončení obnovení můžete začít používat třídu `BarcodeGenerator`. + +> **Pro tip:** Cílová platforma .NET 6 nebo .NET 7 vám poskytne nejnovější vylepšení výkonu a výchozí zpracování UTF‑8. + +### Přidejte potřebné `using` direktivy + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Tyto jmenné prostory zpřístupňují třídu `BarcodeGenerator` a výčet `BarCodeImageFormat`, které budou později v tutoriálu použity. + +--- + +## Jak generovat čárový kód s vlastní velikostí pixelů + +Následující tři kroky ukazují kompletní **příklad generátoru čárových kódů**. Každý krok navazuje na předchozí, takže můžete celý blok zkopírovat do konzolové aplikace a spustit beze změn. + +### Krok 1 – vygenerovat Planet čárový kód s automaticky vypočtenou výškou + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Proč to funguje:** +*Vlastnost `XDimension` určuje šířku jednoho modulu čárového kódu (nejmenšího černého nebo bílého prvku). Když vynecháte `BarHeight`, knihovna vypočítá výšku, která zachová standardní poměr stran pro kódy Planet.* + +**Očekávaný výstup:** PNG soubor pojmenovaný `PlanetAuto.png` obsahující čistý Planet čárový kód. Jeho výška se přizpůsobí šířce 4‑pixelového modulu, typicky kolem 60 pixelů pro šestimístný payload. + +### Krok 2 – vygenerovat Planet čárový kód s explicitní výškou 100 pixelů + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Proč byste to mohli potřebovat:** +Některé skenovací zařízení vyžaduje minimální výšku pruhu pro spolehlivé rozpoznání. Nastavením `BarHeight.Pixels` zajistíte, že každý vygenerovaný obrázek splní tento požadavek, bez ohledu na délku kódovaných dat. + +**Očekávaný výstup:** `PlanetHeight100.png` zobrazuje stejná data jako předtím, ale pruhy mají přesně 100 pixelů na výšku, což vám dává plnou kontrolu nad vizuální velikostí. + +### Krok 3 – vygenerovat RM4SCC čárový kód se stejnou explicitní výškou + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Proč je to důležité:** +`EncodeTypes.RM4SCC` je vrstvený lineární čárový kód používaný v logistice. Zarovnání výšky pruhu s Planet čárovým kódem usnadňuje dávkové zpracování, když se na stejné etiketě objeví oba symbology. + +**Očekávaný výstup:** `RM4SCCHeight100.png` zobrazuje perfektně dimenzovaný RM4SCC čárový kód, který odpovídá výšce 100 pixelů nastavené pro Planet kód. + +> **Ověření výsledku:** Otevřete každý PNG v prohlížeči obrázků a potvrďte, že černé pruhy jsou přesně 4 pixely široké a tam, kde jste zadali, 100 pixelů vysoké. Můžete také soubory nahrát do aplikace pro skenování čárových kódů a ověřit, že dekódují „123456“. + +--- + +## Porozumění velikosti pixelu čárového kódu a výšce pruhu + +### Co je **velikost pixelu čárového kódu**? + +*Velikost pixelu* označuje fyzický počet pixelů na obrazovce nebo tiskárně, které představují jeden modul (`XDimension`). Větší velikost pixelu vede k většímu čárovému kódu, který může být snazší pro nízkorozlišovací skenery, ale zabírá více místa na štítku. + +### Jak `BarHeight` ovlivňuje čitelnost? + +Vlastnost `BarHeight` řídí vertikální délku pruhů. Standardy pro většinu 1‑D čárových kódů (včetně Planet a RM4SCC) doporučují minimální výšku 10 mm při tisku 300 dpi, což odpovídá přibližně 118 pixelům. Nastavení výšky pod tuto hodnotu může způsobit chyby čtení, zejména u mobilních kamer. + +### Kdy nechat knihovnu automaticky vypočítat výšku? + +Pokud generujete čárové kódy pouze pro zobrazení na obrazovce, automatický výpočet udrží poměr stran konzistentní a sníží množství ručního ladění. Pro tištěné štítky, které musí splňovat přísné ISO specifikace, byste měli **explicitně nastavit výšku pruhu**. + +--- + +## Běžné úskalí a osvědčené postupy při generování Planet čárového kódu + +| Problém | Proč k tomu dochází | Řešení | +|---------|----------------------|--------| +| Pruhy se jeví příliš tenké nebo tlusté | `XDimension` zůstala na výchozí hodnotě (1 pixel) na displejích s vysokým rozlišením | Nastavte `XDimension.Pixels` alespoň na 3‑4 pro vizuální jasnost | +| Skenner nedokáže kód přečíst | `BarHeight` je příliš malá pro ohniskovou vzdálenost skeneru | Použijte `BarHeight.Pixels` ≥ 100 pro většinu mobilních skenerů | +| Obrázek je po škálování rozmazaný | Ukládání jako JPEG zavádí kompresní artefakty | Ukládejte jako PNG (`BarCodeImageFormat.Png`) pro bezztrátový výstup | +| Neočekávaný typ čárového kódu | Nesprávná hodnota v enumu `EncodeTypes` | Zkontrolujte, že používáte `EncodeTypes.Planet` pro symbologii Planet | + +### Pro tip na výkon + +Při generování tisíců čárových kódů v dávkovém úkolu opakovaně používejte jedinou instanci `BarcodeGenerator` a mezi ukládáními měňte pouze `CodeText` a parametry velikosti. Tím se vyhnete opakovanému alokování interních renderovacích objektů a můžete zkrátit dobu běhu až o 30 %. + +--- + +## Kompletní funkční příklad – spojte vše dohromady + +Vytvořte nový konzolový projekt (`dotnet new console -n BarcodeDemo`) a nahraďte obsah souboru `Program.cs` následujícím kódem: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Spusťte program pomocí `dotnet run`. Po dokončení najdete ve složce projektu tři PNG soubory, z nichž každý ilustruje jiný scénář **příkladu generátoru čárových kódů**. + +--- + +## Další kroky a související témata + +* **Jak generovat čárový kód v jiných formátech** – prozkoumejte `EncodeTypes.Code128`, `EncodeTypes.QR` a `EncodeTypes.DataMatrix` pro potřeby 2‑D. +* **Vkládání čárových kódů do PDF** – kombinujte Aspose.BarCode s Aspose.PDF pro umístění čárových kódů přímo na šablony faktur. +* **Dynamická velikost čárového kódu na základě vstupu uživatele** – vypočítejte + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vlastních projektech. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/czech/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/czech/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..076b50c7d --- /dev/null +++ b/barcode/czech/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: Rychle nakonfigurujte rozložení čárového kódu Databar v Pythonu. Naučte + se nastavit sloupce, řádky a ukládat obrázky pomocí knihovny generátoru čárových + kódů. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: cs +lastmod: 2026-08-12 +og_description: Nakonfigurujte rozložení čárových kódů Databar v Pythonu, abyste ovládali + sloupce, řádky a výstup obrázku. Postupujte podle tohoto návodu pro připravené řešení + připravené k okamžitému spuštění. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Konfigurace rozložení čárového kódu Databar v Pythonu – kompletní tutoriál +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Nastavte rozložení čárového kódu Databar v Pythonu – krok za krokem +url: /cs/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Nastavení rozložení čárového kódu Databar v Pythonu – krok za krokem + +Pokud potřebujete **nastavit rozložení čárového kódu Databar v Pythonu**, tento průvodce vás provede celým procesem. Uvidíte, jak nastavit počet sloupců nebo řádků pro čárový kód Databar Expanded Stacked a jak uložit výsledný obrázek jediným voláním knihovny pro generování čárových kódů. + +Řízení rozložení je nezbytné, když vkládáte čárové kódy na úzké obaly, účtenky nebo mobilní obrazovky. V následujících sekcích pokryjeme potřebné importy, dvě možnosti rozložení (sloupce a řádky) a osvědčené postupy pro uložení čistého PNG obrázku. + +## Co budete potřebovat + +* Python 3.8 nebo novější +* `aspose.barcode` (nebo jakýkoli kompatibilní balíček pro generování čárových kódů) nainstalovaný + ```bash + pip install aspose-barcode + ``` +* Oprávnění k zápisu do složky, kde budou PNG soubory uloženy + +Žádné další externí nástroje nejsou vyžadovány – knihovna interně zajišťuje vykreslování, škálování a kódování obrázku. + +## Jak nastavit rozložení čárového kódu Databar v Pythonu + +Jádrem řešení je třída `BarcodeGenerator`. Přijímá výčtový typ `EncodeTypes`, který určuje symbologii čárového kódu – v tomto případě `EncodeTypes.DatabarExpandedStacked`. Po vytvoření generátoru můžete upravit rozložení nastavením vlastností `columns` nebo `rows` na objektu parametru `data_bar`. + +### Krok 1: Importujte požadované třídy + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Tyto importy vám poskytují přístup k generátoru, výčtu pro typy Databar a konstantě formátu obrázku PNG. + +### Krok 2: Vytvořte generátor čárového kódu pro Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Proč tento krok?* +`EncodeTypes.DatabarExpandedStacked` říká knihovně, aby vytvořila symbologii **Databar Expanded Stacked**, která podporuje delší číselné řetězce při zachování kompaktního rozměru. Druhý argument jsou data k zakódování; může to být jakýkoli řetězec splňující specifikaci Databar. + +### Krok 3: Nastavte počet sloupců (horizontální rozložení) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** je klíčová fráze pro tuto operaci. Když zvýšíte počet sloupců, čárový kód se rozprostře horizontálně, což může být užitečné pro široké štítky. Knihovna automaticky přepočítá šířku modulu, aby zachovala celkovou velikost konzistentní. + +#### Tip +Maximální počet sloupců pro Databar Expanded Stacked je 8. Nastavení hodnoty vyšší než limit ji ořízne na maximum, ale je lepší vstup předem ověřit. + +### Krok 4: Uložte obrázek čárového kódu s rozložením sloupců + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** je akce, která zapíše vykreslený čárový kód na disk. PNG je bezztrátový formát, který zachovává ostré hrany potřebné pro spolehlivé skenování. + +### Krok 5: Vytvořte druhý generátor pro stejný typ čárového kódu (rozložení řádků) + +Pokud dáváte přednost vertikálnímu uspořádání, pracujete s řádky místo sloupců. Níže uvedený kód znovu použije stejnou hodnotu, ale vytvoří novou instanci `BarcodeGenerator`, aby nedocházelo k míchání nastavení sloupců a řádků. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Krok 6: Nastavte počet řádků (vertikální rozložení) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** uspořádá moduly čárového kódu vertikálně. Rozložení se třemi řádky snižuje výšku každého jednotlivého stacku, což činí čárový kód vhodným pro úzké účtenky nebo mobilní obrazovky. + +#### Okrajový případ +Pokud nastavíte `rows` na 1, knihovna vygeneruje jednoradý Databar (ekvivalent standardního Databar). Hodnoty pod 1 jsou ignorovány a resetovány na výchozí (1 řádek). + +### Krok 7: Uložte obrázek čárového kódu s rozložením řádků + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Opět **save barcode image** pomocí PNG, aby výstup zůstal ostrý. + +## Kompletní spustitelný příklad + +Sestavením všech částí dohromady získáte samostatný skript, který můžete vložit do libovolného Python projektu. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Očekávaný výstup** + +Spuštěním skriptu se vytvoří dva PNG soubory: + +* `output/ExpandedCols4.png` – čárový kód roztažený přes čtyři sloupce +* `output/ExpandedRows3.png` – čárový kód komprimovaný do tří řádků + +Oba obrázky lze otevřít v libovolném prohlížeči obrázků nebo je přímo importovat do PDF faktur, šablon štítků či webových stránek. + +## Časté otázky a řešení problémů + +| Question | Answer | +|----------|--------| +| *Co když čárový kód vypadá rozmazaně?* | Zvyšte rozlišení obrázku nastavením `barcode_generator.parameters.image_width` a `image_height` před voláním `save`. | +| *Mohu použít jiné formáty obrázků?* | Ano. Nahraďte `BarCodeImageFormat.Png` za `Jpeg`, `Bmp` nebo `Gif` podle potřeby. | +| *Existuje limit délky dat?* | Databar Expanded Stacked podporuje až 74 číselných znaků. Překročení limitu vyvolá `ArgumentException`. | +| *Jak změním barvu popředí?* | Použijte `barcode_generator.parameters.barcode.color = Color.Blue` (importujte `System.Drawing.Color`). | +| *Mohu kombinovat sloupce a řádky?* | Ne. API považuje sloupce a řádky za vzájemně se vylučující režimy rozložení. Vyberte jeden pro každou instanci čárového kódu. | + +## Další kroky + +Nyní, když můžete **nastavit rozložení čárového kódu Databar**, zvažte prozkoumání těchto souvisejících témat: + +* **Přidat textové popisky** – použijte `barcode_generator.parameters.barcode.code_text` k zobrazení zakódované hodnoty pod obrázkem. +* **Vložit čárový kód do PDF** – kombinujte vygenerovaný PNG s `aspose.pdf` pro vytvoření tisknutelných dokumentů. +* **Dynamické velikosti** – vypočítejte optimální počet sloupců nebo řádků na základě rozměrů štítku za běhu. +* **Dávkové zpracování** – projděte CSV soubor s kódy produktů a automaticky vygenerujte knihovnu obrázků čárových kódů. + +Experimentujte s různými hodnotami sloupců a řádků, abyste viděli, jak ovlivňují spolehlivost skenování na vašich cílových zařízeních. Čím více testujete, tím lépe pochopíte kompromisy mezi velikostí čárového kódu, čitelností a prostorovými omezeními. + +*Šťastné kódování! Pokud se vám tento tutoriál hodil, sdílejte ho se spolupracovníky nebo zanechte komentář o výzvách s rozložením, se kterými jste se setkali.* + +## Co byste se měli učit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vlastních projektech. + +- [Vytvořit obrázek čárového kódu DotCode – řádky a sloupce (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Vytvořit obrázek čárového kódu c# – nastavit řádky a sloupce Codablock F](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [Jednorozměrné nastavení výšky čárového kódu Databar](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/czech/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/czech/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..e026abeb0 --- /dev/null +++ b/barcode/czech/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: Vytvořte obrázek čárového kódu v C# pomocí BarCodeGenerator. Naučte se + generovat DataBar, ovládat velikost obrázku čárového kódu a efektivně vytvářet více + čárových kódů. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: cs +lastmod: 2026-08-12 +og_description: Vytvořte obrázek čárového kódu v C# pomocí BarCodeGeneratoru. Tento + tutoriál ukazuje krok za krokem, jak generovat kódy DataBar, upravit velikost obrázku + čárového kódu a vytvořit více čárových kódů. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Vytvořte obrázek čárového kódu v C# – kompletní průvodce BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Vytvořte obrázek čárového kódu v C# pomocí BarCodeGenerator +url: /cs/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření obrázku čárového kódu v C# pomocí BarCodeGenerator + +Pokud potřebujete **vytvořit obrázek čárového kódu** v .NET aplikaci, tento průvodce vám přesně ukáže, jak to provést pomocí třídy `BarCodeGenerator`. Ať už budujete maloobchodní POS systém nebo nástroj pro sledování zásob, naučíte se generovat symboly DataBar, řídit velikost obrázku čárového kódu a vytvořit několik čárových kódů v jednom běhu. + +Také zjistíte, jak vám API **barcode generator c#** umožňuje upravovat rozměry, přepínat výstupní formáty a řešit okrajové případy, jako jsou neplatné datové řetězce. Na konci tutoriálu budete sebejistě **vytvářet více čárových kódů** bez psaní opakujícího se kódu. + +## Požadavky + +- .NET 6.0 nebo novější nainstalováno +- Vývojové prostředí (Visual Studio, Rider nebo VS Code) +- Aspose.BarCode pro .NET NuGet balíček (nebo jakákoli kompatibilní knihovna, která poskytuje `BarCodeGenerator`) + +Balíček můžete přidat pomocí: + +```bash +dotnet add package Aspose.BarCode +``` + +## Co tento tutoriál pokrývá + +1. Nastavení instance **barcode generator c#** pro kódování DataBar Omni‑directional. +2. Úprava **barcode image size** změnou X‑dimension a výšky čáry. +3. Použití smyčky k **vytvoření více čárových kódů** s různými výškami. +4. Uložení obrázků jako PNG soubory a ověření výstupu. + +Všechny úryvky kódu jsou kompletní a připravené ke zkopírování a vložení do nového konzolového projektu. + +![Create barcode image example](barcode-example.png){alt="Příklad vytvoření obrázku čárového kódu"} + +## Krok 1: Inicializace generátoru – základy vytváření obrázku čárového kódu + +Prvním krokem je vytvořit instanci `BarCodeGenerator` s požadovanou symbologií. Pro symbol DataBar Omni‑directional použijete `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Proč je to důležité:** Vytvoření instance generátoru definuje pravidla kódování a datový payload. Pokud vynecháte správnou hodnotu `EncodeTypes`, knihovna vytvoří nepodporovaný čárový kód nebo vyhodí výjimku. + +## Krok 2: Nastavení X‑dimension a výšky čáry – kontrola velikosti obrázku čárového kódu + +Vizální velikost čárového kódu je určována dvěma parametry: + +| Parameter | Co řídí | Typický rozsah | +|-----------|---------|----------------| +| `x_dimension.pixels` | Šířka nejmenšího modulu (tzv. „tečka“) | 1 – 4 px | +| `bar_height.pixels` | Výška vertikálních čar | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Tip:** Menší X‑dimension poskytuje vyšší rozlišení obrázku, ale může být obtížnější načíst na tiskárnách nízké kvality. Hodnotu upravte podle cílového skenovacího zařízení. + +## Krok 3: Uložení prvního čárového kódu – vytvoření obrázku čárového kódu pro výšku 30 px + +Nyní můžete vygenerovat obrázek a zapsat jej na disk. Metoda `Save` přijímá cestu k souboru a výčtový typ formátu obrázku. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Očekávaný výsledek:** Soubor PNG s názvem `Databar30.png` se objeví v `C:\Barcodes`. Otevřením souboru se zobrazí symbol DataBar Omni‑directional s čistým, vysokokontrastním vzorem. + +## Krok 4: Změna výšky a generování dalších obrázků – vytvoření více čárových kódů + +Pro **vytvoření více čárových kódů** s různými rozměry stačí upravit vlastnost `BarHeight` a znovu zavolat `Save`. Tím se vyhnete opětovnému vytvoření instance generátoru, což šetří paměť a čas CPU. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Proč to funguje:** Objekt `BarCodeGenerator` uchovává celý konfigurační stav. Změna jedné vlastnosti aktualizuje renderovací engine pro další volání `Save`, což vám umožní efektivně **vytvářet více čárových kódů**. + +## Krok 5: Pokročilé – jak generovat DataBar s vlastním daty + +Výše uvedený příklad používá statický GS1 payload. V reálných scénářích často potřebujete vložit proměnné identifikátory produktů. Knihovna přijímá jakýkoli řetězec, který odpovídá specifikaci DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Klíčový bod:** Nastavení `generator.CodeText` aktualizuje kódovaná data bez nutnosti znovu vytvářet objekt. Toto je doporučený vzor **how to generate databar** při práci s velkými datovými sadami. + +## Krok 6: Ověření a řešení problémů – zajištění správné velikosti obrázku čárového kódu + +Po vygenerování obrázků můžete programově ověřit, že rozměry odpovídají vašim očekáváním. Třída `Image` z `System.Drawing` může soubor načíst a vrátit jeho velikost. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Pokud výška neodpovídá nastavené hodnotě, zkontrolujte: + +- **X‑dimension**: Velmi malá hodnota může způsobit, že renderér zaokrouhlí výšku. +- **Formát obrázku**: Některé formáty (např. JPEG) používají kompresi, která může při ukládání změnit rozměry v pixelech. PNG zachovává přesné rozměry. + +## Krok 7: Nejlepší postupy pro velikost obrázku čárového kódu a výkon + +| Recommendation | Reason | +|----------------|--------| +| Udržujte `x_dimension.pixels` mezi 2 – 3 px pro většinu skenerů. | Vyvažuje čitelnost a velikost souboru. | +| Používejte PNG pro bezztrátový výstup, pokud bude obrázek tištěn. | Zaručuje přesné rozměry a ostré hrany. | +| Znovu použijte jednu instanci `BarCodeGenerator` při generování mnoha čárových kódů. | Snižuje režii alokace objektů. | +| Ověřte vstupní řetězec podle standardu GS1 před přiřazením do `CodeText`. | Zabraňuje výjimkám za běhu a neplatným skenům. | +| Ukládejte vygenerované obrázky do vyhrazené složky s jasnou konvencí pojmenování (např. `Databar_{GTIN}.png`). | Zjednodušuje následné zpracování a auditní stopy. | + +## Kompletní funkční příklad + +Níže je kompletní program, který zahrnuje všechny kroky od inicializace po ověření. Zkopírujte kód do nového konzolového projektu a spusťte jej. + + + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Generovat obrázek čárového kódu – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Vytvořit obrázek DotCode čárového kódu – řádky a sloupce (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Jak vytvořit tichou zónu čárového kódu pro ITF-14 pomocí Aspose.BarCode pro .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/czech/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/czech/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..55e447ae1 --- /dev/null +++ b/barcode/czech/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-08-12 +description: Vytvořte omni‑directionální databar pomocí Pythonu a naučte se, jak vytvořit + obrázek čárového kódu v Pythonu pomocí Aspose.BarCode. Postupujte podle krok‑za‑krokem + průvodce pro kompletní řešení. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: cs +lastmod: 2026-08-12 +og_description: Vytvořte omnidirekční databar pomocí Pythonu a během několika minut + vygenerujte obrázek čárového kódu v Pythonu. Tento tutoriál ukazuje kompletní, spustitelný + příklad. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Vytvořte všesměrový datový panel – kompletní průvodce Pythonem +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Vytvořte všesměrový databar a obrázek čárového kódu v Pythonu +url: /cs/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření omni‑directional databar a obrázku čárového kódu v Pythonu + +Pokud potřebujete **vytvořit omni directional databar** v Python projektu, tento návod vám ukáže, jak na to, a také jak **vytvořit obrázek čárového kódu v Pythonu** pomocí knihovny Aspose.BarCode. Získáte připravený skript, který vygeneruje dva PNG soubory s různými poměry stran. + +Generování DataBaru podle specifikace Omni‑directional je běžnou požadavkem v maloobchodních a logistických aplikacích. Tutoriál pokrývá instalaci, nastavení X‑dimenze, úpravu poměru stran a uložení finálních obrázků. Nepotřebujete žádné externí služby; vše běží lokálně. + +## Co budete potřebovat + +Než začnete, ujistěte se, že máte: + +* Python 3.8 nebo novější nainstalovaný na vašem počítači. +* Přístup k terminálu nebo příkazovému řádku. +* Oprávnění k zápisu do složky, kam budou obrázky čárových kódů uloženy. + +Jedinou třetí stranou závislostí je **Aspose.BarCode for Python via .NET**, která podporuje typ Omni‑directional DataBar přímo z krabice. + +## Krok 1: Instalace Aspose.BarCode pro Python + +Aspose.BarCode poskytuje třídu `BarcodeGenerator`, která se používá v ukázkovém kódu. Nainstalujte balíček pomocí `pip`: + +```bash +pip install aspose-barcode +``` + +Balíček obsahuje potřebná .NET runtime vazby, takže není nutné instalovat .NET SDK samostatně. + +## Krok 2: Import knihovny a vytvoření generátoru + +První řádek skriptu vytvoří generátor pro vrstvený Omni‑directional DataBar. Jako ukázková data se používá hodnota GTIN‑14 `(01)12345678901231`. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Proč je tento krok důležitý*: Konstantní `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` říká knihovně, aby kódovala hodnotu jako Omni‑directional DataBar, což je formát požadovaný mnoha pokladními skenery. + +## Krok 3: Nastavení X‑dimenze (šířka modulu) + +X‑dimenze určuje šířku nejmenšího modulu čáry. Hodnota `2` pixelů vytváří čistý, čitelný čárový kód bez nadměrné velikosti souboru. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Proč je tento krok důležitý*: Úprava X‑dimenze vám umožní vyvážit čitelnost a rozměry obrázku. Příliš malá X‑dimenze může vést k špatnému vykreslení na nízkorozlišovacích tiskárnách. + +## Krok 4: Konfigurace poměru stran a uložení prvního obrázku + +Poměr stran ovlivňuje celkovou výšku DataBaru vzhledem k jeho šířce. Poměr `15` vytváří kompaktní vizuální styl. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Tip**: Použijte `pathlib.Path` pro vytvoření výstupní cesty, který automaticky vytvoří chybějící adresáře. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Krok 5: Změna poměru stran pro druhý vizuální styl a uložení dalšího obrázku + +Změna poměru stran na `30` vytvoří vyšší čárový kód, který může být vyžadován specifickým hardwarem skeneru. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Proč je tento krok důležitý*: Různí prodejci a skenovací zařízení mají odlišná omezení velikosti. Poskytnutí obou poměrů stran v jednom skriptu vám umožní vygenerovat požadovaný styl bez duplikace kódu. + +## Kompletní skript – vytvoření omni directional databar a obrázku čárového kódu v Pythonu + +Níže je kompletní, spustitelný příklad, který zahrnuje všechny předchozí kroky. Uložte jej jako `generate_databar.py` a spusťte pomocí `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Očekávaný výstup + +Po spuštění skriptu se vytvoří následující soubory: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Oba obrázky zobrazují platný Omni‑directional DataBar, který lze načíst standardním maloobchodním vybavením. + +![example of create omni directional databar barcode image in Python](example_databar.png "create omni directional databar barcode image python") + +*Výše uvedený obrázek je jen zástupný a ilustruje dva uložené PNG soubory.* + +## Řešení běžných problémů + +| Problém | Důvod | Řešení | +|---------|-------|--------| +| `ImportError: No module named aspose` | Aspose.BarCode není nainstalován nebo je nainstalován v jiném prostředí. | Aktivujte správné virtuální prostředí a spusťte `pip install aspose-barcode`. | +| `PermissionError` při ukládání | Skript nemá oprávnění k zápisu do cílové složky. | Vyberte adresář, ke kterému máte přístup, nebo spusťte skript s potřebnými oprávněními. | +| Čárový kód se nenačte | X‑dimenze je příliš malá nebo poměr stran nevyhovuje skeneru. | Zvyšte `x_dimension.pixels` na 3 nebo 4 a vyzkoušejte různé hodnoty `aspect_ratio` (např. 20, 25). | +| Chybí .NET runtime | Aspose.BarCode závisí na .NET runtime na Windows/Linux. | Nainstalujte nejnovější .NET runtime z webu Microsoft; dokumentace balíčku poskytuje platformně specifické pokyny. | + +## Rozšíření příkladu + +Můžete upravit skript tak, aby generoval jiné varianty DataBaru (např. `DATABAR_STACKED`, `DATABAR_EXPANDED`). Nahraďte konstantu `EncodeTypes` odpovídající hodnotou: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Pokud potřebujete vložit čárový kód do PDF, Aspose.PDF pro Python dokáže importovat PNG soubor přímo, nebo můžete použít metodu `save` s parametrem `BarCodeImageFormat.Pdf`. + +## Závěr + +Tento tutoriál ukázal, jak **vytvořit omni directional databar** a jak **vytvořit obrázek čárového kódu v Pythonu** pomocí Aspose.BarCode. Nyní máte kompletní, reprodukovatelný skript, který generuje dva PNG soubory s různými poměry stran, řeší běžné problémy a lze jej rozšířit na další formáty čárových kódů. + +Dále můžete zkoumat generování QR kódů, přidávání čárových kódů do PDF faktur nebo automatizaci hromadného zpracování velkých katalogů produktů. Všechny tyto témata staví na stejném vzoru `BarcodeGenerator`, který byl zde předveden. Šťastné programování! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobným krok‑za‑krokem vysvětlením, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vlastních projektech. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to create barcode image and render it in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/czech/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/czech/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..79d7d0d6a --- /dev/null +++ b/barcode/czech/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-08-12 +description: Jak rychle generovat čárový kód pomocí Pythonu. Naučte se vytvořit čárový + kód z dat a exportovat obrázek čárového kódu pomocí jediné knihovny. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: cs +lastmod: 2026-08-12 +og_description: Jak generovat čárový kód v Pythonu pomocí Aspose.BarCode. Postupujte + podle tohoto návodu k vytvoření čárového kódu z dat a exportu obrázku čárového kódu + jako PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Jak generovat čárový kód v Pythonu – rychlý, spolehlivý průvodce +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Jak vygenerovat čárový kód v Pythonu – kompletní krok za krokem průvodce +url: /cs/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak generovat čárový kód v Pythonu – kompletní průvodce krok za krokem + +Pokud potřebujete **jak generovat čárový kód** v aplikaci Python, tento tutoriál vám ukáže přesný kód, který potřebujete. Naučíte se **vytvořit čárový kód z dat**, upravit jeho vzhled a **exportovat obrázek čárového kódu** jako soubor PNG – vše během méně než deseti řádků kódu. + +Generování čárového kódu se může zdát jako samostatná záležitost oddělená od zbytku vaší obchodní logiky, ale s jednou knihovnou můžete proces udržet v souladu s vaším stávajícím kódem. V následujících sekcích uvidíte kompletní, spustitelný příklad, pochopíte, proč je každý řádek důležitý, a objevíte běžné varianty, jako je změna šířky modulu nebo vykreslení čárového kódu pouze s obrysem. + +## Jak generovat čárový kód pomocí knihovny Aspose.BarCode + +Knihovna Aspose.BarCode pro Python (prostřednictvím .NET) poskytuje jednoduché API pro mnoho symbologií, včetně čárového kódu Planet použitého v tomto průvodci. Předtím, než začnete, ujistěte se, že máte balíček nainstalovaný: + +```bash +pip install aspose-barcode +``` + +> **Pro tip:** Použijte virtuální prostředí, abyste se vyhnuli konfliktům verzí s jinými projekty. + +### 1. Importujte požadované třídy + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Tyto importy vám poskytují přístup ke třídě generátoru, výčtu typů čárových kódů a výčtu formátů obrázků, který se používá při ukládání výsledku. + +### 2. Vytvořte čárový kód z dat + +Prvním krokem je **vytvořit čárový kód z dat**. Konstruktor `BarcodeGenerator` přijímá symbologii a surový řetězec, který chcete zakódovat. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +Hodnota `EncodeTypes.Planet` vybírá čárový kód Planet, zatímco `"123456"` je payload, který se objeví ve výsledném obrázku. + +### 3. Nastavte X‑dimenzi (šířka modulu) + +X‑dimenze řídí šířku každého modulu čárového kódu (tenké čáry). Nastavením na 4 pixely získáte čistý, čitelný obrázek, aniž by soubor byl příliš velký. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Proč je to důležité:** Větší X‑dimenze zlepšuje spolehlivost skenování na tiskárnách s nízkým rozlišením, zatímco menší hodnota snižuje velikost souboru pro webové použití. + +### 4. Exportujte obrázek čárového kódu (vyplněný styl) + +Nyní můžete **exportovat obrázek čárového kódu** pomocí metody `save`. Příklad ukládá soubor PNG, ale můžete zvolit JPEG, BMP nebo TIFF změnou výčtu `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +Soubor `PlanetFilled.png` obsahuje plně vyplněný čárový kód Planet, připravený k tisku nebo vložení do PDF. + +### 5. Vytvořte druhý generátor pro čárový kód pouze s obrysem + +Pokud potřebujete verzi s obrysem (prázdné čáry), musíte vytvořit nový generátor, protože příznak `filled_bars` nelze po uložení obrázku změnit. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Použijte stejné nastavení X‑dimenze + +Když vytvoříte druhý generátor, musíte zopakovat všechna vizuální nastavení, která chcete zachovat konzistentní. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Zakázat vyplněné čáry pro čárový kód s obrysem + +Nastavením `filled_bars` na `False` řeknete rendereru, aby kreslil pouze obrysy každého modulu, což vytvoří lehčí obrázek, který může být užitečný pro designové účely. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Exportujte obrázek čárového kódu s obrysem + +Nakonec **exportujte obrázek čárového kódu** znovu, tentokrát ukládající verzi s obrysem. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Nyní máte dva soubory PNG: jeden s plnými čarami (`PlanetFilled.png`) a jeden pouze s obrysy (`PlanetEmpty.png`). + +## Exportujte obrázek čárového kódu v jiných formátech (volitelné) + +Metoda `save` podporuje několik formátů. Pro export jako JPEG s 90 % kvalitou: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Pokud potřebujete průhledné pozadí pro webové použití, zvolte PNG s alfa kanálem: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Běžné varianty a okrajové případy + +| Scénář | Požadovaná změna | Code snippet | +|----------|---------------|--------------| +| **Různá symbologie** (např. QR) | Použít jinou hodnotu `EncodeTypes` | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Vlastní barva popředí** | Nastavit `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Vyšší rozlišení** | Zvýšit DPI pomocí `image_width` a `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Dlouhé řetězce dat** | Zajistit, aby délka dat odpovídala specifikaci symbologie | Validate length before creating the generator | + +> **Pozor na:** Poskytnutí dat, která překračují maximální délku pro zvolenou symbologii, vyvolá výjimku za běhu. Vždy ověřujte délku řetězce nebo zachyťte `ArgumentException`. + +## Kompletní, spustitelný příklad + +Níže je kompletní skript, který můžete zkopírovat a vložit do souboru pojmenovaného `generate_planet_barcode.py`. Upravit `YOUR_DIRECTORY` na složku, která existuje ve vašem počítači. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Spuštěním tohoto skriptu se v určeném adresáři vytvoří dva soubory PNG. Ověřte výstup otevřením obrázků v libovolném prohlížeči obrázků; oba by měly zobrazovat čárový kód Planet kódující řetězec `123456`. + +## Závěr + +Nyní víte, **jak generovat čárový kód** v Pythonu pomocí Aspose.BarCode, **jak vytvořit čárový kód z dat** a **jak exportovat obrázek čárového kódu** jak ve vyplněném, tak v obrysovém stylu. Stejný vzor platí pro jiné symbologie, formáty obrázků a vizuální úpravy, což vám poskytuje flexibilní základ pro jakoukoli funkci související s čárovými kódy ve vaší aplikaci. + +### Další kroky + +* Prozkoumejte další symbologie, jako jsou QR, Code‑128 nebo DataMatrix, výměnou `EncodeTypes.Planet` za požadovanou hodnotu. +* Integrovat vygenerované soubory PNG do PDF reportů pomocí knihoven jako `ReportLab` nebo `PyPDF2`. +* Experimentujte s dynamickými hodnotami X‑dimenze pro přizpůsobení velikosti čárového kódu podle rozlišení obrazovky nebo DPI tiskárny. + +Šťastné programování a neváhejte upravit příklad tak, aby vyhovoval vašim vlastním požadavkům projektu! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Jak generovat obrázek čárového kódu v Javě s Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Jak generovat čárový kód v Javě – Kompletní průvodce konfigurací](/barcode/english/java/barcode-configuration/) +- [Jak vytvořit obrázky čárových kódů code128 v Javě s Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/dutch/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/dutch/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..10ceaa09a --- /dev/null +++ b/barcode/dutch/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-08-12 +description: Barcodegenerator‑voorbeeld dat laat zien hoe je een barcode genereert + met precieze pixelgrootte. Leer hoe je de modulebreedte, balkhoogte instelt en Planet‑barcodes + maakt. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: nl +lastmod: 2026-08-12 +og_description: Barcode‑generatorvoorbeeld toont hoe je een barcode met exacte pixelafmetingen + genereert. Volg deze gids om de modulebreedte en balkhoogte voor Planet‑ en RM4SCC‑codes + te regelen. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: barcode‑generatorvoorbeeld – pas pixelgrootte aan in C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: barcodegenerator‑voorbeeld – stapsgewijze handleiding voor aangepaste pixelgroottes +url: /nl/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# barcode generator voorbeeld – stapsgewijze gids voor aangepaste pixelgroottes + +Als je een **barcode generator voorbeeld** nodig hebt dat je elke pixel kunt laten controleren, laat deze gids precies zien hoe je dat doet. Je leert de modulebreedte in te stellen, een vaste balkhoogte te definiëren en zowel Planet- als RM4SCC-barcodes te genereren met voorspelbare afmetingen. + +De meeste ontwikkelaars worstelen met “how to generate barcode” afbeeldingen die er op elk scherm of elke printer hetzelfde uitzien. De code‑fragmenten hieronder lossen dat probleem op door de pixel‑niveau parameters van de Aspose.BarCode for .NET bibliotheek bloot te leggen, zodat je consistente output kunt produceren zonder giswerk. + +## Wat je zult leren + +* Hoe het vereiste NuGet‑pakket te installeren. +* Hoe een Planet‑barcode te genereren met automatisch berekende hoogte. +* Hoe een Planet‑barcode te genereren met een expliciete hoogte van 100 pixel. +* Hoe een RM4SCC‑barcode te genereren met dezelfde expliciete hoogte. +* Waarom **barcode pixel size** belangrijk is voor de betrouwbaarheid van het scannen. +* Tips voor het oplossen van veelvoorkomende problemen bij het genereren van Planet‑barcode‑afbeeldingen. + +Je hebt alleen .NET 6 of later nodig, een basis C#‑ontwikkelomgeving, en een internetverbinding om het NuGet‑pakket te downloaden. + +--- + +## barcode generator voorbeeld – ontwikkelomgeving instellen + +Voordat je code schrijft, zorg ervoor dat de Aspose.BarCode‑bibliotheek beschikbaar is voor je project. + +### Installeer het Aspose.BarCode‑pakket + +Open een terminal in je projectmap en voer uit: + +```bash +dotnet add package Aspose.BarCode +``` + +Het commando voegt de nieuwste stabiele versie van **Aspose.BarCode** toe aan je `csproj`. Nadat het herstel is voltooid, kun je de `BarcodeGenerator`‑klasse gaan gebruiken. + +> **Pro tip:** Richt je op .NET 6 of .NET 7 om te profiteren van de nieuwste prestatie‑verbeteringen en de standaard UTF‑8‑afhandeling. + +### Voeg de benodigde `using`‑directieven toe + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Deze namespaces maken de `BarcodeGenerator`‑klasse en de `BarCodeImageFormat`‑enum beschikbaar die later in de tutorial worden gebruikt. + +## Hoe een barcode te genereren met aangepaste pixelgrootte + +De volgende drie stappen illustreren het volledige **barcode generator voorbeeld**. Elke stap bouwt voort op de vorige, zodat je het hele blok kunt kopiëren‑plakken in een console‑app en ongewijzigd kunt uitvoeren. + +### Stap 1 – genereer een Planet‑barcode met automatisch berekende hoogte + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Waarom dit werkt:** +*De `XDimension`‑eigenschap definieert de breedte van een enkele barcode‑module (het kleinste zwarte of witte element). Wanneer je `BarHeight` weglaten, berekent de bibliotheek een hoogte die de standaard beeldverhouding voor Planet‑codes behoudt.* + +**Verwachte output:** Een PNG‑bestand met de naam `PlanetAuto.png` dat een schone Planet‑barcode bevat. De hoogte past zich aan de 4‑pixel module‑breedte aan, meestal rond de 60 pixels voor een payload van zes tekens. + +### Stap 2 – genereer een Planet‑barcode met een expliciete hoogte van 100 pixel + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Waarom je dit nodig zou kunnen hebben:** +Soms verwacht de scanapparatuur een minimale balkhoogte voor betrouwbare detectie. Door `BarHeight.Pixels` in te stellen, garandeer je dat elke gegenereerde afbeelding aan die eis voldoet, ongeacht de lengte van de gecodeerde gegevens. + +**Verwachte output:** `PlanetHeight100.png` toont dezelfde gegevens als eerder, maar de balken zijn precies 100 pixels hoog, waardoor je volledige controle hebt over de visuele grootte. + +### Stap 3 – genereer een RM4SCC‑barcode met dezelfde expliciete hoogte + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Waarom dit belangrijk is:** +`EncodeTypes.RM4SCC` is een gestapelde lineaire barcode die in de logistiek wordt gebruikt. Het afstemmen van de balkhoogte op die van de Planet‑barcode vereenvoudigt batchverwerking wanneer beide symbolen op hetzelfde label verschijnen. + +**Verwachte output:** `RM4SCCHeight100.png` toont een perfect formaat RM4SCC‑barcode, die overeenkomt met de 100‑pixel hoogte die je voor de Planet‑code hebt ingesteld. + +> **Resultaatverificatie:** Open elke PNG in een afbeeldingsviewer en bevestig dat de zwarte balken precies 4 pixels breed zijn en, waar je dat hebt opgegeven, 100 pixels hoog. Je kunt de bestanden ook aan een barcode‑scanner‑app voeren om te controleren of ze decoderen naar “123456”. + +--- + +## Begrijpen van barcode pixelgrootte en balkhoogte + +### Wat is **barcode pixel size**? + +*Pixelgrootte* verwijst naar het fysieke aantal scherm‑ of printerpixels dat een enkele module (`XDimension`) representeert. Een grotere pixelgrootte levert een grotere barcode op, wat gemakkelijker kan zijn voor scanners met lage resolutie, maar meer labelruimte verbruikt. + +### Hoe beïnvloedt `BarHeight` de leesbaarheid? + +De `BarHeight`‑eigenschap regelt de verticale lengte van de balken. Normen voor de meeste 1‑D‑barcodes (inclusief Planet en RM4SCC) bevelen een minimale hoogte van 10 mm aan bij afdrukken op 300 dpi, wat ongeveer 118 pixels is. Een hoogte lager dan dat kan leesfouten veroorzaken, vooral bij mobiele camera's. + +### Wanneer moet je de bibliotheek de hoogte automatisch laten berekenen? + +Als je barcodes alleen voor weergave op het scherm genereert, houdt de automatische berekening de beeldverhouding consistent en vermindert het de hoeveelheid handmatige aanpassingen die nodig zijn. Voor afgedrukte labels die moeten voldoen aan strikte ISO‑specificaties, moet je **expliciet de balkhoogte instellen**. + +## Veelvoorkomende valkuilen en best practices bij het genereren van Planet‑barcode + +| Valkuil | Waarom het gebeurt | Oplossing | +|---------|--------------------|-----------| +| Balken verschijnen te dun of te dik | `XDimension` blijft op de standaardwaarde (1 pixel) op hoge‑resolutie displays | Stel `XDimension.Pixels` in op minimaal 3‑4 voor visuele duidelijkheid | +| Scanner kan de code niet lezen | `BarHeight` is te klein voor de brandpuntsafstand van de scanner | Gebruik `BarHeight.Pixels` ≥ 100 voor de meeste mobiele scanners | +| Afbeelding is onscherp na schalen | Opslaan als JPEG introduceert compressie‑artefacten | Sla op als PNG (`BarCodeImageFormat.Png`) voor verliesvrije output | +| Onverwacht barcode‑type | Verkeerde `EncodeTypes`‑enumwaarde | Controleer dubbel of je `EncodeTypes.Planet` gebruikt voor Planet‑symboliek | + +### Pro tip voor prestaties + +Wanneer je duizenden barcodes genereert in een batch‑taak, hergebruik dan een enkele `BarcodeGenerator`‑instantie en wijzig alleen de `CodeText`‑ en grootte‑parameters tussen opslagen. Dit voorkomt herhaalde toewijzing van interne renderobjecten en kan de uitvoeringstijd met tot 30 % verkorten. + +## Volledig werkend voorbeeld – alles samenvoegen + +Maak een nieuw console‑project (`dotnet new console -n BarcodeDemo`) en vervang de inhoud van `Program.cs` door het volgende: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Voer het programma uit met `dotnet run`. Na uitvoering vind je drie PNG‑bestanden in de projectmap, elk illustrerend een ander **barcode generator voorbeeld** scenario. + +## Volgende stappen en gerelateerde onderwerpen + +* **How to generate barcode in other formats** – verken `EncodeTypes.Code128`, `EncodeTypes.QR` en `EncodeTypes.DataMatrix` voor 2‑D‑behoeften. +* **Embedding barcodes in PDFs** – combineer Aspose.BarCode met Aspose.PDF om barcodes direct op factuursjablonen te plaatsen. +* **Dynamic barcode size based on user input** – bereken + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe barcode genereren java: Maak een exacte barcode‑afbeelding](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [Hoe barcode genereren in Java: Maak en stel de grootte in voor de volledige afbeelding](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [Hoe een code128‑barcode maken in Java en de balkhoogte instellen](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/dutch/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/dutch/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..2d9cefaad --- /dev/null +++ b/barcode/dutch/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: Configureer de Databar-barcode-indeling snel in Python. Leer kolommen + en rijen instellen en afbeeldingen opslaan met de barcode-generatorbibliotheek. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: nl +lastmod: 2026-08-12 +og_description: Configureer de Databar‑barcode‑indeling in Python om kolommen, rijen + en afbeeldingoutput te beheren. Volg deze gids voor een kant‑klaar oplossing. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Configureer Databar barcode‑indeling in Python – volledige tutorial +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Configureer Databar‑barcode‑indeling in Python – stapsgewijze handleiding +url: /nl/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Configureer Databar barcode lay-out in Python – stapsgewijze handleiding + +Als je **Databar barcode lay-out in Python** moet configureren, leidt deze gids je door het volledige proces. Je ziet hoe je het aantal kolommen of rijen voor een Databar Expanded Stacked barcode instelt en hoe je de resulterende afbeelding opslaat met één aanroep van de barcode‑generatorbibliotheek. + +Het beheersen van de lay-out is essentieel wanneer je barcodes op smalle verpakkingen, bonnen of mobiele schermen embedt. In de onderstaande secties behandelen we de benodigde imports, de twee lay-outopties (kolommen en rijen) en de best practices voor het opslaan van een schone PNG‑afbeelding. + +## Wat je nodig hebt + +* Python 3.8 of nieuwer +* `aspose.barcode` (of een compatibel barcode‑generatiepakket) geïnstalleerd + ```bash + pip install aspose-barcode + ``` +* Schrijfrechten voor een map waar de PNG‑bestanden worden opgeslagen + +Er zijn geen extra externe tools nodig — de bibliotheek behandelt rendering, schaling en beeldcodering intern. + +## Hoe Databar barcode lay-out in Python te configureren + +De kern van de oplossing is de `BarcodeGenerator`‑klasse. Deze accepteert een `EncodeTypes`‑enum die de barcode‑symbologie identificeert — in dit geval `EncodeTypes.DatabarExpandedStacked`. Na het aanmaken van de generator kun je de lay-out aanpassen door de `columns`‑ of `rows`‑eigenschappen in te stellen op het `data_bar`‑parameterobject. + +### Stap 1: Importeer de vereiste klassen + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Deze imports geven je toegang tot de generator, de enumeratie voor Databar‑typen, en de constante voor het PNG‑afbeeldingsformaat. + +### Stap 2: Maak een barcode‑generator voor Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Waarom deze stap?* +`EncodeTypes.DatabarExpandedStacked` vertelt de bibliotheek om de **Databar Expanded Stacked**‑symbologie te produceren, die langere numerieke tekenreeksen ondersteunt terwijl hij een compacte footprint behoudt. Het tweede argument is de te coderen data; dit kan elke string zijn die voldoet aan de Databar‑specificatie. + +### Stap 3: Stel het aantal kolommen in (horizontale lay-out) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** is de sleutelzin voor deze bewerking. Wanneer je het aantal kolommen verhoogt, spreidt de barcode zich horizontaal uit, wat nuttig kan zijn voor brede etiketten. De bibliotheek berekent automatisch de module‑breedte opnieuw om de totale grootte consistent te houden. + +#### Pro‑tip +Het maximale aantal kolommen voor Databar Expanded Stacked is 8. Een waarde hoger dan de limiet wordt begrensd tot het maximum, maar het is beter om je invoer vooraf te valideren. + +### Stap 4: Sla de barcode‑afbeelding op met de kolom‑lay-out + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** is de actie die de gerenderde barcode naar schijf schrijft. PNG is verliesloos, waardoor de scherpe randen behouden blijven die nodig zijn voor betrouwbare scanning. + +### Stap 5: Maak een tweede generator voor hetzelfde barcode‑type (rij‑lay-out) + +Als je de voorkeur geeft aan een verticale stapeling, werk je met rijen in plaats van kolommen. De onderstaande code hergebruikt dezelfde waarde maar maakt een nieuwe `BarcodeGenerator`‑instantie aan om het mengen van kolom‑ en rij‑instellingen te voorkomen. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Stap 6: Stel het aantal rijen in (verticale lay-out) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** rangschikt de barcode‑modules verticaal. Een lay-out met drie rijen verkleint de hoogte van elke individuele stapel, waardoor de barcode geschikt is voor smalle bonnen of mobiele schermen. + +#### Randgeval +Als je `rows` op 1 zet, genereert de bibliotheek een één‑rij Databar (equivalent aan een standaard Databar). Waarden onder 1 worden genegeerd en teruggezet naar de standaard (1 rij). + +### Stap 7: Sla de barcode‑afbeelding op met de rij‑lay-out + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Opnieuw gebruiken we **save barcode image** met PNG om de output scherp te houden. + +## Volledig uitvoerbaar voorbeeld + +Alle onderdelen samenvoegen levert een zelfstandige script op die je in elk Python‑project kunt plaatsen. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Verwachte output** + +Het uitvoeren van het script maakt twee PNG‑bestanden aan: + +* `output/ExpandedCols4.png` – een barcode uitgerekt over vier kolommen +* `output/ExpandedRows3.png` – een barcode samengeperst in drie rijen + +Beide afbeeldingen kunnen worden geopend in elke afbeeldingsviewer of direct worden geïmporteerd in PDF‑facturen, etiket‑templates of webpagina's. + +## Veelgestelde vragen en probleemoplossing + +| Vraag | Antwoord | +|----------|--------| +| *Wat als de barcode er onscherp uitziet?* | Verhoog de beeldresolutie door `barcode_generator.parameters.image_width` en `image_height` in te stellen vóór het aanroepen van `save`. | +| *Kan ik andere afbeeldingsformaten gebruiken?* | Ja. Vervang `BarCodeImageFormat.Png` door `Jpeg`, `Bmp` of `Gif` indien nodig. | +| *Is er een limiet op de datalengte?* | Databar Expanded Stacked ondersteunt tot 74 numerieke tekens. Het overschrijden van de limiet veroorzaakt een `ArgumentException`. | +| *Hoe wijzig ik de voorgrondkleur?* | Gebruik `barcode_generator.parameters.barcode.color = Color.Blue` (import `System.Drawing.Color`). | +| *Kan ik kolommen en rijen combineren?* | Nee. De API behandelt kolommen en rijen als onderling exclusieve lay-outmodi. Kies er één per barcode‑instantie. | + +## Volgende stappen + +Nu je **Databar barcode lay-out** kunt **configureren**, overweeg dan deze gerelateerde onderwerpen: + +* **Tekstbijschriften toevoegen** – gebruik `barcode_generator.parameters.barcode.code_text` om de gecodeerde waarde onder de afbeelding weer te geven. +* **De barcode in een PDF embedden** – combineer de gegenereerde PNG met `aspose.pdf` om afdrukbare documenten te maken. +* **Dynamische grootte** – bereken optimale kolom‑ of rij‑aantallen op basis van labelafmetingen tijdens runtime. +* **Batchverwerking** – loop over een CSV met productcodes om automatisch een bibliotheek van barcode‑afbeeldingen te genereren. + +Experimenteer met verschillende kolom‑ en rij‑waarden om te zien hoe ze de scanbetrouwbaarheid op je doelsystemen beïnvloeden. Hoe meer je test, hoe beter je de afwegingen tussen barcode‑grootte, leesbaarheid en ruimtebeperkingen begrijpt. + +--- + +*Happy coding! Als je deze tutorial nuttig vond, deel hem dan met teamgenoten of laat een reactie achter over de lay‑outuitdagingen die je bent tegengekomen.* + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap‑uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Maak DotCode barcode afbeelding – rijen & kolommen (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Maak barcode afbeelding c# – Configureer Codablock F rijen & kolommen](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [Eéndimensionale Databar barcode hoogte‑aanpassing](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/dutch/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/dutch/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..b39a8eaae --- /dev/null +++ b/barcode/dutch/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: Maak een barcode-afbeelding in C# met BarCodeGenerator. Leer hoe je DataBar + genereert, de grootte van de barcode-afbeelding regelt en efficiënt meerdere barcodes + maakt. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: nl +lastmod: 2026-08-12 +og_description: Maak een barcode‑afbeelding in C# met BarCodeGenerator. Deze tutorial + laat stap‑voor‑stap zien hoe je DataBar‑codes genereert, de grootte van de barcode‑afbeelding + aanpast en meerdere barcodes maakt. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Barcode‑afbeelding maken in C# – volledige BarCodeGenerator‑gids +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Barcode-afbeelding maken in C# met BarCodeGenerator +url: /nl/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode-afbeelding maken in C# met BarCodeGenerator + +Als je een **barcode-afbeelding** moet maken in een .NET‑applicatie, laat deze gids je precies zien hoe je dat doet met de `BarCodeGenerator`‑klasse. Of je nu een retail‑POS‑systeem of een voorraad‑volgtool bouwt, je leert DataBar‑symbolen genereren, de grootte van de barcode‑afbeelding regelen en meerdere barcodes in één keer produceren. + +Je ontdekt ook hoe de **barcode generator c#**‑API je in staat stelt afmetingen aan te passen, uitvoerformaten te wisselen en randgevallen zoals ongeldige gegevensreeksen af te handelen. Aan het einde van de tutorial kun je vol vertrouwen **meerdere barcodes maken** zonder repetitieve code te schrijven. + +## Vereisten + +- .NET 6.0 of later geïnstalleerd +- Een ontwikkelomgeving (Visual Studio, Rider of VS Code) +- Het Aspose.BarCode for .NET NuGet‑pakket (of een compatibele bibliotheek die `BarCodeGenerator` levert) + +Je kunt het pakket toevoegen met: + +```bash +dotnet add package Aspose.BarCode +``` + +## Wat deze tutorial behandelt + +1. Een **barcode generator c#**‑instantie instellen voor DataBar Omni‑directionele codering. +2. De **barcode‑afbeeldingsgrootte** aanpassen door X‑dimensie en balkhoogte te wijzigen. +3. Een lus gebruiken om **meerdere barcodes** met verschillende hoogtes te **maken**. +4. De afbeeldingen opslaan als PNG‑bestanden en de output verifiëren. + +Alle code‑fragmenten zijn compleet en klaar om te kopiëren‑en‑plakken in een nieuw console‑project. + +![Create barcode image example](barcode-example.png){alt="Voorbeeld van barcode‑afbeelding maken"} + +## Stap 1: Initialiseer de generator – basis van barcode‑afbeelding maken + +De eerste stap is om `BarCodeGenerator` te instantieren met de gewenste symbologie. Voor een DataBar Omni‑directionaal symbool gebruik je `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Waarom dit belangrijk is:** Het instantieren van de generator definieert de coderingsregels en de gegevenspayload. Als je de juiste `EncodeTypes`‑waarde weglaat, zal de bibliotheek een niet‑ondersteunde barcode produceren of een uitzondering werpen. + +## Stap 2: X‑dimensie en balkhoogte configureren – barcode‑afbeeldingsgrootte regelen + +De visuele grootte van een barcode wordt bepaald door twee parameters: + +| Parameter | Wat het regelt | Typisch bereik | +|-----------|----------------|----------------| +| `x_dimension.pixels` | Breedte van de kleinste module (de “dot”) | 1 – 4 px | +| `bar_height.pixels` | Hoogte van de verticale balken | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Pro tip:** Een kleinere X‑dimensie levert een hogere resolutie‑afbeelding op, maar kan moeilijker te scannen zijn op printers van lage kwaliteit. Pas de waarde aan op basis van je beoogde scanapparatuur. + +## Stap 3: Sla de eerste barcode op – barcode‑afbeelding maken voor 30 px hoogte + +Nu kun je de afbeelding genereren en naar schijf schrijven. De `Save`‑methode accepteert een bestandspad en een afbeeldingsformaat‑enum. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Verwacht resultaat:** Een PNG‑bestand met de naam `Databar30.png` verschijnt in `C:\Barcodes`. Het openen van het bestand toont een DataBar Omni‑directionaal symbool met een duidelijk, hoog‑contrast patroon. + +## Stap 4: Verander de hoogte en genereer extra afbeeldingen – meerdere barcodes maken + +Om **meerdere barcodes** met verschillende afmetingen te **maken**, hoef je alleen de `BarHeight`‑eigenschap aan te passen en `Save` opnieuw aan te roepen. Dit voorkomt het opnieuw instantieren van de generator, wat geheugen en CPU‑tijd bespaart. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Waarom dit werkt:** Het `BarCodeGenerator`‑object bewaart alle configuratiestatus. Het wijzigen van één eigenschap werkt de renderengine bij voor de volgende `Save`‑aanroep, waardoor je **meerdere barcodes** efficiënt kunt **maken**. + +## Stap 5: Geavanceerd – hoe DataBar te genereren met aangepaste data + +Het bovenstaande voorbeeld gebruikt een statische GS1‑payload. In real‑world scenario's moet je vaak variabele productidentifiers insluiten. De bibliotheek accepteert elke string die voldoet aan de DataBar‑specificatie. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Belangrijk punt:** Het instellen van `generator.CodeText` werkt de gecodeerde data bij zonder het object opnieuw te maken. Dit is het aanbevolen **hoe je databar genereert**‑patroon bij het verwerken van grote datasets. + +## Stap 6: Verifiëren en oplossen – zorgen voor correcte barcode‑afbeeldingsgrootte + +Na het genereren van de afbeeldingen wil je mogelijk programmatisch bevestigen dat de afmetingen overeenkomen met je verwachtingen. De `Image`‑klasse uit `System.Drawing` kan het bestand lezen en de grootte rapporteren. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Als de hoogte niet overeenkomt met de ingestelde waarde, controleer dan: + +- **X‑dimensie**: Een zeer kleine waarde kan ervoor zorgen dat de renderer de hoogte afrondt. +- **Afbeeldingsformaat**: Sommige formaten (bijv. JPEG) passen compressie toe die de pixelafmetingen bij het opslaan kan wijzigen. PNG behoudt exacte afmetingen. + +## Stap 7: Best practices voor barcode‑afbeeldingsgrootte en prestaties + +| Aanbeveling | Reden | +|------------|-------| +| Houd `x_dimension.pixels` tussen 2 – 3 px voor de meeste scanners. | Balans tussen leesbaarheid en bestandsgrootte. | +| Gebruik PNG voor lossless output wanneer de afbeelding wordt afgedrukt. | Garandeert exacte afmetingen en scherpe randen. | +| Hergebruik een enkele `BarCodeGenerator`‑instantie bij het genereren van veel barcodes. | Vermindert overhead van objectallocatie. | +| Valideer de invoerstring tegen de GS1‑standaard voordat je deze toewijst aan `CodeText`. | Voorkomt runtime‑exceptions en ongeldige scans. | +| Sla gegenereerde afbeeldingen op in een speciale map met een duidelijke naamgevingsconventie (bijv. `Databar_{GTIN}.png`). | Vereenvoudigt downstream verwerking en audit‑trails. | + +## Volledig werkend voorbeeld + +Hieronder staat het volledige programma dat alle stappen van initialisatie tot verificatie bevat. Kopieer de code naar een nieuw console‑project en voer het uit. + + + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Barcode‑afbeelding genereren – GS1 Coupon UPC‑A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode barcode‑afbeelding maken – rijen & kolommen (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Hoe een Barcode Quiet Zone te maken voor ITF‑14 met Aspose.BarCode voor .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/dutch/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/dutch/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..c74984a9b --- /dev/null +++ b/barcode/dutch/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-08-12 +description: Maak een omnidirectionele databar met Python en leer hoe je een barcode‑afbeelding + maakt met Python met behulp van Aspose.BarCode. Volg de stap‑voor‑stap‑handleiding + voor een complete oplossing. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: nl +lastmod: 2026-08-12 +og_description: Maak een omni-directionele databar met Python en genereer in enkele + minuten een barcode‑afbeelding met Python. Deze tutorial toont een volledig, uitvoerbaar + voorbeeld. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Creëer een omnidirectionele databar – volledige Python‑gids +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Maak omni-directionele databar- en barcode-afbeelding in Python +url: /nl/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak omni-directionele databar en barcode‑afbeelding in Python + +Als je een **omni-directionele databar** wilt **maken** in een Python‑project, laat deze gids je zien hoe je dat doet en ook hoe je een **barcode‑afbeelding in Python** maakt met de Aspose.BarCode‑bibliotheek. Je krijgt een kant‑klaar script dat twee PNG‑bestanden met verschillende beeldverhoudingen genereert. + +Het genereren van een DataBar die voldoet aan de Omni‑directionele specificatie is een veelvoorkomende eis voor retail‑ en logistieke toepassingen. De tutorial behandelt installatie, configuratie van de X‑dimensie, aanpassing van de beeldverhouding en het opslaan van de uiteindelijke afbeeldingen. Er zijn geen externe services nodig; alles draait lokaal. + +## Wat je nodig hebt + +* Python 3.8 of nieuwer geïnstalleerd op je machine. +* Toegang tot een terminal of opdrachtprompt. +* Schrijfrechten voor een map waar de barcode‑afbeeldingen worden opgeslagen. + +De enige externe afhankelijkheid is **Aspose.BarCode for Python via .NET**, die het Omni‑directionele DataBar‑type direct ondersteunt. + +## Stap 1: Installeer Aspose.BarCode voor Python + +Aspose.BarCode biedt de `BarcodeGenerator`‑klasse die in de voorbeeldcode wordt gebruikt. Installeer het pakket met `pip`: + +```bash +pip install aspose-barcode +``` + +Het pakket bevat de benodigde .NET‑runtime‑bindings, zodat je de .NET SDK niet apart hoeft te installeren. + +## Stap 2: Importeer de bibliotheek en maak de generator + +De eerste regel van het script maakt een generator voor een gestapelde Omni‑directionele DataBar. De GTIN‑14‑waarde `(01)12345678901231` wordt als voorbeeldgegevens gebruikt. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Waarom deze stap belangrijk is*: De constante `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` vertelt de bibliotheek de waarde te coderen als een Omni‑directionele DataBar, het formaat dat door veel point‑of‑sale scanners wordt vereist. + +## Stap 3: Stel de X‑dimensie (module‑breedte) in + +De X‑dimensie bepaalt de breedte van de kleinste balkmodule. Een waarde van `2` pixels levert een duidelijke, leesbare barcode op zonder een buitensporige bestandsgrootte. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Waarom deze stap belangrijk is*: Het aanpassen van de X‑dimensie stelt je in staat de leesbaarheid en afbeeldingsgrootte in balans te brengen. Een X‑dimensie die te klein is, kan slecht renderen op printers met lage resolutie. + +## Stap 4: Configureer de beeldverhouding en sla de eerste afbeelding op + +De beeldverhouding beïnvloedt de totale hoogte van de DataBar ten opzichte van de breedte. Een beeldverhouding van `15` creëert een compacte visuele stijl. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Pro tip**: Gebruik `pathlib.Path` om het uitvoerpad op te bouwen; dit maakt automatisch ontbrekende mappen aan. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Stap 5: Verander de beeldverhouding voor een tweede visuele stijl en sla een andere afbeelding op + +Het wijzigen van de beeldverhouding naar `30` produceert een hogere barcode die mogelijk vereist is door specifieke scanner‑hardware. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Waarom deze stap belangrijk is*: Verschillende retailers en scanapparaten hebben uiteenlopende grootte‑beperkingen. Door beide beeldverhoudingen in één script aan te bieden, kun je de exacte stijl genereren die je nodig hebt zonder code te dupliceren. + +## Volledig script – maak omni-directionele databar en barcode‑afbeelding python + +Hieronder staat het volledige, uitvoerbare voorbeeld dat alle voorgaande stappen combineert. Sla het op als `generate_databar.py` en voer het uit met `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Verwachte output + +Het uitvoeren van het script maakt de volgende bestanden aan: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Beide afbeeldingen tonen een geldige Omni‑directionele DataBar die kan worden gescand door standaard retail‑apparatuur. + +![example of create omni directional databar barcode image in Python](example_databar.png "create omni directional databar barcode image python") + +*De bovenstaande afbeelding is een placeholder die de twee opgeslagen PNG‑bestanden illustreert.* + +## Veelvoorkomende problemen oplossen + +| Probleem | Reden | Oplossing | +|----------|-------|-----------| +| `ImportError: No module named aspose` | Aspose.BarCode niet geïnstalleerd of geïnstalleerd in een andere omgeving. | Activeer de juiste virtuele omgeving en voer `pip install aspose-barcode` uit. | +| `PermissionError` bij opslaan | Het script heeft geen schrijfrechten voor de doelmap. | Kies een map waar je toegang toe hebt of voer het script uit met de juiste privileges. | +| Barcode scant niet | X‑dimensie te laag of beeldverhouding onverenigbaar met de scanner. | Verhoog `x_dimension.pixels` naar 3 of 4, en test verschillende `aspect_ratio`‑waarden (bijv. 20, 25). | +| Ontbrekende .NET‑runtime | Aspose.BarCode is afhankelijk van de .NET‑runtime op Windows/Linux. | Installeer de nieuwste .NET‑runtime vanaf de Microsoft‑site; de pakketdocumentatie biedt platform‑specifieke aanwijzingen. | + +## Voorbeeld uitbreiden + +Je kunt het script aanpassen om andere DataBar‑varianten te genereren (bijv. `DATABAR_STACKED`, `DATABAR_EXPANDED`). Vervang de `EncodeTypes`‑constante dienovereenkomstig: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Als je de barcode in een PDF wilt insluiten, kan Aspose.PDF for Python het PNG‑bestand direct importeren of kun je de `save`‑methode gebruiken met `BarCodeImageFormat.Pdf`. + +## Conclusie + +Deze tutorial liet zien hoe je **omni-directionele databar** kunt **maken** en hoe je **barcode‑afbeelding in Python** kunt **maken** met Aspose.BarCode. Je hebt nu een compleet, reproduceerbaar script dat twee PNG‑bestanden met verschillende beeldverhoudingen genereert, veelvoorkomende valkuilen afhandelt en kan worden uitgebreid naar andere barcode‑formaten. + +Vervolgens kun je QR‑codes genereren, de barcode toevoegen aan PDF‑facturen, of batchverwerking automatiseren voor grote productcatalogi. Elk van deze onderwerpen bouwt voort op hetzelfde `BarcodeGenerator`‑patroon dat hier wordt gedemonstreerd. Veel programmeerplezier! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Genereer barcode‑afbeelding – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Maak DotCode barcode‑afbeelding – rijen & kolommen (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Hoe maak je een barcode‑afbeelding en render je deze in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/dutch/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/dutch/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..ae0683dbd --- /dev/null +++ b/barcode/dutch/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: Hoe je snel een barcode genereert met Python. Leer een barcode te maken + van gegevens en een barcode‑afbeelding te exporteren met één enkele bibliotheek. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: nl +lastmod: 2026-08-12 +og_description: Hoe barcode te genereren in Python met Aspose.BarCode. Volg deze gids + om een barcode te maken van gegevens en de barcode‑afbeelding als PNG te exporteren. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Hoe barcode te genereren in Python – snelle, betrouwbare gids +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Hoe barcode te genereren in Python – complete stapsgewijze gids +url: /nl/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe een barcode te genereren in Python – volledige stapsgewijze gids + +Als je **hoe een barcode te genereren** in een Python‑applicatie nodig hebt, laat deze tutorial je de exacte code zien die je nodig hebt. Je leert om **barcode van data te maken**, het uiterlijk aan te passen, en **barcode‑afbeelding te exporteren** als een PNG‑bestand — alles in minder dan tien regels code. + +Het genereren van een barcode kan aanvoelen als een aparte zorg ten opzichte van de rest van je bedrijfslogica, maar met één enkele bibliotheek kun je het proces geïntegreerd houden met je bestaande codebase. In de volgende secties zie je een volledig, uitvoerbaar voorbeeld, begrijp je waarom elke regel belangrijk is, en ontdek je veelvoorkomende variaties zoals het wijzigen van de modulebreedte of het tekenen van een barcode alleen met omtrek. + +## Hoe een barcode te genereren met de Aspose.BarCode‑bibliotheek + +De Aspose.BarCode‑bibliotheek voor Python (via .NET) biedt een eenvoudige API voor veel symbologieën, inclusief de Planet‑barcode die in deze gids wordt gebruikt. Zorg ervoor dat je het pakket geïnstalleerd hebt voordat je begint: + +```bash +pip install aspose-barcode +``` + +> **Pro tip:** Gebruik een virtuele omgeving om versieconflicten met andere projecten te vermijden. + +### 1. Importeer de vereiste klassen + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Deze imports geven je toegang tot de generator‑klasse, de enumeratie van barcode‑typen, en de image‑format‑enum die wordt gebruikt bij het opslaan van het resultaat. + +### 2. Maak een barcode van data + +De eerste stap is om **een barcode van data te maken**. De `BarcodeGenerator`‑constructor neemt de symbologie en de ruwe string die je wilt coderen. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +De waarde `EncodeTypes.Planet` selecteert de Planet‑barcode, terwijl `"123456"` de payload is die in de uiteindelijke afbeelding zal verschijnen. + +### 3. Pas de X‑dimensie aan (modulebreedte) + +De X‑dimensie bepaalt de breedte van elke barcode‑module (de dunne balk). Instellen op 4 pixels geeft een duidelijke, leesbare afbeelding zonder het bestand te groot te maken. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Waarom dit belangrijk is:** Een grotere X‑dimensie verbetert de scanbetrouwbaarheid op printers met lage resolutie, terwijl een kleinere waarde de bestandsgrootte voor webgebruik verkleint. + +### 4. Exporteer barcode‑afbeelding (gevulde stijl) + +Nu kun je **barcode‑afbeelding exporteren** met de `save`‑methode. Het voorbeeld slaat een PNG‑bestand op, maar je kunt JPEG, BMP of TIFF kiezen door de `BarCodeImageFormat`‑enum te wijzigen. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +Het bestand `PlanetFilled.png` bevat een volledig gevulde Planet‑barcode, klaar voor afdrukken of insluiten in een PDF. + +### 5. Maak een tweede generator voor een barcode alleen met omtrek + +Als je een omtrekversie (lege balken) nodig hebt, moet je een nieuwe generator maken omdat de `filled_bars`‑vlag niet kan worden gewijzigd nadat de afbeelding is opgeslagen. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Pas dezelfde X‑dimensie‑instelling toe + +Wanneer je een tweede generator maakt, moet je alle visuele instellingen die je consistent wilt houden opnieuw toepassen. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Schakel gevulde balken uit voor een omtrek‑barcode + +Het instellen van `filled_bars` op `False` vertelt de renderer alleen de omtrekken van elke module te tekenen, waardoor een lichtere afbeelding ontstaat die nuttig kan zijn voor ontwerpdoeleinden. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Exporteer de omtrek‑barcode‑afbeelding + +Tot slot, **exporteer barcode‑afbeelding** opnieuw, dit keer de omtrekversie opslaan. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Je hebt nu twee PNG‑bestanden: één met solide balken (`PlanetFilled.png`) en één met alleen omtrekken (`PlanetEmpty.png`). + +## Exporteer barcode‑afbeelding in andere formaten (optioneel) + +De `save`‑methode ondersteunt verschillende formaten. Om te exporteren als JPEG met 90 % kwaliteit: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Als je een transparante achtergrond voor webgebruik nodig hebt, kies dan PNG met een alfakanaal: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Veelvoorkomende variaties en randgevallen + +| Scenario | Vereiste wijziging | Codefragment | +|----------|-------------------|--------------| +| **Andere symbologie** (bijv. QR) | Gebruik een andere `EncodeTypes`‑waarde | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Aangepaste voorgrondkleur** | Stel `fore_color` in | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Hogere resolutie** | Verhoog DPI via `image_width` en `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Grote gegevensreeksen** | Zorg ervoor dat de gegevenslengte binnen de specificatie van de symbologie past | Validate length before creating the generator | + +> **Let op:** Het leveren van gegevens die de maximale lengte voor de gekozen symbologie overschrijden, veroorzaakt een runtime‑exception. Valideer altijd de stringlengte of vang `ArgumentException`. + +## Volledig, uitvoerbaar voorbeeld + +Hieronder staat het volledige script dat je kunt kopiëren‑plakken in een bestand genaamd `generate_planet_barcode.py`. Pas `YOUR_DIRECTORY` aan naar een map die bestaat op je computer. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Het uitvoeren van dit script produceert twee PNG‑bestanden in de opgegeven map. Controleer de output door de afbeeldingen te openen in een willekeurige afbeeldingsviewer; beide moeten een Planet‑barcode tonen die de string `123456` codeert. + +## Conclusie + +Je weet nu **hoe je een barcode kunt genereren** in Python met Aspose.BarCode, hoe je **een barcode van data kunt maken**, en hoe je **barcode‑afbeelding kunt exporteren** in zowel gevulde als omtrekstijlen. Hetzelfde patroon geldt voor andere symbologieën, afbeeldingsformaten en visuele aanpassingen, waardoor je een flexibele basis krijgt voor elke barcode‑gerelateerde functionaliteit in je applicatie. + +### Volgende stappen + +* Verken andere symbologieën zoals QR, Code‑128 of DataMatrix door `EncodeTypes.Planet` te vervangen door de gewenste waarde. +* Integreer de gegenereerde PNG‑bestanden in PDF‑rapporten met bibliotheken zoals `ReportLab` of `PyPDF2`. +* Experimenteer met dynamische X‑dimension‑waarden om de barcode‑grootte aan te passen op basis van schermresolutie of printer‑DPI. + +Veel plezier met coderen, en voel je vrij om het voorbeeld aan te passen aan je eigen projectvereisten! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stapsgewijze uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe een barcode‑afbeelding te genereren in Java met Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Hoe een barcode te genereren in Java – Complete configuratie‑gids](/barcode/english/java/barcode-configuration/) +- [Hoe code128‑barcode‑afbeeldingen te maken in Java met Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/english/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..68676e026 --- /dev/null +++ b/barcode/english/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,296 @@ +--- +category: general +date: 2026-08-12 +description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: en +lastmod: 2026-08-12 +og_description: barcode generator example demonstrates how to generate barcode with + exact pixel dimensions. Follow this guide to control module width and bar height + for Planet and RM4SCC codes. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: barcode generator example – customize pixel size in C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: barcode generator example – step‑by‑step guide for custom pixel sizes +url: /python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# barcode generator example – step‑by‑step guide for custom pixel sizes + +If you need a **barcode generator example** that lets you control every pixel, this guide shows exactly how to do it. You’ll learn to set the module width, define a fixed bar height, and generate both Planet and RM4SCC barcodes with predictable dimensions. + +Most developers struggle with “how to generate barcode” images that look the same on every screen or printer. The code snippets below solve that problem by exposing the pixel‑level parameters of the Aspose.BarCode for .NET library, so you can produce consistent output without guesswork. + +## What you’ll learn + +* How to install the required NuGet package. +* How to generate a Planet barcode with automatically calculated height. +* How to generate a Planet barcode with an explicit 100‑pixel height. +* How to generate an RM4SCC barcode using the same explicit height. +* Why **barcode pixel size** matters for scanning reliability. +* Tips for troubleshooting common issues when you generate Planet barcode images. + +You only need .NET 6 or later, a basic C# development environment, and an internet connection to pull the NuGet package. + +--- + +## barcode generator example – set up the development environment + +Before writing any code, make sure the Aspose.BarCode library is available to your project. + +### Install the Aspose.BarCode package + +Open a terminal in your project folder and run: + +```bash +dotnet add package Aspose.BarCode +``` + +The command adds the latest stable version of **Aspose.BarCode** to your `csproj`. After the restore finishes, you can start using the `BarcodeGenerator` class. + +> **Pro tip:** Target .NET 6 or .NET 7 to benefit from the latest performance improvements and default UTF‑8 handling. + +### Add the necessary `using` directives + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +These namespaces expose the `BarcodeGenerator` class and the `BarCodeImageFormat` enum used later in the tutorial. + +--- + +## How to generate barcode with custom pixel size + +The following three steps illustrate the complete **barcode generator example**. Each step builds on the previous one, so you can copy‑paste the whole block into a console app and run it unchanged. + +### Step 1 – generate a Planet barcode with automatically calculated height + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Why this works:** +*The `XDimension` property defines the width of a single barcode module (the smallest black or white element). When you omit `BarHeight`, the library calculates a height that maintains the standard aspect ratio for Planet codes.* + +**Expected output:** A PNG file named `PlanetAuto.png` containing a clean Planet barcode. Its height adapts to the 4‑pixel module width, typically around 60 pixels for a six‑character payload. + +### Step 2 – generate a Planet barcode with an explicit 100‑pixel height + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Why you might need this:** +Sometimes the scanning equipment expects a minimum bar height for reliable detection. By setting `BarHeight.Pixels`, you guarantee that every generated image meets that requirement, regardless of the encoded data length. + +**Expected output:** `PlanetHeight100.png` shows the same data as before, but the bars are exactly 100 pixels tall, giving you full control over the visual size. + +### Step 3 – generate an RM4SCC barcode with the same explicit height + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Why this matters:** +`EncodeTypes.RM4SCC` is a stacked linear barcode used in logistics. Aligning its bar height with the Planet barcode simplifies batch processing when both symbologies appear on the same label. + +**Expected output:** `RM4SCCHeight100.png` displays a perfectly sized RM4SCC barcode, matching the 100‑pixel height you set for the Planet code. + +> **Result verification:** Open each PNG in an image viewer and confirm that the black bars are exactly 4 pixels wide and, where you specified, 100 pixels tall. You can also feed the files to a barcode scanner app to ensure they decode to “123456”. + +--- + +## Understanding barcode pixel size and bar height + +### What is **barcode pixel size**? + +*Pixel size* refers to the physical number of screen or printer pixels that represent a single module (`XDimension`). A larger pixel size yields a bigger barcode, which can be easier for low‑resolution scanners but consumes more label real‑estate. + +### How does `BarHeight` affect readability? + +The `BarHeight` property controls the vertical length of the bars. Standards for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting a height below that can cause read errors, especially on mobile cameras. + +### When should you let the library calculate height automatically? + +If you’re generating barcodes for on‑screen display only, the automatic calculation keeps the aspect ratio consistent and reduces the amount of manual tweaking needed. For printed labels that must meet strict ISO specifications, you should **explicitly set the bar height**. + +--- + +## Common pitfalls and best practices when you generate Planet barcode + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| Bars appear too thin or thick | `XDimension` left at default (1 pixel) on high‑resolution displays | Set `XDimension.Pixels` to at least 3‑4 for visual clarity | +| Scanner cannot read the code | `BarHeight` is too small for the scanner’s focal length | Use `BarHeight.Pixels` ≥ 100 for most mobile scanners | +| Image is blurry after scaling | Saving as JPEG introduces compression artifacts | Save as PNG (`BarCodeImageFormat.Png`) for lossless output | +| Unexpected barcode type | Wrong `EncodeTypes` enum value | Double‑check you’re using `EncodeTypes.Planet` for Planet symbology | + +### Pro tip on performance + +When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` instance and only change the `CodeText` and size parameters between saves. This avoids repeated allocation of internal rendering objects and can cut execution time by up to 30 %. + +--- + +## Full working example – put everything together + +Create a new console project (`dotnet new console -n BarcodeDemo`) and replace the content of `Program.cs` with the following: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Run the program with `dotnet run`. After execution you will find three PNG files in the project folder, each illustrating a different **barcode generator example** scenario. + +--- + +## Next steps and related topics + +* **How to generate barcode in other formats** – explore `EncodeTypes.Code128`, `EncodeTypes.QR`, and `EncodeTypes.DataMatrix` for 2‑D needs. +* **Embedding barcodes in PDFs** – combine Aspose.BarCode with Aspose.PDF to place barcodes directly onto invoice templates. +* **Dynamic barcode size based on user input** – calculate + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/og-image.png b/barcode/english/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/og-image.png new file mode 100644 index 000000000..5238dda8e Binary files /dev/null and b/barcode/english/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/og-image.png differ diff --git a/barcode/english/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/english/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..07e7acc77 --- /dev/null +++ b/barcode/english/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-08-12 +description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: en +lastmod: 2026-08-12 +og_description: Configure Databar barcode layout in Python to control columns, rows, + and image output. Follow this guide for a ready‑to‑run solution. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Configure Databar barcode layout in Python – complete tutorial +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Configure Databar barcode layout in Python – step‑by‑step guide +url: /python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Configure Databar barcode layout in Python – step‑by‑step guide + +If you need to **configure Databar barcode layout in Python**, this guide walks you through the entire process. You’ll see how to set the number of columns or rows for a Databar Expanded Stacked barcode and how to save the resulting image with a single call to the barcode generator library. + +Controlling the layout is essential when you embed barcodes on narrow packaging, receipts, or mobile screens. In the sections below we’ll cover the required imports, the two layout options (columns and rows), and the best practices for saving a clean PNG image. + +## What you’ll need + +Before you start, make sure you have: + +* Python 3.8 or newer +* `aspose.barcode` (or any compatible barcode‑generation package) installed + ```bash + pip install aspose-barcode + ``` +* Write permission to a folder where the PNG files will be stored + +No additional external tools are required—the library handles rendering, scaling, and image encoding internally. + +## How to configure Databar barcode layout in Python + +The core of the solution is the `BarcodeGenerator` class. It accepts an `EncodeTypes` enum that identifies the barcode symbology—in this case `EncodeTypes.DatabarExpandedStacked`. After creating the generator you can adjust the layout by setting the `columns` or `rows` properties on the `data_bar` parameter object. + +### Step 1: Import the required classes + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +These imports give you access to the generator, the enumeration for Databar types, and the PNG image format constant. + +### Step 2: Create a barcode generator for Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Why this step?* +`EncodeTypes.DatabarExpandedStacked` tells the library to produce the **Databar Expanded Stacked** symbology, which supports longer numeric strings while keeping a compact footprint. The second argument is the data to encode; it can be any string that meets the Databar specification. + +### Step 3: Set the number of columns (horizontal layout) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** is the key phrase for this operation. When you increase the column count, the barcode spreads horizontally, which can be useful for wide labels. The library automatically recalculates the module width to keep the overall size consistent. + +#### Pro tip +The maximum column count for Databar Expanded Stacked is 8. Setting a value higher than the limit will clamp it to the maximum, but it’s better to validate your input beforehand. + +### Step 4: Save the barcode image with the column layout + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** is the action that writes the rendered barcode to disk. PNG is lossless, which preserves the sharp edges required for reliable scanning. + +### Step 5: Create a second generator for the same barcode type (row layout) + +If you prefer a vertical stack, you work with rows instead of columns. The code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance to avoid mixing column and row settings. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Step 6: Set the number of rows (vertical layout) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** arranges the barcode modules vertically. A three‑row layout reduces the height of each individual stack, making the barcode suitable for narrow receipts or mobile screens. + +#### Edge case +If you set `rows` to 1, the library generates a single‑row Databar (equivalent to a standard Databar). Values below 1 are ignored and reset to the default (1 row). + +### Step 7: Save the barcode image with the row layout + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Again, we **save barcode image** using PNG to keep the output crisp. + +## Full runnable example + +Putting all the pieces together gives you a self‑contained script you can drop into any Python project. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Expected output** + +Running the script creates two PNG files: + +* `output/ExpandedCols4.png` – a barcode stretched across four columns +* `output/ExpandedRows3.png` – a barcode compressed into three rows + +Both images can be opened in any image viewer or imported directly into PDF invoices, label templates, or web pages. + +## Common questions and troubleshooting + +| Question | Answer | +|----------|--------| +| *What if the barcode looks blurry?* | Increase the image resolution by setting `barcode_generator.parameters.image_width` and `image_height` before calling `save`. | +| *Can I use other image formats?* | Yes. Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. | +| *Is there a limit on the data length?* | Databar Expanded Stacked supports up to 74 numeric characters. Exceeding the limit raises a `ArgumentException`. | +| *How do I change the foreground color?* | Use `barcode_generator.parameters.barcode.color = Color.Blue` (import `System.Drawing.Color`). | +| *Can I combine columns and rows?* | No. The API treats columns and rows as mutually exclusive layout modes. Choose one per barcode instance. | + +## Next steps + +Now that you can **configure Databar barcode layout**, consider exploring these related topics: + +* **Add text captions** – use `barcode_generator.parameters.barcode.code_text` to display the encoded value beneath the image. +* **Embed the barcode in a PDF** – combine the generated PNG with `aspose.pdf` to create printable documents. +* **Dynamic sizing** – calculate optimal column or row counts based on label dimensions at runtime. +* **Batch processing** – loop over a CSV of product codes to generate a library of barcode images automatically. + +Experiment with different column and row values to see how they affect scan reliability on your target devices. The more you test, the better you’ll understand the trade‑offs between barcode size, readability, and space constraints. + +--- + +*Happy coding! If you found this tutorial useful, share it with teammates or leave a comment about the layout challenges you faced.* + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Create barcode image c# – Configure Codablock F Rows & Columns](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [One-Dimensional Databar Barcode Height Adjustment](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/og-image.png b/barcode/english/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/og-image.png new file mode 100644 index 000000000..1902306ae Binary files /dev/null and b/barcode/english/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/og-image.png differ diff --git a/barcode/english/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/english/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..d32c2a1c8 --- /dev/null +++ b/barcode/english/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-08-12 +description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: en +lastmod: 2026-08-12 +og_description: Create barcode image in C# with BarCodeGenerator. This tutorial shows + step‑by‑step how to generate DataBar codes, adjust barcode image size, and produce + multiple barcodes. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Create barcode image in C# – complete BarCodeGenerator guide +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Create barcode image in C# with BarCodeGenerator +url: /python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create barcode image in C# with BarCodeGenerator + +If you need to **create barcode image** in a .NET application, this guide shows you exactly how to do it with the `BarCodeGenerator` class. Whether you are building a retail POS system or an inventory‑tracking tool, you’ll learn to generate DataBar symbols, control the barcode image size, and produce several barcodes in one run. + +You’ll also discover how the **barcode generator c#** API lets you tweak dimensions, switch output formats, and handle edge cases such as invalid data strings. By the end of the tutorial you can confidently **create multiple barcodes** without writing repetitive code. + +## Prerequisites + +Before you start, make sure you have: + +- .NET 6.0 or later installed +- A development environment (Visual Studio, Rider, or VS Code) +- The Aspose.BarCode for .NET NuGet package (or any compatible library that provides `BarCodeGenerator`) + +You can add the package with: + +```bash +dotnet add package Aspose.BarCode +``` + +## What this tutorial covers + +1. Setting up a **barcode generator c#** instance for DataBar Omni‑directional encoding. +2. Adjusting **barcode image size** by changing X‑dimension and bar height. +3. Using a loop to **create multiple barcodes** with different heights. +4. Saving the images as PNG files and verifying the output. + +All code snippets are complete and ready to copy‑paste into a new console project. + +![Create barcode image example](barcode-example.png){alt="Create barcode image example"} + +## Step 1: Initialize the generator – create barcode image basics + +The first step is to instantiate `BarCodeGenerator` with the desired symbology. For a DataBar Omni‑directional symbol you use `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Why this matters:** Instantiating the generator defines the encoding rules and the data payload. If you omit the correct `EncodeTypes` value, the library will produce an unsupported barcode or throw an exception. + +## Step 2: Configure X‑dimension and bar height – control barcode image size + +The visual size of a barcode is driven by two parameters: + +| Parameter | What it controls | Typical range | +|-----------|------------------|---------------| +| `x_dimension.pixels` | Width of the smallest module (the “dot”) | 1 – 4 px | +| `bar_height.pixels` | Height of the vertical bars | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Pro tip:** A smaller X‑dimension yields a higher‑resolution image but may be harder to scan on low‑quality printers. Adjust the value based on your target scanning equipment. + +## Step 3: Save the first barcode – create barcode image for 30 px height + +Now you can generate the image and write it to disk. The `Save` method accepts a file path and an image format enum. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Expected result:** A PNG file named `Databar30.png` appears in `C:\Barcodes`. Opening the file shows a DataBar Omni‑directional symbol with a clear, high‑contrast pattern. + +## Step 4: Change the height and generate additional images – create multiple barcodes + +To **create multiple barcodes** with different dimensions you only need to modify the `BarHeight` property and call `Save` again. This avoids re‑instantiating the generator, which saves memory and CPU time. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Why this works:** The `BarCodeGenerator` object holds all configuration state. Changing a single property updates the rendering engine for the next `Save` call, allowing you to **create multiple barcodes** efficiently. + +## Step 5: Advanced – how to generate DataBar with custom data + +The example above uses a static GS1 payload. In real‑world scenarios you often need to embed variable product identifiers. The library accepts any string that matches the DataBar specification. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Key point:** Setting `generator.CodeText` updates the encoded data without recreating the object. This is the recommended **how to generate databar** pattern when handling large data sets. + +## Step 6: Verify and troubleshoot – ensuring correct barcode image size + +After generating the images, you may want to programmatically confirm that the dimensions match your expectations. The `Image` class from `System.Drawing` can read the file and report its size. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +If the height does not reflect the value you set, check: + +- **X‑dimension**: A very small value may cause the renderer to round the height. +- **Image format**: Some formats (e.g., JPEG) apply compression that can alter pixel dimensions on saving. PNG preserves exact dimensions. + +## Step 7: Best practices for barcode image size and performance + +| Recommendation | Reason | +|----------------|--------| +| Keep `x_dimension.pixels` between 2 – 3 px for most scanners. | Balances readability and file size. | +| Use PNG for lossless output when the image will be printed. | Guarantees exact dimensions and sharp edges. | +| Reuse a single `BarCodeGenerator` instance when generating many barcodes. | Reduces object allocation overhead. | +| Validate the input string against the GS1 standard before assigning to `CodeText`. | Prevents runtime exceptions and invalid scans. | +| Store generated images in a dedicated folder with a clear naming convention (e.g., `Databar_{GTIN}.png`). | Simplifies downstream processing and audit trails. | + +## Full working example + +Below is the complete program that incorporates all steps from initialization through verification. Copy the code into a new console project and run it. + +```csharp +using System; +using System.Drawing; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ------------------------------------------------- + // Step 1: Create the generator (create barcode image basics) + // ------------------------------------------------- + var generator = new BarCodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + // ------------------------------------------------- + // Step 2: Set X‑dimension and initial bar height + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/python-java/general/create-barcode-image-in-c-with-barcodegenerator/og-image.png b/barcode/english/python-java/general/create-barcode-image-in-c-with-barcodegenerator/og-image.png new file mode 100644 index 000000000..a52bd1951 Binary files /dev/null and b/barcode/english/python-java/general/create-barcode-image-in-c-with-barcodegenerator/og-image.png differ diff --git a/barcode/english/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/english/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..58e1586a4 --- /dev/null +++ b/barcode/english/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-08-12 +description: Create omni directional databar with Python and learn how to create barcode + image python using Aspose.BarCode. Follow the step‑by‑step guide for a complete + solution. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: en +lastmod: 2026-08-12 +og_description: Create omni directional databar with Python and generate a barcode + image python in minutes. This tutorial shows a complete, runnable example. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Create omni directional databar – full Python guide +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Create omni directional databar and barcode image in Python +url: /python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create omni directional databar and barcode image in Python + +If you need to **create omni directional databar** in a Python project, this guide shows you how to do it and also how to **create barcode image python** using the Aspose.BarCode library. You will get a ready‑to‑run script that produces two PNG files with different aspect ratios. + +Generating a DataBar that follows the Omni‑directional specification is a common requirement for retail and logistics applications. The tutorial covers installation, configuration of the X‑dimension, adjustment of the aspect ratio, and saving the final images. No external services are required; everything runs locally. + +## What you will need + +Before you start, make sure you have: + +* Python 3.8 or newer installed on your machine. +* Access to a terminal or command prompt. +* Write permission to a folder where the barcode images will be saved. + +The only third‑party dependency is **Aspose.BarCode for Python via .NET**, which supports the Omni‑directional DataBar type out of the box. + +## Step 1: Install Aspose.BarCode for Python + +Aspose.BarCode provides the `BarcodeGenerator` class used in the example code. Install the package with `pip`: + +```bash +pip install aspose-barcode +``` + +The package includes the necessary .NET runtime bindings, so you do not need to install the .NET SDK separately. + +## Step 2: Import the library and create the generator + +The first line of the script creates a generator for a stacked Omni‑directional DataBar. The GTIN‑14 value `(01)12345678901231` is used as sample data. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Why this step matters*: The `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` constant tells the library to encode the value as an Omni‑directional DataBar, which is the format required by many point‑of‑sale scanners. + +## Step 3: Set the X‑dimension (module width) + +The X‑dimension defines the width of the smallest bar module. A value of `2` pixels produces a clear, readable barcode without excessive file size. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Why this step matters*: Adjusting the X‑dimension allows you to balance readability and image dimensions. An X‑dimension that is too small may render poorly on low‑resolution printers. + +## Step 4: Configure the aspect ratio and save the first image + +The aspect ratio influences the overall height of the DataBar relative to its width. An aspect ratio of `15` creates a compact visual style. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Pro tip**: Use `pathlib.Path` to build the output path, which automatically creates missing directories. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Step 5: Change the aspect ratio for a second visual style and save another image + +Switching the aspect ratio to `30` produces a taller barcode that may be required by specific scanner hardware. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Why this step matters*: Different retailers and scanning devices have distinct size constraints. Providing both aspect ratios in a single script lets you generate the exact style you need without duplicating code. + +## Full script – create omni directional databar and barcode image python + +Below is the complete, runnable example that incorporates all previous steps. Save it as `generate_databar.py` and run it with `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Expected output + +Running the script creates the following files: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Both images display a valid Omni‑directional DataBar that can be scanned by standard retail equipment. + +![example of create omni directional databar barcode image in Python](example_databar.png "create omni directional databar barcode image python") + +*The image above is a placeholder that illustrates the two saved PNG files.* + +## Handling common issues + +| Issue | Reason | Fix | +|-------|--------|-----| +| `ImportError: No module named aspose` | Aspose.BarCode not installed or installed in a different environment. | Activate the correct virtual environment and run `pip install aspose-barcode`. | +| `PermissionError` when saving | The script lacks write permission for the target folder. | Choose a directory you own or run the script with appropriate privileges. | +| Barcode does not scan | X‑dimension too low or aspect ratio incompatible with the scanner. | Increase `x_dimension.pixels` to 3 or 4, and test different `aspect_ratio` values (e.g., 20, 25). | +| Missing .NET runtime | Aspose.BarCode depends on the .NET runtime on Windows/Linux. | Install the latest .NET runtime from Microsoft’s site; the package documentation provides platform‑specific guidance. | + +## Extending the example + +You can adapt the script to generate other DataBar variants (e.g., `DATABAR_STACKED`, `DATABAR_EXPANDED`). Replace the `EncodeTypes` constant accordingly: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +If you need to embed the barcode in a PDF, Aspose.PDF for Python can import the PNG file directly or you can use the `save` method with `BarCodeImageFormat.Pdf`. + +## Conclusion + +This tutorial showed how to **create omni directional databar** and how to **create barcode image python** using Aspose.BarCode. You now have a complete, reproducible script that generates two PNG files with different aspect ratios, handles common pitfalls, and can be extended to other barcode formats. + +Next, explore generating QR codes, adding the barcode to PDF invoices, or automating batch processing for large product catalogs. Each of those topics builds on the same `BarcodeGenerator` pattern demonstrated here. Happy coding! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to create barcode image and render it in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/og-image.png b/barcode/english/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/og-image.png new file mode 100644 index 000000000..354ad13f3 Binary files /dev/null and b/barcode/english/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/og-image.png differ diff --git a/barcode/english/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/english/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..5cf906148 --- /dev/null +++ b/barcode/english/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: en +lastmod: 2026-08-12 +og_description: How to generate barcode in Python with Aspose.BarCode. Follow this + guide to create barcode from data and export barcode image as PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: How to generate barcode in Python – fast, reliable guide +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: How to generate barcode in Python – complete step‑by‑step guide +url: /python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to generate barcode in Python – complete step‑by‑step guide + +If you need to **how to generate barcode** in a Python application, this tutorial shows you the exact code you need. You’ll learn to **create barcode from data**, adjust its appearance, and **export barcode image** as a PNG file—all in under ten lines of code. + +Generating a barcode can feel like a separate concern from the rest of your business logic, but with a single library you can keep the process inline with your existing code base. In the sections that follow you’ll see a full, runnable example, understand why each line matters, and discover common variations such as changing the module width or drawing an outline‑only barcode. + +## How to generate barcode with the Aspose.BarCode library + +The Aspose.BarCode library for Python (via .NET) provides a straightforward API for many symbologies, including the Planet barcode used in this guide. Before you start, make sure you have the package installed: + +```bash +pip install aspose-barcode +``` + +> **Pro tip:** Use a virtual environment to avoid version conflicts with other projects. + +### 1. Import the required classes + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +These imports give you access to the generator class, the enumeration of barcode types, and the image format enum used when saving the result. + +### 2. Create barcode from data + +The first step is to **create barcode from data**. The `BarcodeGenerator` constructor takes the symbology and the raw string you want to encode. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +The `EncodeTypes.Planet` value selects the Planet barcode, while `"123456"` is the payload that will appear in the final image. + +### 3. Adjust the X‑dimension (module width) + +The X‑dimension controls the width of each barcode module (the thin bar). Setting it to 4 pixels gives a clear, readable image without making the file too large. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Why this matters:** A larger X‑dimension improves scan reliability on low‑resolution printers, while a smaller value reduces file size for web use. + +### 4. Export barcode image (filled style) + +Now you can **export barcode image** using the `save` method. The example saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` enum. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +The file `PlanetFilled.png` contains a fully filled Planet barcode, ready for printing or embedding in a PDF. + +### 5. Create a second generator for an outline‑only barcode + +If you need an outline version (empty bars), you must create a new generator because the `filled_bars` flag cannot be toggled after the image is saved. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Apply the same X‑dimension setting + +When you create a second generator, you must repeat any visual settings you want to keep consistent. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Disable filled bars for an outline barcode + +Setting `filled_bars` to `False` tells the renderer to draw only the outlines of each module, producing a lighter image that can be useful for design purposes. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Export the outline barcode image + +Finally, **export barcode image** again, this time storing the outline version. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +You now have two PNG files: one with solid bars (`PlanetFilled.png`) and one with only outlines (`PlanetEmpty.png`). + +## Export barcode image in other formats (optional) + +The `save` method supports several formats. To export as JPEG with 90 % quality: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +If you need a transparent background for web use, choose PNG with an alpha channel: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Common variations and edge cases + +| Scenario | Change needed | Code snippet | +|----------|---------------|--------------| +| **Different symbology** (e.g., QR) | Use a different `EncodeTypes` value | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Custom foreground color** | Set `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Higher resolution** | Increase DPI via `image_width` and `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Large data strings** | Ensure data length fits the symbology spec | Validate length before creating the generator | + +> **Watch out for:** Supplying data that exceeds the maximum length for the chosen symbology raises a runtime exception. Always validate the string length or catch `ArgumentException`. + +## Full, runnable example + +Below is the complete script that you can copy‑paste into a file named `generate_planet_barcode.py`. Adjust `YOUR_DIRECTORY` to a folder that exists on your machine. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Running this script produces two PNG files in the specified directory. Verify the output by opening the images in any image viewer; both should display a Planet barcode encoding the string `123456`. + +## Conclusion + +You now know **how to generate barcode** in Python using Aspose.BarCode, how to **create barcode from data**, and how to **export barcode image** in both filled and outline styles. The same pattern applies to other symbologies, image formats, and visual customizations, giving you a flexible foundation for any barcode‑related feature in your application. + +### Next steps + +* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping `EncodeTypes.Planet` with the desired value. +* Integrate the generated PNG files into PDF reports using libraries like `ReportLab` or `PyPDF2`. +* Experiment with dynamic X‑dimension values to adapt barcode size based on screen resolution or printer DPI. + +Happy coding, and feel free to adapt the example to fit your own project requirements! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/english/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/og-image.png b/barcode/english/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/og-image.png new file mode 100644 index 000000000..30cdb14c1 Binary files /dev/null and b/barcode/english/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/og-image.png differ diff --git a/barcode/french/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/french/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..0fcb69202 --- /dev/null +++ b/barcode/french/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,297 @@ +--- +category: general +date: 2026-08-12 +description: Exemple de générateur de code-barres montrant comment créer un code-barres + avec une taille de pixel précise. Apprenez à définir la largeur du module, la hauteur + des barres et à créer des codes-barres Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: fr +lastmod: 2026-08-12 +og_description: L'exemple de générateur de code-barres montre comment créer un code-barres + avec des dimensions de pixel exactes. Suivez ce guide pour contrôler la largeur + du module et la hauteur des barres pour les codes Planet et RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: exemple de générateur de code-barres – personnaliser la taille des pixels + en C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: exemple de générateur de code‑barres – guide étape par étape pour des tailles + de pixel personnalisées +url: /fr/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# exemple de générateur de code-barres – guide étape par étape pour des tailles de pixel personnalisées + +Si vous avez besoin d'un **exemple de générateur de code-barres** qui vous permet de contrôler chaque pixel, ce guide montre exactement comment le faire. Vous apprendrez à définir la largeur du module, à spécifier une hauteur de barre fixe, et à générer des codes-barres Planet et RM4SCC avec des dimensions prévisibles. + +La plupart des développeurs ont du mal à créer des images « comment générer un code-barres » qui ont le même aspect sur chaque écran ou imprimante. Les extraits de code ci‑dessous résolvent ce problème en exposant les paramètres au niveau du pixel de la bibliothèque Aspose.BarCode pour .NET, afin que vous puissiez produire une sortie cohérente sans conjecture. + +## Ce que vous apprendrez + +* Comment installer le package NuGet requis. +* Comment générer un code-barres Planet avec une hauteur calculée automatiquement. +* Comment générer un code-barres Planet avec une hauteur explicite de 100 pixels. +* Comment générer un code-barres RM4SCC en utilisant la même hauteur explicite. +* Pourquoi la **taille de pixel du code-barres** est importante pour la fiabilité du scan. +* Conseils pour dépanner les problèmes courants lors de la génération d'images de code-barres Planet. + +Vous avez seulement besoin de .NET 6 ou supérieur, d'un environnement de développement C# basique, et d'une connexion Internet pour récupérer le package NuGet. + +--- + +## exemple de générateur de code-barres – configurer l'environnement de développement + +Avant d'écrire du code, assurez-vous que la bibliothèque Aspose.BarCode est disponible pour votre projet. + +### Installer le package Aspose.BarCode + +Ouvrez un terminal dans le dossier de votre projet et exécutez : + +```bash +dotnet add package Aspose.BarCode +``` + +La commande ajoute la dernière version stable de **Aspose.BarCode** à votre `csproj`. Après la fin de la restauration, vous pouvez commencer à utiliser la classe `BarcodeGenerator`. + +> **Astuce :** Ciblez .NET 6 ou .NET 7 pour profiter des dernières améliorations de performances et de la gestion UTF‑8 par défaut. + +### Ajouter les directives `using` nécessaires + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Ces espaces de noms exposent la classe `BarcodeGenerator` et l'énumération `BarCodeImageFormat` utilisées plus tard dans le tutoriel. + +--- + +## Comment générer un code-barres avec une taille de pixel personnalisée + +Les trois étapes suivantes illustrent l'**exemple complet de générateur de code-barres**. Chaque étape s'appuie sur la précédente, de sorte que vous pouvez copier‑coller le bloc entier dans une application console et l'exécuter tel quel. + +### Étape 1 – générer un code-barres Planet avec une hauteur calculée automatiquement + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Pourquoi cela fonctionne :** +*La propriété `XDimension` définit la largeur d'un seul module de code-barres (l'élément noir ou blanc le plus petit). Lorsque vous omettez `BarHeight`, la bibliothèque calcule une hauteur qui maintient le rapport d'aspect standard pour les codes Planet.* + +**Sortie attendue :** Un fichier PNG nommé `PlanetAuto.png` contenant un code-barres Planet propre. Sa hauteur s'adapte à la largeur de module de 4 pixels, généralement autour de 60 pixels pour une charge utile de six caractères. + +### Étape 2 – générer un code-barres Planet avec une hauteur explicite de 100 pixels + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Pourquoi vous pourriez en avoir besoin :** +Parfois, l'équipement de numérisation attend une hauteur de barre minimale pour une détection fiable. En définissant `BarHeight.Pixels`, vous garantissez que chaque image générée satisfait cette exigence, quel que soit la longueur des données encodées. + +**Sortie attendue :** `PlanetHeight100.png` montre les mêmes données qu'auparavant, mais les barres font exactement 100 pixels de haut, vous donnant un contrôle total sur la taille visuelle. + +### Étape 3 – générer un code-barres RM4SCC avec la même hauteur explicite + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Pourquoi c'est important :** +`EncodeTypes.RM4SCC` est un code-barres linéaire empilé utilisé en logistique. Aligner sa hauteur de barre avec le code-barres Planet simplifie le traitement par lots lorsque les deux symbologies apparaissent sur la même étiquette. + +**Sortie attendue :** `RM4SCCHeight100.png` affiche un code-barres RM4SCC parfaitement dimensionné, correspondant à la hauteur de 100 pixels que vous avez définie pour le code Planet. + +> **Vérification du résultat :** Ouvrez chaque PNG dans un visualiseur d'images et confirmez que les barres noires font exactement 4 pixels de large et, là où vous l'avez spécifié, 100 pixels de haut. Vous pouvez également envoyer les fichiers à une application de lecture de code-barres pour vous assurer qu'ils décodent « 123456 ». + +--- + +## Comprendre la taille de pixel du code-barres et la hauteur des barres + +### Qu'est-ce que la **taille de pixel du code-barres** ? + +*La taille de pixel* désigne le nombre physique de pixels d'écran ou d'imprimante qui représentent un seul module (`XDimension`). Une taille de pixel plus grande produit un code-barres plus grand, ce qui peut être plus facile pour les scanners à basse résolution mais consomme plus d'espace sur l'étiquette. + +### Comment `BarHeight` affecte-t-il la lisibilité ? + +La propriété `BarHeight` contrôle la longueur verticale des barres. Les normes pour la plupart des codes-barres 1‑D (y compris Planet et RM4SCC) recommandent une hauteur minimale de 10 mm lorsqu'ils sont imprimés à 300 dpi, ce qui correspond à environ 118 pixels. Définir une hauteur inférieure peut entraîner des erreurs de lecture, notamment avec les caméras mobiles. + +### Quand faut‑il laisser la bibliothèque calculer automatiquement la hauteur ? + +Si vous générez des codes-barres uniquement pour un affichage à l'écran, le calcul automatique maintient le rapport d'aspect constant et réduit le nombre d'ajustements manuels nécessaires. Pour les étiquettes imprimées qui doivent respecter des spécifications ISO strictes, vous devez **définir explicitement la hauteur des barres**. + +--- + +## Pièges courants et bonnes pratiques lors de la génération d'un code-barres Planet + +| Problème | Pourquoi cela se produit | Solution | +|----------|--------------------------|----------| +| Les barres apparaissent trop fines ou trop épaisses | `XDimension` laissé à la valeur par défaut (1 pixel) sur les écrans haute résolution | Définissez `XDimension.Pixels` à au moins 3‑4 pour une clarté visuelle | +| Le scanner ne peut pas lire le code | `BarHeight` est trop petite pour la focale du scanner | Utilisez `BarHeight.Pixels` ≥ 100 pour la plupart des scanners mobiles | +| L'image est floue après mise à l'échelle | Enregistrer en JPEG introduit des artefacts de compression | Enregistrez en PNG (`BarCodeImageFormat.Png`) pour une sortie sans perte | +| Type de code-barres inattendu | Valeur d'énumération `EncodeTypes` incorrecte | Vérifiez que vous utilisez `EncodeTypes.Planet` pour la symbologie Planet | + +### Astuce de performance + +Lors de la génération de milliers de codes-barres dans un travail par lots, réutilisez une seule instance de `BarcodeGenerator` et ne modifiez que le `CodeText` et les paramètres de taille entre les sauvegardes. Cela évite l'allocation répétée d'objets de rendu internes et peut réduire le temps d'exécution jusqu'à 30 %. + +--- + +## Exemple complet fonctionnel – assembler le tout + +Créez un nouveau projet console (`dotnet new console -n BarcodeDemo`) et remplacez le contenu de `Program.cs` par ce qui suit : + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Exécutez le programme avec `dotnet run`. Après l'exécution, vous trouverez trois fichiers PNG dans le dossier du projet, chacun illustrant un scénario différent d'**exemple de générateur de code-barres**. + +--- + +## Prochaines étapes et sujets associés + +* **Comment générer un code-barres dans d'autres formats** – explorez `EncodeTypes.Code128`, `EncodeTypes.QR` et `EncodeTypes.DataMatrix` pour les besoins 2‑D. +* **Intégrer des codes-barres dans des PDF** – combinez Aspose.BarCode avec Aspose.PDF pour placer les codes-barres directement sur les modèles de factures. +* **Taille dynamique du code-barres basée sur l'entrée utilisateur** – calculer + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s'appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités d'API supplémentaires et explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Comment générer un code-barres java : créer une image de code-barres exacte](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [Comment générer un code-barres en Java créer et définir la taille pour l'image complète](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [Comment créer un code-barres code128 en Java et définir la hauteur des barres](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/french/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/french/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..5bc9eea10 --- /dev/null +++ b/barcode/french/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-08-12 +description: Configurez rapidement la mise en page du code‑barres Databar en Python. + Apprenez à définir les colonnes, les lignes et à enregistrer les images avec la + bibliothèque de génération de codes‑barres. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: fr +lastmod: 2026-08-12 +og_description: Configurez la mise en page du code‑barres Databar en Python pour contrôler + les colonnes, les lignes et la sortie d’image. Suivez ce guide pour une solution + prête à l’emploi. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Configurer la mise en page du code‑barres Databar en Python – tutoriel complet +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Configurer la mise en page du code‑barres Databar en Python – guide étape par + étape +url: /fr/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Configurer la mise en page du code‑barres Databar en Python – guide étape par étape + +Si vous devez **configurer la mise en page du code‑barres Databar en Python**, ce guide vous accompagne tout au long du processus. Vous verrez comment définir le nombre de colonnes ou de lignes pour un code‑barres Databar Expanded Stacked et comment enregistrer l’image résultante avec un seul appel à la bibliothèque de génération de code‑barres. + +Contrôler la mise en page est essentiel lorsque vous intégrez des codes‑barres sur des emballages étroits, des reçus ou des écrans mobiles. Dans les sections ci‑dessous, nous couvrirons les importations requises, les deux options de mise en page (colonnes et lignes) et les meilleures pratiques pour enregistrer une image PNG nette. + +## Ce dont vous aurez besoin + +* Python 3.8 ou plus récent +* `aspose.barcode` (ou tout package compatible de génération de code‑barres) installé + ```bash + pip install aspose-barcode + ``` +* Permission d'écriture sur un dossier où les fichiers PNG seront stockés + +Aucun outil externe supplémentaire n'est requis — la bibliothèque gère le rendu, le redimensionnement et l'encodage d'image en interne. + +## Comment configurer la mise en page du code‑barres Databar en Python + +Le cœur de la solution est la classe `BarcodeGenerator`. Elle accepte une énumération `EncodeTypes` qui identifie la symbologie du code‑barres — dans ce cas `EncodeTypes.DatabarExpandedStacked`. Après avoir créé le générateur, vous pouvez ajuster la mise en page en définissant les propriétés `columns` ou `rows` sur l'objet paramètre `data_bar`. + +### Étape 1 : Importer les classes requises + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Ces importations vous donnent accès au générateur, à l'énumération des types Databar et à la constante de format d'image PNG. + +### Étape 2 : Créer un générateur de code‑barres pour Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Pourquoi cette étape ?* +`EncodeTypes.DatabarExpandedStacked` indique à la bibliothèque de produire la symbologie **Databar Expanded Stacked**, qui prend en charge des chaînes numériques plus longues tout en conservant une empreinte compacte. Le deuxième argument est la donnée à encoder ; il peut s'agir de n'importe quelle chaîne qui respecte la spécification Databar. + +### Étape 3 : Définir le nombre de colonnes (mise en page horizontale) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** est la phrase clé pour cette opération. Lorsque vous augmentez le nombre de colonnes, le code‑barres s'étend horizontalement, ce qui peut être utile pour des étiquettes larges. La bibliothèque recalcule automatiquement la largeur du module afin de maintenir la taille globale cohérente. + +#### Astuce pro +Le nombre maximal de colonnes pour Databar Expanded Stacked est de 8. Définir une valeur supérieure à cette limite la limitera au maximum, mais il est préférable de valider votre entrée au préalable. + +### Étape 4 : Enregistrer l'image du code‑barres avec la mise en page en colonnes + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** est l'action qui écrit le code‑barres rendu sur le disque. PNG est sans perte, ce qui préserve les bords nets nécessaires à un scan fiable. + +### Étape 5 : Créer un second générateur pour le même type de code‑barres (mise en page en lignes) + +Si vous préférez une pile verticale, vous travaillez avec des lignes au lieu des colonnes. Le code ci‑dessous réutilise la même valeur mais crée une nouvelle instance `BarcodeGenerator` afin d'éviter de mélanger les paramètres de colonnes et de lignes. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Étape 6 : Définir le nombre de lignes (mise en page verticale) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** organise les modules du code‑barres verticalement. Une mise en page à trois lignes réduit la hauteur de chaque pile individuelle, rendant le code‑barres adapté aux reçus étroits ou aux écrans mobiles. + +#### Cas limite +Si vous définissez `rows` à 1, la bibliothèque génère un Databar à une seule ligne (équivalent à un Databar standard). Les valeurs inférieures à 1 sont ignorées et réinitialisées à la valeur par défaut (1 ligne). + +### Étape 7 : Enregistrer l'image du code‑barres avec la mise en page en lignes + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Encore une fois, nous **save barcode image** en utilisant PNG pour garder la sortie nette. + +## Exemple complet exécutable + +Assembler toutes les pièces vous fournit un script autonome que vous pouvez intégrer dans n'importe quel projet Python. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Sortie attendue** + +L'exécution du script crée deux fichiers PNG : + +* `output/ExpandedCols4.png` – un code‑barres étiré sur quatre colonnes +* `output/ExpandedRows3.png` – un code‑barres compressé en trois lignes + +Les deux images peuvent être ouvertes avec n'importe quel visualiseur d'images ou importées directement dans des factures PDF, des modèles d'étiquettes ou des pages web. + +## Questions fréquentes et dépannage + +| Question | Réponse | +|----------|--------| +| *Que faire si le code‑barres apparaît flou ?* | Augmentez la résolution de l'image en définissant `barcode_generator.parameters.image_width` et `image_height` avant d'appeler `save`. | +| *Puis-je utiliser d'autres formats d'image ?* | Oui. Remplacez `BarCodeImageFormat.Png` par `Jpeg`, `Bmp` ou `Gif` selon vos besoins. | +| *Y a-t-il une limite de longueur des données ?* | Databar Expanded Stacked prend en charge jusqu'à 74 caractères numériques. Dépasser cette limite déclenche une `ArgumentException`. | +| *Comment changer la couleur du premier plan ?* | Utilisez `barcode_generator.parameters.barcode.color = Color.Blue` (importez `System.Drawing.Color`). | +| *Puis-je combiner colonnes et lignes ?* | Non. L'API considère les colonnes et les lignes comme des modes de mise en page mutuellement exclusifs. Choisissez‑en un par instance de code‑barres. | + +## Prochaines étapes + +Maintenant que vous pouvez **configurer la mise en page du code‑barres Databar**, envisagez d'explorer ces sujets connexes : + +* **Add text captions** – utilisez `barcode_generator.parameters.barcode.code_text` pour afficher la valeur encodée sous l'image. +* **Embed the barcode in a PDF** – combinez le PNG généré avec `aspose.pdf` pour créer des documents imprimables. +* **Dynamic sizing** – calculez le nombre optimal de colonnes ou de lignes en fonction des dimensions de l'étiquette à l'exécution. +* **Batch processing** – parcourez un CSV de codes produit pour générer automatiquement une bibliothèque d'images de code‑barres. + +Expérimentez différentes valeurs de colonnes et de lignes pour voir comment elles affectent la fiabilité du scan sur vos appareils cibles. Plus vous testez, mieux vous comprendrez les compromis entre la taille du code‑barres, la lisibilité et les contraintes d'espace. + +--- + +*Bon codage ! Si vous avez trouvé ce tutoriel utile, partagez‑le avec vos collègues ou laissez un commentaire sur les défis de mise en page que vous avez rencontrés.* + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s'appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités supplémentaires de l'API et explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Créer une image de code‑barres DotCode – lignes & colonnes (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Créer une image de code‑barres c# – Configurer les lignes & colonnes de Codablock F](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [Ajustement de la hauteur du code‑barres Databar unidimensionnel](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/french/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/french/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..8490ad63e --- /dev/null +++ b/barcode/french/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: Créer une image de code‑barres en C# avec BarCodeGenerator. Apprenez + à générer DataBar, à contrôler la taille de l’image du code‑barres et à créer plusieurs + codes‑barres efficacement. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: fr +lastmod: 2026-08-12 +og_description: Créer une image de code‑barres en C# avec BarCodeGenerator. Ce tutoriel + montre étape par étape comment générer des codes DataBar, ajuster la taille de l’image + du code‑barres et produire plusieurs codes‑barres. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Créer une image de code-barres en C# – guide complet de BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Créer une image de code-barres en C# avec BarCodeGenerator +url: /fr/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer une image de code-barres en C# avec BarCodeGenerator + +Si vous devez **créer une image de code-barres** dans une application .NET, ce guide vous montre exactement comment le faire avec la classe `BarCodeGenerator`. Que vous construisiez un système de point de vente (POS) pour le commerce de détail ou un outil de suivi d'inventaire, vous apprendrez à générer des symboles DataBar, à contrôler la taille de l'image du code-barres et à produire plusieurs codes-barres en une seule exécution. + +Vous découvrirez également comment l'API **barcode generator c#** vous permet d'ajuster les dimensions, de changer les formats de sortie et de gérer les cas limites tels que les chaînes de données invalides. À la fin du tutoriel, vous pourrez **créer plusieurs codes-barres** en toute confiance sans écrire de code répétitif. + +## Prérequis + +- .NET 6.0 ou version ultérieure installé +- Un environnement de développement (Visual Studio, Rider ou VS Code) +- Le package NuGet Aspose.BarCode for .NET (ou toute bibliothèque compatible qui fournit `BarCodeGenerator`) + +Vous pouvez ajouter le package avec: + +```bash +dotnet add package Aspose.BarCode +``` + +## Ce que couvre ce tutoriel + +1. Configurer une instance **barcode generator c#** pour l'encodage DataBar Omni‑directional. +2. Ajuster la **taille de l'image du code-barres** en modifiant la X‑dimension et la hauteur des barres. +3. Utiliser une boucle pour **créer plusieurs codes-barres** avec des hauteurs différentes. +4. Enregistrer les images au format PNG et vérifier le résultat. + +Tous les extraits de code sont complets et prêts à être copiés‑collés dans un nouveau projet console. + +![Exemple de création d'image de code-barres](barcode-example.png){alt="Exemple de création d'image de code-barres"} + +## Étape 1 : Initialiser le générateur – bases de la création d'image de code-barres + +La première étape consiste à instancier `BarCodeGenerator` avec la symbologie souhaitée. Pour un symbole DataBar Omni‑directional, vous utilisez `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Pourquoi c'est important :** L'instanciation du générateur définit les règles d'encodage et la charge de données. Si vous omettez la valeur correcte de `EncodeTypes`, la bibliothèque générera un code-barres non pris en charge ou lèvera une exception. + +## Étape 2 : Configurer la X‑dimension et la hauteur des barres – contrôler la taille de l'image du code-barres + +La taille visuelle d'un code-barres est déterminée par deux paramètres : + +| Paramètre | Ce qu'il contrôle | Plage typique | +|-----------|-------------------|----------------| +| `x_dimension.pixels` | Largeur du plus petit module (le « point ») | 1 – 4 px | +| `bar_height.pixels` | Hauteur des barres verticales | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Astuce :** Une X‑dimension plus petite donne une image à plus haute résolution mais peut être plus difficile à scanner avec des imprimantes de basse qualité. Ajustez la valeur en fonction de votre équipement de numérisation cible. + +## Étape 3 : Enregistrer le premier code-barres – créer une image de code-barres pour une hauteur de 30 px + +Vous pouvez maintenant générer l'image et l'écrire sur le disque. La méthode `Save` accepte un chemin de fichier et une énumération de format d'image. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Résultat attendu :** Un fichier PNG nommé `Databar30.png` apparaît dans `C:\Barcodes`. L'ouverture du fichier montre un symbole DataBar Omni‑directional avec un motif clair et à fort contraste. + +## Étape 4 : Modifier la hauteur et générer des images supplémentaires – créer plusieurs codes-barres + +Pour **créer plusieurs codes-barres** avec des dimensions différentes, il suffit de modifier la propriété `BarHeight` et d'appeler à nouveau `Save`. Cela évite de ré‑instancier le générateur, ce qui économise de la mémoire et du temps CPU. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Pourquoi cela fonctionne :** L'objet `BarCodeGenerator` conserve tout l'état de configuration. Modifier une seule propriété met à jour le moteur de rendu pour l'appel suivant de `Save`, vous permettant de **créer plusieurs codes-barres** efficacement. + +## Étape 5 : Avancé – comment générer un DataBar avec des données personnalisées + +L'exemple ci‑dessus utilise une charge utile GS1 statique. Dans des scénarios réels, vous devez souvent intégrer des identifiants de produit variables. La bibliothèque accepte toute chaîne qui correspond à la spécification DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Point clé :** Définir `generator.CodeText` met à jour les données encodées sans recréer l'objet. C'est le modèle recommandé **how to generate databar** lors du traitement de grands ensembles de données. + +## Étape 6 : Vérifier et dépanner – garantir la bonne taille de l'image du code-barres + +Après avoir généré les images, vous pouvez vouloir confirmer programmétiquement que les dimensions correspondent à vos attentes. La classe `Image` de `System.Drawing` peut lire le fichier et rapporter sa taille. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Si la hauteur ne reflète pas la valeur que vous avez définie, vérifiez : + +- **X‑dimension** : Une valeur très petite peut amener le rendu à arrondir la hauteur. +- **Format d'image** : Certains formats (par ex., JPEG) appliquent une compression qui peut modifier les dimensions en pixels lors de l'enregistrement. PNG préserve les dimensions exactes. + +## Étape 7 : Bonnes pratiques pour la taille de l'image du code-barres et les performances + +| Recommandation | Raison | +|----------------|--------| +| Conservez `x_dimension.pixels` entre 2 – 3 px pour la plupart des scanners. | Équilibre lisibilité et taille du fichier. | +| Utilisez PNG pour une sortie sans perte lorsque l'image sera imprimée. | Garantit des dimensions exactes et des bords nets. | +| Réutilisez une seule instance de `BarCodeGenerator` lors de la génération de nombreux codes-barres. | Réduit la surcharge d'allocation d'objets. | +| Validez la chaîne d'entrée selon la norme GS1 avant de l'assigner à `CodeText`. | Empêche les exceptions d'exécution et les scans invalides. | +| Stockez les images générées dans un dossier dédié avec une convention de nommage claire (par ex., `Databar_{GTIN}.png`). | Simplifie le traitement en aval et les traces d'audit. | + +## Exemple complet fonctionnel + +Voici le programme complet qui intègre toutes les étapes, de l'initialisation à la vérification. Copiez le code dans un nouveau projet console et exécutez-le. + + + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s'appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Générer une image de code-barres – GS1 Coupon UPC‑A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Créer une image de code-barres DotCode – lignes & colonnes (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Comment créer une zone silencieuse de code-barres pour ITF‑14 avec Aspose.BarCode pour .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/french/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/french/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..9d73e9aaa --- /dev/null +++ b/barcode/french/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-12 +description: Créez un databar omnidirectionnel avec Python et apprenez comment créer + une image de code‑barres en Python en utilisant Aspose.BarCode. Suivez le guide + étape par étape pour une solution complète. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: fr +lastmod: 2026-08-12 +og_description: Créez un databar omnidirectionnel avec Python et générez une image + de code‑barres en quelques minutes. Ce tutoriel présente un exemple complet et exécutable. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Créer une databar omnidirectionnelle – guide complet Python +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Créer une image de databar et de code‑barres omnidirectionnelle en Python +url: /fr/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un databar omnidirectionnel et une image de code-barres en Python + +Si vous devez **créer un databar omnidirectionnel** dans un projet Python, ce guide vous montre comment le faire ainsi que comment **créer une image de code-barres en Python** en utilisant la bibliothèque Aspose.BarCode. Vous obtiendrez un script prêt à l'exécution qui génère deux fichiers PNG avec des rapports d'aspect différents. + +Générer un DataBar conforme à la spécification omnidirectionnelle est une exigence courante pour les applications de vente au détail et de logistique. Le tutoriel couvre l'installation, la configuration de la dimension X, l'ajustement du rapport d'aspect et l'enregistrement des images finales. Aucun service externe n'est requis ; tout s'exécute localement. + +## Ce dont vous aurez besoin + +* Python 3.8 ou une version plus récente installé sur votre machine. +* Accès à un terminal ou à l'invite de commande. +* Permission d'écriture sur un dossier où les images de code-barres seront enregistrées. + +La seule dépendance tierce est **Aspose.BarCode for Python via .NET**, qui prend en charge le type Omni‑directional DataBar dès l'installation. + +## Étape 1 : Installer Aspose.BarCode pour Python + +Aspose.BarCode fournit la classe `BarcodeGenerator` utilisée dans le code d'exemple. Installez le paquet avec `pip` : + +```bash +pip install aspose-barcode +``` + +Le paquet inclut les liaisons d'exécution .NET nécessaires, vous n'avez donc pas besoin d'installer le SDK .NET séparément. + +## Étape 2 : Importer la bibliothèque et créer le générateur + +La première ligne du script crée un générateur pour un DataBar Omni‑directionnel empilé. La valeur GTIN‑14 `(01)12345678901231` est utilisée comme donnée d'exemple. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Pourquoi cette étape est importante* : la constante `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` indique à la bibliothèque d'encoder la valeur en tant que Omni‑directional DataBar, le format requis par de nombreux scanners de point de vente. + +## Étape 3 : Définir la dimension X (largeur du module) + +La dimension X définit la largeur du plus petit module de barre. Une valeur de `2` pixels produit un code-barres clair et lisible sans taille de fichier excessive. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Pourquoi cette étape est importante* : ajuster la dimension X vous permet d'équilibrer lisibilité et dimensions de l'image. Une dimension X trop petite peut rendre le code-barres difficile à lire sur des imprimantes à basse résolution. + +## Étape 4 : Configurer le rapport d'aspect et enregistrer la première image + +Le rapport d'aspect influence la hauteur globale du DataBar par rapport à sa largeur. Un rapport d'aspect de `15` crée un style visuel compact. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Astuce** : utilisez `pathlib.Path` pour construire le chemin de sortie, ce qui crée automatiquement les répertoires manquants. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Étape 5 : Modifier le rapport d'aspect pour un deuxième style visuel et enregistrer une autre image + +Passer le rapport d'aspect à `30` produit un code-barres plus haut qui peut être requis par du matériel de scanner spécifique. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Pourquoi cette étape est importante* : différents détaillants et appareils de lecture ont des contraintes de taille distinctes. Fournir les deux rapports d'aspect dans un même script vous permet de générer le style exact dont vous avez besoin sans dupliquer le code. + +## Script complet – créer un databar omnidirectionnel et une image de code-barres en Python + +Voici l'exemple complet et exécutable qui intègre toutes les étapes précédentes. Enregistrez-le sous le nom `generate_databar.py` et exécutez-le avec `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Résultat attendu + +L'exécution du script crée les fichiers suivants : + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Les deux images affichent un DataBar omnidirectionnel valide qui peut être scanné par l'équipement de vente au détail standard. + +![exemple de création d'un databar omnidirectionnel image de code-barres en Python](example_databar.png "créer un databar omnidirectionnel image de code-barres python") + +*L'image ci‑dessus est un espace réservé illustrant les deux fichiers PNG enregistrés.* + +## Gestion des problèmes courants + +| Issue | Reason | Fix | +|-------|--------|-----| +| `ImportError: No module named aspose` | Aspose.BarCode n'est pas installé ou installé dans un environnement différent. | Activez l'environnement virtuel correct et exécutez `pip install aspose-barcode`. | +| `PermissionError` when saving | Le script n'a pas la permission d'écriture pour le dossier cible. | Choisissez un répertoire que vous possédez ou exécutez le script avec les privilèges appropriés. | +| Barcode does not scan | La dimension X est trop faible ou le rapport d'aspect est incompatible avec le scanner. | Augmentez `x_dimension.pixels` à 3 ou 4, et testez différentes valeurs de `aspect_ratio` (par ex., 20, 25). | +| Missing .NET runtime | Aspose.BarCode dépend du runtime .NET sur Windows/Linux. | Installez le dernier runtime .NET depuis le site de Microsoft ; la documentation du paquet fournit des instructions spécifiques à chaque plateforme. | + +## Extension de l'exemple + +Vous pouvez adapter le script pour générer d'autres variantes de DataBar (par ex., `DATABAR_STACKED`, `DATABAR_EXPANDED`). Remplacez la constante `EncodeTypes` en conséquence : + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Si vous devez intégrer le code-barres dans un PDF, Aspose.PDF for Python peut importer directement le fichier PNG ou vous pouvez utiliser la méthode `save` avec `BarCodeImageFormat.Pdf`. + +## Conclusion + +Ce tutoriel a montré comment **créer un databar omnidirectionnel** et comment **créer une image de code-barres en Python** en utilisant Aspose.BarCode. Vous disposez maintenant d'un script complet et reproductible qui génère deux fichiers PNG avec des rapports d'aspect différents, gère les problèmes courants et peut être étendu à d'autres formats de code-barres. + +Ensuite, explorez la génération de QR codes, l'ajout du code-barres aux factures PDF, ou l'automatisation du traitement par lots pour de grands catalogues de produits. Chacun de ces sujets s'appuie sur le même modèle `BarcodeGenerator` présenté ici. Bon codage ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s'appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités d'API supplémentaires et à explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Générer une image de code-barres – GS1 Coupon UPC‑A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Créer une image de code-barres DotCode – lignes & colonnes (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Comment créer une image de code-barres et l'afficher en Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/french/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/french/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..565269858 --- /dev/null +++ b/barcode/french/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Comment générer rapidement un code‑barres avec Python. Apprenez à créer + un code‑barres à partir de données et à exporter l’image du code‑barres avec une + seule bibliothèque. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: fr +lastmod: 2026-08-12 +og_description: Comment générer un code‑barres en Python avec Aspose.BarCode. Suivez + ce guide pour créer un code‑barres à partir de données et exporter l’image du code‑barres + au format PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Comment générer un code-barres en Python – guide rapide et fiable +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Comment générer un code‑barres en Python – guide complet étape par étape +url: /fr/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment générer un code-barres en Python – guide complet étape par étape + +Si vous avez besoin de **how to generate barcode** dans une application Python, ce tutoriel vous montre le code exact dont vous avez besoin. Vous apprendrez à **create barcode from data**, ajuster son apparence, et **export barcode image** en fichier PNG — le tout en moins de dix lignes de code. + +Générer un code-barres peut sembler être une préoccupation distincte du reste de votre logique métier, mais avec une seule bibliothèque vous pouvez garder le processus intégré à votre base de code existante. Dans les sections suivantes, vous verrez un exemple complet et exécutable, comprendrez pourquoi chaque ligne est importante, et découvrirez des variantes courantes telles que la modification de la largeur du module ou le dessin d'un code-barres uniquement en contour. + +## Comment générer un code-barres avec la bibliothèque Aspose.BarCode + +La bibliothèque Aspose.BarCode pour Python (via .NET) fournit une API simple pour de nombreuses symbologies, y compris le code-barres Planet utilisé dans ce guide. Avant de commencer, assurez-vous que le paquet est installé : + +```bash +pip install aspose-barcode +``` + +> **Astuce :** Utilisez un environnement virtuel pour éviter les conflits de version avec d’autres projets. + +### 1. Importer les classes requises + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Ces importations vous donnent accès à la classe générateur, à l’énumération des types de code-barres, et à l’énumération des formats d’image utilisée lors de l’enregistrement du résultat. + +### 2. Créer un code-barres à partir de données + +La première étape consiste à **create barcode from data**. Le constructeur `BarcodeGenerator` prend la symbologie et la chaîne brute que vous souhaitez encoder. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +La valeur `EncodeTypes.Planet` sélectionne le code-barres Planet, tandis que `"123456"` est la charge utile qui apparaîtra dans l’image finale. + +### 3. Ajuster la dimension X (largeur du module) + +La dimension X contrôle la largeur de chaque module du code-barres (la barre fine). La régler à 4 pixels donne une image claire et lisible sans rendre le fichier trop volumineux. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Pourquoi c’est important :** Une dimension X plus grande améliore la fiabilité du scan sur les imprimantes basse résolution, tandis qu’une valeur plus petite réduit la taille du fichier pour une utilisation web. + +### 4. Exporter l’image du code-barres (style rempli) + +Vous pouvez maintenant **export barcode image** en utilisant la méthode `save`. L’exemple enregistre un fichier PNG, mais vous pouvez choisir JPEG, BMP ou TIFF en modifiant l’énumération `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +Le fichier `PlanetFilled.png` contient un code-barres Planet entièrement rempli, prêt à être imprimé ou intégré dans un PDF. + +### 5. Créer un second générateur pour un code-barres uniquement en contour + +Si vous avez besoin d’une version en contour (barres vides), vous devez créer un nouveau générateur car le drapeau `filled_bars` ne peut pas être modifié après l’enregistrement de l’image. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Appliquer le même réglage de dimension X + +Lorsque vous créez un second générateur, vous devez répéter tous les réglages visuels que vous souhaitez conserver de façon cohérente. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Désactiver les barres remplies pour un code-barres en contour + +Définir `filled_bars` à `False` indique au rendu de ne dessiner que les contours de chaque module, produisant une image plus légère qui peut être utile à des fins de conception. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Exporter l’image du code-barres en contour + +Enfin, **export barcode image** à nouveau, cette fois en enregistrant la version en contour. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Vous avez maintenant deux fichiers PNG : un avec des barres solides (`PlanetFilled.png`) et un avec uniquement les contours (`PlanetEmpty.png`). + +## Exporter l’image du code-barres dans d’autres formats (optionnel) + +La méthode `save` prend en charge plusieurs formats. Pour exporter en JPEG avec une qualité de 90 % : + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Si vous avez besoin d’un arrière-plan transparent pour le web, choisissez PNG avec un canal alpha : + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Variantes courantes et cas limites + +| Scénario | Modification requise | Extrait de code | +|----------|----------------------|-----------------| +| **Different symbology** (e.g., QR) | Use a different `EncodeTypes` value | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Custom foreground color** | Set `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Higher resolution** | Increase DPI via `image_width` and `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Large data strings** | Ensure data length fits the symbology spec | Validate length before creating the generator | + +> **Attention :** Fournir des données qui dépassent la longueur maximale pour la symbologie choisie déclenche une exception d’exécution. Validez toujours la longueur de la chaîne ou capturez `ArgumentException`. + +## Exemple complet et exécutable + +Voici le script complet que vous pouvez copier‑coller dans un fichier nommé `generate_planet_barcode.py`. Ajustez `YOUR_DIRECTORY` vers un dossier qui existe sur votre machine. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +L’exécution de ce script produit deux fichiers PNG dans le répertoire spécifié. Vérifiez le résultat en ouvrant les images avec n’importe quel visualiseur d’images ; les deux doivent afficher un code-barres Planet encodant la chaîne `123456`. + +## Conclusion + +Vous savez maintenant **how to generate barcode** en Python avec Aspose.BarCode, comment **create barcode from data**, et comment **export barcode image** à la fois en styles remplis et en contour. Le même modèle s’applique à d’autres symbologies, formats d’image et personnalisations visuelles, vous offrant une base flexible pour toute fonctionnalité liée aux codes-barres dans votre application. + +### Prochaines étapes + +* Explorez d’autres symbologies telles que QR, Code‑128 ou DataMatrix en remplaçant `EncodeTypes.Planet` par la valeur souhaitée. +* Intégrez les fichiers PNG générés dans des rapports PDF en utilisant des bibliothèques comme `ReportLab` ou `PyPDF2`. +* Expérimentez avec des valeurs dynamiques de dimension X pour adapter la taille du code-barres en fonction de la résolution d’écran ou du DPI de l’imprimante. + +Bonne programmation, et n’hésitez pas à adapter l’exemple pour répondre aux exigences de votre propre projet ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Comment générer une image de code-barres en Java avec Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Comment générer un code-barres Java – Guide complet de configuration](/barcode/english/java/barcode-configuration/) +- [Comment créer des images de code128 en Java avec Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/german/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/german/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..b2b0fdc9b --- /dev/null +++ b/barcode/german/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,297 @@ +--- +category: general +date: 2026-08-12 +description: Barcode‑Generator‑Beispiel, das zeigt, wie man Barcodes mit präziser + Pixelgröße erzeugt. Lernen Sie, die Modulbreite, die Balkenhöhe einzustellen und + Planet‑Barcodes zu erstellen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: de +lastmod: 2026-08-12 +og_description: Das Barcode‑Generator‑Beispiel zeigt, wie man Barcodes mit genauen + Pixelabmessungen erzeugt. Folgen Sie dieser Anleitung, um die Modulbreite und die + Balkenhöhe für Planet‑ und RM4SCC‑Codes zu steuern. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: Barcode-Generator-Beispiel – Pixelgröße in C# anpassen +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Barcode‑Generator‑Beispiel – Schritt‑für‑Schritt‑Anleitung für benutzerdefinierte + Pixelgrößen +url: /de/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode‑Generator‑Beispiel – Schritt‑für‑Schritt‑Anleitung für benutzerdefinierte Pixelgrößen + +Wenn Sie ein **barcode generator example** benötigen, das Ihnen die Kontrolle über jedes Pixel gibt, zeigt Ihnen diese Anleitung genau, wie das funktioniert. Sie lernen, die Modulbreite festzulegen, eine feste Balkenhöhe zu definieren und sowohl Planet‑ als auch RM4SCC‑Barcodes mit vorhersehbaren Abmessungen zu erzeugen. + +Die meisten Entwickler kämpfen mit der Frage „wie man Barcode‑Bilder generiert“, die auf jedem Bildschirm oder Drucker gleich aussehen. Die untenstehenden Code‑Snippets lösen dieses Problem, indem sie die Pixel‑Parameter der Aspose.BarCode for .NET‑Bibliothek offenlegen, sodass Sie konsistente Ausgaben ohne Rätselraten erzeugen können. + +## Was Sie lernen werden + +* Wie Sie das erforderliche NuGet‑Paket installieren. +* Wie Sie einen Planet‑Barcode mit automatisch berechneter Höhe erzeugen. +* Wie Sie einen Planet‑Barcode mit einer expliziten Höhe von 100 Pixel erzeugen. +* Wie Sie einen RM4SCC‑Barcode mit derselben expliziten Höhe erzeugen. +* Warum **barcode pixel size** für die Scan‑Zuverlässigkeit wichtig ist. +* Tipps zur Fehlersuche bei häufigen Problemen beim Erzeugen von Planet‑Barcode‑Bildern. + +Sie benötigen nur .NET 6 oder höher, eine grundlegende C#‑Entwicklungsumgebung und eine Internetverbindung, um das NuGet‑Paket zu beziehen. + +--- + +## barcode generator example – Entwicklungsumgebung einrichten + +Bevor Sie Code schreiben, stellen Sie sicher, dass die Aspose.BarCode‑Bibliothek Ihrem Projekt zur Verfügung steht. + +### Aspose.BarCode‑Paket installieren + +Öffnen Sie ein Terminal in Ihrem Projektordner und führen Sie aus: + +```bash +dotnet add package Aspose.BarCode +``` + +Der Befehl fügt die neueste stabile Version von **Aspose.BarCode** zu Ihrer `csproj`‑Datei hinzu. Nachdem die Wiederherstellung abgeschlossen ist, können Sie die Klasse `BarcodeGenerator` verwenden. + +> **Pro‑Tipp:** Ziel‑Framework .NET 6 oder .NET 7 wählen, um von den neuesten Leistungsverbesserungen und der standardmäßigen UTF‑8‑Verarbeitung zu profitieren. + +### Notwendige `using`‑Direktiven hinzufügen + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Diese Namespaces stellen die Klasse `BarcodeGenerator` und das Enum `BarCodeImageFormat` bereit, die später im Tutorial verwendet werden. + +--- + +## Wie man einen Barcode mit benutzerdefinierter Pixelgröße erzeugt + +Die folgenden drei Schritte illustrieren das komplette **barcode generator example**. Jeder Schritt baut auf dem vorherigen auf, sodass Sie den gesamten Block in eine Konsolen‑App kopieren und unverändert ausführen können. + +### Schritt 1 – Planet‑Barcode mit automatisch berechneter Höhe erzeugen + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Warum das funktioniert:** +*Die Eigenschaft `XDimension` definiert die Breite eines einzelnen Barcode‑Moduls (das kleinste schwarze oder weiße Element). Wenn Sie `BarHeight` weglassen, berechnet die Bibliothek eine Höhe, die das Standard‑Seitenverhältnis für Planet‑Codes beibehält.* + +**Erwartete Ausgabe:** Eine PNG‑Datei namens `PlanetAuto.png`, die einen sauberen Planet‑Barcode enthält. Die Höhe passt sich der 4‑Pixel‑Modulbreite an und liegt typischerweise bei etwa 60 Pixel für eine sechs‑stellige Nutzlast. + +### Schritt 2 – Planet‑Barcode mit expliziter Höhe von 100 Pixel erzeugen + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Warum Sie das benötigen könnten:** +Manchmal erwartet das Scan‑Gerät eine Mindestbalkenhöhe für eine zuverlässige Erkennung. Durch das Setzen von `BarHeight.Pixels` stellen Sie sicher, dass jedes erzeugte Bild diese Anforderung erfüllt, unabhängig von der Länge der codierten Daten. + +**Erwartete Ausgabe:** `PlanetHeight100.png` zeigt dieselben Daten wie zuvor, jedoch sind die Balken exakt 100 Pixel hoch, sodass Sie die visuelle Größe vollständig kontrollieren können. + +### Schritt 3 – RM4SCC‑Barcode mit derselben expliziten Höhe erzeugen + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Warum das wichtig ist:** +`EncodeTypes.RM4SCC` ist ein gestapelter Linear‑Barcode, der in der Logistik verwendet wird. Die Angleichung seiner Balkenhöhe an den Planet‑Barcode vereinfacht die Stapelverarbeitung, wenn beide Symboliken auf demselben Etikett vorkommen. + +**Erwartete Ausgabe:** `RM4SCCHeight100.png` zeigt einen perfekt dimensionierten RM4SCC‑Barcode, der der für den Planet‑Code festgelegten Höhe von 100 Pixel entspricht. + +> **Ergebnis‑Verifizierung:** Öffnen Sie jedes PNG in einem Bildbetrachter und prüfen Sie, dass die schwarzen Balken exakt 4 Pixel breit und – wo Sie es angegeben haben – 100 Pixel hoch sind. Sie können die Dateien auch einer Barcode‑Scanner‑App zuführen, um sicherzustellen, dass sie zu „123456“ dekodieren. + +--- + +## Verständnis von Barcode‑Pixelgröße und Balkenhöhe + +### Was ist **barcode pixel size**? + +*Pixelgröße* bezeichnet die physische Anzahl von Bildschirm‑ oder Drucker‑Pixeln, die ein einzelnes Modul (`XDimension`) darstellen. Eine größere Pixelgröße erzeugt einen größeren Barcode, der für Scanner mit niedriger Auflösung leichter zu lesen ist, jedoch mehr Etiketten‑Platz beansprucht. + +### Wie beeinflusst `BarHeight` die Lesbarkeit? + +Die Eigenschaft `BarHeight` steuert die vertikale Länge der Balken. Standards für die meisten 1‑D‑Barcodes (einschließlich Planet und RM4SCC) empfehlen eine Mindesthöhe von 10 mm bei 300 dpi, was etwa 118 Pixel entspricht. Eine geringere Höhe kann zu Lesefehlern führen, insbesondere bei mobilen Kameras. + +### Wann sollte die Bibliothek die Höhe automatisch berechnen? + +Wenn Sie Barcodes ausschließlich zur Anzeige auf Bildschirmen erzeugen, hält die automatische Berechnung das Seitenverhältnis konsistent und reduziert den manuellen Aufwand. Für gedruckte Etiketten, die strenge ISO‑Spezifikationen erfüllen müssen, sollten Sie **die Balkenhöhe explizit setzen**. + +--- + +## Häufige Stolperfallen und bewährte Vorgehensweisen beim Erzeugen von Planet‑Barcodes + +| Stolperfalle | Warum es passiert | Lösung | +|--------------|-------------------|--------| +| Balken erscheinen zu dünn oder zu dick | `XDimension` bleibt bei Standard (1 Pixel) auf hochauflösenden Displays | `XDimension.Pixels` auf mindestens 3‑4 setzen für bessere Sichtbarkeit | +| Scanner kann den Code nicht lesen | `BarHeight` ist zu klein für die Brennweite des Scanners | `BarHeight.Pixels` ≥ 100 für die meisten mobilen Scanner verwenden | +| Bild ist nach Skalierung unscharf | Speicherung als JPEG führt zu Kompressionsartefakten | Als PNG (`BarCodeImageFormat.Png`) speichern für verlustfreie Ausgabe | +| Unerwarteter Barcode‑Typ | Falscher Wert im `EncodeTypes`‑Enum | Prüfen, dass `EncodeTypes.Planet` für die Planet‑Symbolik verwendet wird | + +### Pro‑Tipp zur Performance + +Wenn Sie Tausende von Barcodes in einem Batch‑Job erzeugen, verwenden Sie eine einzige `BarcodeGenerator`‑Instanz und ändern Sie nur `CodeText` sowie die Größenparameter zwischen den Saves. Das verhindert wiederholte Allokationen interner Rendering‑Objekte und kann die Ausführungszeit um bis zu 30 % reduzieren. + +--- + +## Vollständiges funktionierendes Beispiel – alles zusammenführen + +Erstellen Sie ein neues Konsolen‑Projekt (`dotnet new console -n BarcodeDemo`) und ersetzen Sie den Inhalt von `Program.cs` durch das Folgende: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Führen Sie das Programm mit `dotnet run` aus. Nach der Ausführung finden Sie drei PNG‑Dateien im Projektordner, die jeweils ein anderes **barcode generator example**‑Szenario illustrieren. + +--- + +## Nächste Schritte und verwandte Themen + +* **Wie man Barcodes in anderen Formaten erzeugt** – erkunden Sie `EncodeTypes.Code128`, `EncodeTypes.QR` und `EncodeTypes.DataMatrix` für 2‑D‑Bedürfnisse. +* **Barcodes in PDFs einbetten** – kombinieren Sie Aspose.BarCode mit Aspose.PDF, um Barcodes direkt in Rechnungsvorlagen zu platzieren. +* **Dynamische Barcode‑Größe basierend auf Benutzereingaben** – berechnen Sie ... + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/german/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/german/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..f49248cca --- /dev/null +++ b/barcode/german/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Konfigurieren Sie das Databar-Barcode-Layout in Python schnell. Lernen + Sie, Spalten und Zeilen festzulegen und Bilder mit der Barcode‑Generator‑Bibliothek + zu speichern. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: de +lastmod: 2026-08-12 +og_description: Konfigurieren Sie das Databar‑Barcode‑Layout in Python, um Spalten, + Zeilen und die Bildausgabe zu steuern. Folgen Sie dieser Anleitung für eine sofort + einsatzbereite Lösung. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Databar-Barcode-Layout in Python konfigurieren – vollständiges Tutorial +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Databar-Barcode-Layout in Python konfigurieren – Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Databar-Barcode-Layout in Python konfigurieren – Schritt‑für‑Schritt‑Anleitung + +Wenn Sie **Databar-Barcode-Layout in Python konfigurieren** müssen, führt Sie diese Anleitung durch den gesamten Prozess. Sie sehen, wie Sie die Anzahl der Spalten oder Zeilen für einen Databar Expanded Stacked‑Barcode festlegen und das resultierende Bild mit einem einzigen Aufruf der Barcode‑Generator‑Bibliothek speichern. + +Die Steuerung des Layouts ist entscheidend, wenn Sie Barcodes auf schmalen Verpackungen, Quittungen oder mobilen Bildschirmen einbetten. In den folgenden Abschnitten behandeln wir die erforderlichen Importe, die beiden Layout‑Optionen (Spalten und Zeilen) und bewährte Methoden zum Speichern eines sauberen PNG‑Bildes. + +## Was Sie benötigen + +* Python 3.8 oder neuer +* `aspose.barcode` (oder ein kompatibles Barcode‑Generierungspaket) installiert + ```bash + pip install aspose-barcode + ``` +* Schreibberechtigung für einen Ordner, in dem die PNG‑Dateien gespeichert werden + +Es werden keine zusätzlichen externen Werkzeuge benötigt – die Bibliothek übernimmt das Rendern, Skalieren und die Bildkodierung intern. + +## So konfigurieren Sie das Databar-Barcode-Layout in Python + +Der Kern der Lösung ist die Klasse `BarcodeGenerator`. Sie akzeptiert ein `EncodeTypes`‑Enum, das die Barcode‑Symbologie identifiziert – in diesem Fall `EncodeTypes.DatabarExpandedStacked`. Nach dem Erstellen des Generators können Sie das Layout anpassen, indem Sie die Eigenschaften `columns` oder `rows` im Parameterobjekt `data_bar` setzen. + +### Schritt 1: Erforderliche Klassen importieren + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Diese Importe geben Ihnen Zugriff auf den Generator, das Aufzählungs‑Element für Databar‑Typen und die PNG‑Bildformat‑Konstante. + +### Schritt 2: Einen Barcode‑Generator für Databar Expanded Stacked erstellen + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Warum dieser Schritt?* +`EncodeTypes.DatabarExpandedStacked` weist die Bibliothek an, die **Databar Expanded Stacked**‑Symbologie zu erzeugen, die längere numerische Zeichenketten unterstützt und dabei einen kompakten Platzbedarf beibehält. Das zweite Argument ist die zu kodierende Daten; es kann jede Zeichenkette sein, die der Databar‑Spezifikation entspricht. + +### Schritt 3: Anzahl der Spalten festlegen (horizontales Layout) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** ist die Schlüsselphrase für diese Operation. Wenn Sie die Spaltenanzahl erhöhen, breitet sich der Barcode horizontal aus, was bei breiten Etiketten nützlich sein kann. Die Bibliothek berechnet die Modulbreite automatisch neu, um die Gesamtabmessungen konsistent zu halten. + +#### Profi‑Tipp +Die maximale Spaltenanzahl für Databar Expanded Stacked beträgt 8. Wird ein höherer Wert angegeben, wird er auf das Maximum begrenzt, aber es ist besser, die Eingabe vorher zu validieren. + +### Schritt 4: Barcode‑Bild mit Spalten‑Layout speichern + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** ist die Aktion, die den gerenderten Barcode auf die Festplatte schreibt. PNG ist verlustfrei und bewahrt die scharfen Kanten, die für zuverlässiges Scannen erforderlich sind. + +### Schritt 5: Einen zweiten Generator für denselben Barcode‑Typ erstellen (Zeilen‑Layout) + +Wenn Sie einen vertikalen Stapel bevorzugen, arbeiten Sie mit Zeilen statt mit Spalten. Der untenstehende Code verwendet denselben Wert erneut, erstellt jedoch eine neue `BarcodeGenerator`‑Instanz, um das Mischen von Spalten‑ und Zeileneinstellungen zu vermeiden. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Schritt 6: Anzahl der Zeilen festlegen (vertikales Layout) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** ordnet die Barcode‑Module vertikal an. Ein Drei‑Zeilen‑Layout reduziert die Höhe jedes einzelnen Stacks, wodurch der Barcode für schmale Quittungen oder mobile Bildschirme geeignet ist. + +#### Randfall +Wenn Sie `rows` auf 1 setzen, erzeugt die Bibliothek einen einzeiligen Databar (entsprechend einem Standard‑Databar). Werte unter 1 werden ignoriert und auf den Standardwert (1 Zeile) zurückgesetzt. + +### Schritt 7: Barcode‑Bild mit Zeilen‑Layout speichern + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Erneut **save barcode image** mit PNG, um die Ausgabe scharf zu halten. + +## Vollständiges ausführbares Beispiel + +Wenn Sie alle Teile zusammenfügen, erhalten Sie ein eigenständiges Skript, das Sie in jedes Python‑Projekt einbinden können. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Erwartete Ausgabe** + +Beim Ausführen des Skripts werden zwei PNG‑Dateien erstellt: + +* `output/ExpandedCols4.png` – ein Barcode, der über vier Spalten gestreckt ist +* `output/ExpandedRows3.png` – ein Barcode, der in drei Zeilen komprimiert ist + +Beide Bilder können in jedem Bildbetrachter geöffnet oder direkt in PDF‑Rechnungen, Etiketten‑Vorlagen oder Webseiten importiert werden. + +## Häufige Fragen und Fehlersuche + +| Frage | Antwort | +|----------|--------| +| *Was ist, wenn der Barcode unscharf aussieht?* | Erhöhen Sie die Bildauflösung, indem Sie `barcode_generator.parameters.image_width` und `image_height` vor dem Aufruf von `save` setzen. | +| *Kann ich andere Bildformate verwenden?* | Ja. Ersetzen Sie `BarCodeImageFormat.Png` durch `Jpeg`, `Bmp` oder `Gif`, je nach Bedarf. | +| *Gibt es ein Limit für die Datenlänge?* | Databar Expanded Stacked unterstützt bis zu 74 numerische Zeichen. Wird das Limit überschritten, wird eine `ArgumentException` ausgelöst. | +| *Wie ändere ich die Vordergrundfarbe?* | Verwenden Sie `barcode_generator.parameters.barcode.color = Color.Blue` (importieren Sie `System.Drawing.Color`). | +| *Kann ich Spalten und Zeilen kombinieren?* | Nein. Die API behandelt Spalten und Zeilen als gegenseitig exklusive Layout‑Modi. Pro Barcode‑Instanz wählen Sie einen Modus. | + +## Nächste Schritte + +Jetzt, da Sie **Databar-Barcode-Layout konfigurieren** können, sollten Sie diese verwandten Themen erkunden: + +* **Textbeschriftungen hinzufügen** – verwenden Sie `barcode_generator.parameters.barcode.code_text`, um den codierten Wert unter dem Bild anzuzeigen. +* **Barcode in ein PDF einbetten** – kombinieren Sie das erzeugte PNG mit `aspose.pdf`, um druckbare Dokumente zu erstellen. +* **Dynamische Größenanpassung** – berechnen Sie die optimale Spalten‑ oder Zeilenanzahl basierend auf den Etikettendimensionen zur Laufzeit. +* **Stapelverarbeitung** – iterieren Sie über eine CSV mit Produktcodes, um automatisch eine Bibliothek von Barcode‑Bildern zu erzeugen. + +Experimentieren Sie mit verschiedenen Spalten‑ und Zeilenwerten, um zu sehen, wie sie die Scan‑Zuverlässigkeit auf Ihren Zielgeräten beeinflussen. Je mehr Sie testen, desto besser verstehen Sie die Kompromisse zwischen Barcode‑Größe, Lesbarkeit und Platzbeschränkungen. + +--- + +*Viel Spaß beim Coden! Wenn Ihnen dieses Tutorial nützlich war, teilen Sie es mit Kolleg*innen oder hinterlassen Sie einen Kommentar zu den Layout‑Herausforderungen, denen Sie begegnet sind.* + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu beherrschen und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [DotCode-Barcode-Bild erstellen – Zeilen & Spalten (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Barcode‑Bild in C# erstellen – Codablock F‑Zeilen & Spalten konfigurieren](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [Ein‑dimensionaler Databar‑Barcode‑Höhen‑Anpassung](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/german/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/german/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..8ebdb2d08 --- /dev/null +++ b/barcode/german/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: Erstellen Sie ein Barcode‑Bild in C# mit BarCodeGenerator. Erfahren Sie, + wie Sie DataBar generieren, die Größe des Barcode‑Bildes steuern und mehrere Barcodes + effizient erstellen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: de +lastmod: 2026-08-12 +og_description: Erstelle Barcode‑Bild in C# mit BarCodeGenerator. Dieses Tutorial + zeigt Schritt für Schritt, wie man DataBar‑Codes generiert, die Größe des Barcode‑Bildes + anpasst und mehrere Barcodes erzeugt. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Barcode-Bild in C# erstellen – vollständige BarCodeGenerator-Anleitung +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Barcode-Bild in C# mit BarCodeGenerator erstellen +url: /de/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode‑Bild in C# mit BarCodeGenerator erstellen + +Wenn Sie ein **barcode image** in einer .NET‑Anwendung erstellen müssen, zeigt Ihnen diese Anleitung genau, wie Sie dies mit der `BarCodeGenerator`‑Klasse tun. Egal, ob Sie ein Einzelhandels‑POS‑System oder ein Inventar‑Tracking‑Tool entwickeln, Sie lernen, DataBar‑Symbole zu erzeugen, die Größe des barcode image zu steuern und mehrere Barcodes in einem Durchlauf zu produzieren. + +Sie werden außerdem entdecken, wie die **barcode generator c#** API Ihnen ermöglicht, Abmessungen anzupassen, Ausgabeformate zu wechseln und Randfälle wie ungültige Datenzeichenfolgen zu behandeln. Am Ende des Tutorials können Sie sicher **create multiple barcodes** ohne wiederholenden Code schreiben. + +## Voraussetzungen + +- .NET 6.0 oder höher installiert +- Eine Entwicklungsumgebung (Visual Studio, Rider oder VS Code) +- Das Aspose.BarCode for .NET NuGet‑Paket (oder eine kompatible Bibliothek, die `BarCodeGenerator` bereitstellt) + +Sie können das Paket hinzufügen mit: + +```bash +dotnet add package Aspose.BarCode +``` + +## Was dieses Tutorial abdeckt + +1. Einrichten einer **barcode generator c#** Instanz für DataBar Omni‑directional‑Kodierung. +2. Anpassen der **barcode image size** durch Ändern der X‑Dimension und der Balkenhöhe. +3. Verwenden einer Schleife, um **create multiple barcodes** mit unterschiedlichen Höhen zu erzeugen. +4. Speichern der Bilder als PNG‑Dateien und Überprüfen der Ausgabe. + +Alle Code‑Snippets sind vollständig und bereit zum Kopieren‑Einfügen in ein neues Konsolenprojekt. + +![Create barcode image example](barcode-example.png){alt="Beispiel für Barcode‑Bild erstellen"} + +## Schritt 1: Generator initialisieren – Grundlagen zum Erstellen von barcode image + +Der erste Schritt besteht darin, `BarCodeGenerator` mit der gewünschten Symbolik zu instanziieren. Für ein DataBar Omni‑directional‑Symbol verwenden Sie `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Warum das wichtig ist:** Das Instanziieren des Generators definiert die Kodierungsregeln und die Datenpayload. Wenn Sie den korrekten `EncodeTypes`‑Wert weglassen, erzeugt die Bibliothek einen nicht unterstützten Barcode oder wirft eine Ausnahme. + +## Schritt 2: X‑dimension und Balkenhöhe konfigurieren – barcode image size steuern + +Die visuelle Größe eines Barcodes wird von zwei Parametern bestimmt: + +| Parameter | Was es steuert | Typischer Bereich | +|-----------|----------------|-------------------| +| `x_dimension.pixels` | Width of the smallest module (the “dot”) | 1 – 4 px | +| `bar_height.pixels` | Height of the vertical bars | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Pro Tipp:** Eine kleinere X‑Dimension liefert ein hochauflösendes Bild, kann jedoch auf Druckern mit geringer Qualität schwerer zu scannen sein. Passen Sie den Wert an die Ziel‑Scanning‑Ausrüstung an. + +## Schritt 3: Ersten Barcode speichern – barcode image für 30 px Höhe erstellen + +Jetzt können Sie das Bild erzeugen und auf die Festplatte schreiben. Die `Save`‑Methode akzeptiert einen Dateipfad und ein Bildformat‑Enum. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Erwartetes Ergebnis:** Eine PNG‑Datei mit dem Namen `Databar30.png` erscheint in `C:\Barcodes`. Beim Öffnen der Datei wird ein DataBar Omni‑directional‑Symbol mit einem klaren, hochkontrastierenden Muster angezeigt. + +## Schritt 4: Höhe ändern und zusätzliche Bilder erzeugen – create multiple barcodes + +Um **create multiple barcodes** mit unterschiedlichen Abmessungen zu **create**, müssen Sie lediglich die `BarHeight`‑Eigenschaft ändern und `Save` erneut aufrufen. Dadurch wird ein erneutes Instanziieren des Generators vermieden, was Speicher und CPU‑Zeit spart. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Warum das funktioniert:** Das `BarCodeGenerator`‑Objekt speichert den gesamten Konfigurationszustand. Das Ändern einer einzelnen Eigenschaft aktualisiert die Rendering‑Engine für den nächsten `Save`‑Aufruf, sodass Sie **create multiple barcodes** effizient erzeugen können. + +## Schritt 5: Fortgeschritten – how to generate DataBar mit benutzerdefinierten Daten + +Das obige Beispiel verwendet eine statische GS1‑Payload. In realen Szenarien müssen Sie häufig variable Produktkennungen einbetten. Die Bibliothek akzeptiert jede Zeichenfolge, die der DataBar‑Spezifikation entspricht. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Wichtiger Punkt:** Das Setzen von `generator.CodeText` aktualisiert die kodierten Daten, ohne das Objekt neu zu erstellen. Dies ist das empfohlene **how to generate databar** Muster beim Umgang mit großen Datensätzen. + +## Schritt 6: Überprüfen und Fehlerbehebung – korrekte barcode image size sicherstellen + +Nach dem Erzeugen der Bilder möchten Sie möglicherweise programmgesteuert bestätigen, dass die Abmessungen Ihren Erwartungen entsprechen. Die `Image`‑Klasse aus `System.Drawing` kann die Datei lesen und ihre Größe melden. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Wenn die Höhe nicht den von Ihnen gesetzten Wert widerspiegelt, prüfen Sie: + +- **X‑dimension**: Ein sehr kleiner Wert kann dazu führen, dass der Renderer die Höhe rundet. +- **Image format**: Einige Formate (z. B. JPEG) wenden Kompression an, die beim Speichern die Pixelabmessungen verändern kann. PNG bewahrt exakte Abmessungen. + +## Schritt 7: Best Practices für barcode image size und Performance + +| Empfehlung | Grund | +|----------------|--------| +| Behalten Sie `x_dimension.pixels` zwischen 2 – 3 px für die meisten Scanner bei. | Balanciert Lesbarkeit und Dateigröße. | +| Verwenden Sie PNG für verlustfreie Ausgabe, wenn das Bild gedruckt wird. | Garantiert exakte Abmessungen und scharfe Kanten. | +| Verwenden Sie eine einzelne `BarCodeGenerator`‑Instanz wieder, wenn Sie viele Barcodes erzeugen. | Reduziert den Overhead bei Objektallokationen. | +| Validieren Sie die Eingabezeichenfolge gegen den GS1‑Standard, bevor Sie sie `CodeText` zuweisen. | Verhindert Laufzeitausnahmen und ungültige Scans. | +| Speichern Sie erzeugte Bilder in einem dedizierten Ordner mit einer klaren Namenskonvention (z. B. `Databar_{GTIN}.png`). | Vereinfacht die nachgelagerte Verarbeitung und Audit‑Trails. | + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie das vollständige Programm, das alle Schritte von der Initialisierung bis zur Verifizierung enthält. Kopieren Sie den Code in ein neues Konsolenprojekt und führen Sie ihn aus. + + + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Barcode‑Bild erzeugen – GS1 Coupon UPC‑A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode‑Barcode‑Bild erstellen – Zeilen & Spalten (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Wie man eine Barcode‑Quiet‑Zone für ITF‑14 mit Aspose.BarCode für .NET erstellt](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/german/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/german/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..da898be7f --- /dev/null +++ b/barcode/german/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-08-12 +description: Erstellen Sie einen omnidirektionalen Databar mit Python und lernen Sie, + wie Sie ein Barcode‑Bild in Python mit Aspose.BarCode erzeugen. Folgen Sie der Schritt‑für‑Schritt‑Anleitung + für eine vollständige Lösung. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: de +lastmod: 2026-08-12 +og_description: Erstelle einen omnidirektionalen Databar mit Python und generiere + in Minuten ein Barcode‑Bild mit Python. Dieses Tutorial zeigt ein vollständiges, + ausführbares Beispiel. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Erstelle omnidirektionale Databar – vollständiger Python-Leitfaden +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Erstelle ein omnidirektionales Databar‑ und Barcode‑Bild in Python +url: /de/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Erstellen eines omni‑directional DataBar und Barcode‑Bildes in Python + +Wenn Sie in einem Python‑Projekt **create omni directional databar** erstellen müssen, zeigt Ihnen diese Anleitung, wie Sie das tun und auch, wie Sie **create barcode image python** mithilfe der Aspose.BarCode‑Bibliothek erstellen können. Sie erhalten ein sofort ausführbares Skript, das zwei PNG‑Dateien mit unterschiedlichen Seitenverhältnissen erzeugt. + +Das Erzeugen eines DataBar, das der Omni‑directional‑Spezifikation entspricht, ist eine häufige Anforderung für Einzelhandels‑ und Logistikanwendungen. Das Tutorial behandelt die Installation, die Konfiguration der X‑Dimension, die Anpassung des Seitenverhältnisses und das Speichern der finalen Bilder. Es werden keine externen Dienste benötigt; alles läuft lokal. + +## Was Sie benötigen + +* Python 3.8 oder neuer, auf Ihrem Rechner installiert. +* Zugriff auf ein Terminal oder die Eingabeaufforderung. +* Schreibrechte für einen Ordner, in dem die Barcode‑Bilder gespeichert werden. + +Die einzige Drittanbieter‑Abhängigkeit ist **Aspose.BarCode for Python via .NET**, das den Omni‑directional DataBar‑Typ sofort unterstützt. + +## Schritt 1: Aspose.BarCode für Python installieren + +Aspose.BarCode stellt die im Beispielcode verwendete Klasse `BarcodeGenerator` bereit. Installieren Sie das Paket mit `pip`: + +```bash +pip install aspose-barcode +``` + +Das Paket enthält die erforderlichen .NET‑Runtime‑Bindings, sodass Sie das .NET‑SDK nicht separat installieren müssen. + +## Schritt 2: Bibliothek importieren und Generator erstellen + +Die erste Zeile des Skripts erstellt einen Generator für einen gestapelten Omni‑directional DataBar. Der GTIN‑14‑Wert `(01)12345678901231` wird als Beispieldaten verwendet. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Warum dieser Schritt wichtig ist*: Die Konstante `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` weist die Bibliothek an, den Wert als Omni‑directional DataBar zu kodieren, das Format, das von vielen Point‑of‑Sale‑Scannern benötigt wird. + +## Schritt 3: X‑Dimension festlegen (Modulbreite) + +Die X‑Dimension definiert die Breite des kleinsten Balkenmoduls. Ein Wert von `2` Pixeln erzeugt einen klaren, lesbaren Barcode ohne übermäßige Dateigröße. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Warum dieser Schritt wichtig ist*: Durch Anpassen der X‑Dimension können Sie Lesbarkeit und Bildabmessungen ausbalancieren. Eine zu kleine X‑Dimension kann auf Niedrigauflösungs‑Druckern schlecht dargestellt werden. + +## Schritt 4: Seitenverhältnis konfigurieren und erstes Bild speichern + +Das Seitenverhältnis beeinflusst die Gesamthöhe des DataBar im Verhältnis zur Breite. Ein Seitenverhältnis von `15` erzeugt einen kompakten visuellen Stil. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Pro‑Tipp**: Verwenden Sie `pathlib.Path`, um den Ausgabepfad zu erstellen, der fehlende Verzeichnisse automatisch anlegt. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Schritt 5: Seitenverhältnis für einen zweiten visuellen Stil ändern und ein weiteres Bild speichern + +Das Ändern des Seitenverhältnisses auf `30` erzeugt einen höheren Barcode, der von bestimmter Scanner‑Hardware erforderlich sein kann. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Warum dieser Schritt wichtig ist*: Verschiedene Einzelhändler und Scan‑Geräte haben unterschiedliche Größenbeschränkungen. Das Bereitstellen beider Seitenverhältnisse in einem einzigen Skript ermöglicht es Ihnen, den genauen Stil zu erzeugen, den Sie benötigen, ohne Code zu duplizieren. + +## Vollständiges Skript – create omni directional databar and barcode image python + +Unten finden Sie das vollständige, ausführbare Beispiel, das alle vorherigen Schritte integriert. Speichern Sie es als `generate_databar.py` und führen Sie es mit `python generate_databar.py` aus. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Erwartete Ausgabe + +Das Ausführen des Skripts erzeugt die folgenden Dateien: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Beide Bilder zeigen einen gültigen Omni‑directional DataBar, der von Standard‑Einzelhandelsgeräten gescannt werden kann. + +![example of create omni directional databar barcode image in Python](example_databar.png "create omni directional databar barcode image python") + +*Das obige Bild ist ein Platzhalter, der die beiden gespeicherten PNG‑Dateien veranschaulicht.* + +## Umgang mit häufigen Problemen + +| Problem | Ursache | Lösung | +|-------|--------|-----| +| `ImportError: No module named aspose` | Aspose.BarCode nicht installiert oder in einer anderen Umgebung installiert. | Aktivieren Sie die richtige virtuelle Umgebung und führen Sie `pip install aspose-barcode` aus. | +| `PermissionError` when saving | Das Skript hat keine Schreibberechtigung für das Zielverzeichnis. | Wählen Sie ein Verzeichnis, das Ihnen gehört, oder führen Sie das Skript mit entsprechenden Rechten aus. | +| Barcode does not scan | X‑Dimension zu klein oder Seitenverhältnis inkompatibel mit dem Scanner. | Erhöhen Sie `x_dimension.pixels` auf 3 oder 4 und testen Sie verschiedene `aspect_ratio`‑Werte (z. B. 20, 25). | +| Missing .NET runtime | Aspose.BarCode hängt von der .NET‑Runtime unter Windows/Linux ab. | Installieren Sie die neueste .NET‑Runtime von Microsofts Seite; die Paketanleitung bietet plattformspezifische Hinweise. | + +## Erweiterung des Beispiels + +Sie können das Skript anpassen, um andere DataBar‑Varianten zu erzeugen (z. B. `DATABAR_STACKED`, `DATABAR_EXPANDED`). Ersetzen Sie die `EncodeTypes`‑Konstante entsprechend: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Falls Sie den Barcode in ein PDF einbetten müssen, kann Aspose.PDF für Python die PNG‑Datei direkt importieren oder Sie können die `save`‑Methode mit `BarCodeImageFormat.Pdf` verwenden. + +## Fazit + +Dieses Tutorial zeigte, wie man **create omni directional databar** und **create barcode image python** mit Aspose.BarCode erstellt. Sie haben nun ein vollständiges, reproduzierbares Skript, das zwei PNG‑Dateien mit unterschiedlichen Seitenverhältnissen erzeugt, gängige Fallstricke behandelt und auf andere Barcode‑Formate erweitert werden kann. + +Als Nächstes können Sie die Erzeugung von QR‑Codes, das Hinzufügen des Barcodes zu PDF‑Rechnungen oder die Automatisierung der Stapelverarbeitung für große Produktkataloge erkunden. Jeder dieser Themen baut auf dem hier gezeigten `BarcodeGenerator`‑Muster auf. Viel Spaß beim Coden! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Barcode‑Bild generieren – GS1 Coupon UPC‑A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode‑Barcode‑Bild erstellen – Zeilen & Spalten (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Wie man ein Barcode‑Bild erstellt und in Java rendert](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/german/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/german/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..4a3ec5bc6 --- /dev/null +++ b/barcode/german/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Wie man schnell Barcodes mit Python erzeugt. Lernen Sie, Barcodes aus + Daten zu erstellen und das Barcode‑Bild mit einer einzigen Bibliothek zu exportieren. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: de +lastmod: 2026-08-12 +og_description: Wie man in Python mit Aspose.BarCode einen Barcode erzeugt. Folgen + Sie dieser Anleitung, um einen Barcode aus Daten zu erstellen und das Barcode‑Bild + als PNG zu exportieren. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Wie man Barcodes in Python generiert – schneller, zuverlässiger Leitfaden +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Wie man in Python einen Barcode generiert – vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man Barcodes in Python generiert – vollständige Schritt‑für‑Schritt‑Anleitung + +Wenn Sie **wie man Barcodes generiert** in einer Python‑Anwendung benötigen, zeigt Ihnen dieses Tutorial den genauen Code, den Sie benötigen. Sie lernen, **Barcodes aus Daten zu erstellen**, ihr Aussehen anzupassen und **Barcode‑Bilder** als PNG‑Datei zu **exportieren** – alles in weniger als zehn Zeilen Code. + +Das Erzeugen eines Barcodes kann sich wie ein separater Aspekt Ihrer Geschäftslogik anfühlen, aber mit einer einzigen Bibliothek können Sie den Prozess nahtlos in Ihren bestehenden Code integrieren. In den folgenden Abschnitten sehen Sie ein vollständiges, ausführbares Beispiel, verstehen, warum jede Zeile wichtig ist, und entdecken gängige Varianten wie das Ändern der Modulbreite oder das Zeichnen eines reinen Umriss‑Barcodes. + +## Wie man Barcodes mit der Aspose.BarCode‑Bibliothek generiert + +Die Aspose.BarCode‑Bibliothek für Python (via .NET) bietet eine unkomplizierte API für viele Symbologien, einschließlich des in diesem Leitfaden verwendeten Planet‑Barcodes. Stellen Sie vor dem Start sicher, dass das Paket installiert ist: + +```bash +pip install aspose-barcode +``` + +> **Pro‑Tipp:** Verwenden Sie ein virtuelles Umfeld, um Versionskonflikte mit anderen Projekten zu vermeiden. + +### 1. Die erforderlichen Klassen importieren + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Diese Importe geben Ihnen Zugriff auf die Generator‑Klasse, die Aufzählung der Barcode‑Typen und das Bildformat‑Enum, das beim Speichern des Ergebnisses verwendet wird. + +### 2. Barcode aus Daten erstellen + +Der erste Schritt ist, **einen Barcode aus Daten zu erstellen**. Der Konstruktor `BarcodeGenerator` nimmt die Symbologie und den Rohstring, den Sie codieren möchten. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +Der Wert `EncodeTypes.Planet` wählt den Planet‑Barcode, während `"123456"` die Nutzdaten sind, die im endgültigen Bild erscheinen. + +### 3. X‑Dimension (Modulbreite) anpassen + +Die X‑Dimension steuert die Breite jedes Barcode‑Moduls (der dünnen Leiste). Auf 4 Pixel gesetzt ergibt ein klares, lesbares Bild, ohne die Datei zu groß werden zu lassen. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Warum das wichtig ist:** Eine größere X‑Dimension verbessert die Scan‑Zuverlässigkeit auf Niedrig‑Auflösungs‑Druckern, während ein kleinerer Wert die Dateigröße für die Web‑Nutzung reduziert. + +### 4. Barcode‑Bild exportieren (gefüllter Stil) + +Jetzt können Sie **das Barcode‑Bild exportieren** mit der Methode `save`. Das Beispiel speichert eine PNG‑Datei, Sie können jedoch JPEG, BMP oder TIFF wählen, indem Sie das `BarCodeImageFormat`‑Enum ändern. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +Die Datei `PlanetFilled.png` enthält einen vollständig gefüllten Planet‑Barcode, bereit zum Drucken oder Einbetten in ein PDF. + +### 5. Einen zweiten Generator für einen reinen Umriss‑Barcode erstellen + +Wenn Sie eine Umriss‑Version (leere Balken) benötigen, müssen Sie einen neuen Generator erstellen, da das Flag `filled_bars` nach dem Speichern des Bildes nicht mehr umgeschaltet werden kann. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. dieselbe X‑Dimension‑Einstellung anwenden + +Wenn Sie einen zweiten Generator erstellen, müssen Sie alle visuellen Einstellungen wiederholen, die Sie konsistent behalten wollen. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Gefüllte Balken für einen Umriss‑Barcode deaktivieren + +Das Setzen von `filled_bars` auf `False` weist den Renderer an, nur die Umrisse jedes Moduls zu zeichnen, was ein leichteres Bild erzeugt, das für Design‑Zwecke nützlich sein kann. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Das Umriss‑Barcode‑Bild exportieren + +Abschließend **das Barcode‑Bild erneut exportieren**, diesmal die Umriss‑Version speichern. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Sie haben nun zwei PNG‑Dateien: eine mit soliden Balken (`PlanetFilled.png`) und eine nur mit Umrissen (`PlanetEmpty.png`). + +## Barcode‑Bild in anderen Formaten exportieren (optional) + +Die Methode `save` unterstützt mehrere Formate. Zum Exportieren als JPEG mit 90 % Qualität: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Wenn Sie einen transparenten Hintergrund für das Web benötigen, wählen Sie PNG mit Alphakanal: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Häufige Varianten und Sonderfälle + +| Szenario | erforderliche Änderung | Code‑Snippet | +|----------|------------------------|--------------| +| **Andere Symbologie** (z. B. QR) | Verwenden Sie einen anderen `EncodeTypes`‑Wert | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Benutzerdefinierte Vordergrundfarbe** | Setzen Sie `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Höhere Auflösung** | DPI über `image_width` und `image_height` erhöhen | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Lange Datenstrings** | Sicherstellen, dass die Datenlänge zur Symbologie‑Spezifikation passt | Vor der Generator‑Erstellung Länge prüfen | + +> **Achtung:** Das Übergeben von Daten, die die maximale Länge der gewählten Symbologie überschreiten, löst eine Laufzeit‑Ausnahme aus. Validieren Sie stets die String‑Länge oder fangen Sie `ArgumentException` ab. + +## Vollständiges, ausführbares Beispiel + +Unten finden Sie das komplette Skript, das Sie in eine Datei namens `generate_planet_barcode.py` kopieren‑und‑einfügen können. Passen Sie `YOUR_DIRECTORY` an einen Ordner an, der auf Ihrem Rechner existiert. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Wenn Sie dieses Skript ausführen, werden zwei PNG‑Dateien im angegebenen Verzeichnis erzeugt. Überprüfen Sie das Ergebnis, indem Sie die Bilder in einem Bildbetrachter öffnen; beide sollten einen Planet‑Barcode mit dem String `123456` darstellen. + +## Fazit + +Sie wissen jetzt **wie man Barcodes generiert** in Python mit Aspose.BarCode, **wie man Barcodes aus Daten erstellt** und **wie man Barcode‑Bilder** sowohl im gefüllten als auch im Umriss‑Stil **exportiert**. Das gleiche Muster gilt für andere Symbologien, Bildformate und visuelle Anpassungen und bietet Ihnen eine flexible Grundlage für jede barcode‑bezogene Funktion in Ihrer Anwendung. + +### Nächste Schritte + +* Erkunden Sie weitere Symbologien wie QR, Code‑128 oder DataMatrix, indem Sie `EncodeTypes.Planet` durch den gewünschten Wert ersetzen. +* Integrieren Sie die erzeugten PNG‑Dateien in PDF‑Berichte mithilfe von Bibliotheken wie `ReportLab` oder `PyPDF2`. +* Experimentieren Sie mit dynamischen X‑Dimension‑Werten, um die Barcode‑Größe an Bildschirmauflösung oder Drucker‑DPI anzupassen. + +Viel Spaß beim Coden und passen Sie das Beispiel gern an Ihre Projektanforderungen an! + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/greek/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/greek/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..b0a698553 --- /dev/null +++ b/barcode/greek/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-08-12 +description: Παράδειγμα γεννήτριας barcode που δείχνει πώς να δημιουργήσετε barcode + με ακριβές μέγεθος pixel. Μάθετε πώς να ορίσετε το πλάτος μονάδας, το ύψος της γραμμής + και να δημιουργήσετε κωδικούς Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: el +lastmod: 2026-08-12 +og_description: Το παράδειγμα δημιουργίας γραμμωτού κώδικα δείχνει πώς να δημιουργήσετε + γραμμωτό κώδικα με ακριβείς διαστάσεις pixel. Ακολουθήστε αυτόν τον οδηγό για να + ελέγξετε το πλάτος μονάδας και το ύψος μπάρας για κώδικες Planet και RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: Παράδειγμα δημιουργού barcode – προσαρμογή μεγέθους pixel σε C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Παράδειγμα δημιουργού barcode – βήμα‑βήμα οδηγός για προσαρμοσμένα μεγέθη εικονοστοιχείων +url: /el/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# παράδειγμα γεννήτριας barcode – βήμα‑βήμα οδηγός για προσαρμοσμένα μεγέθη pixel + +Αν χρειάζεστε ένα **παράδειγμα γεννήτριας barcode** που σας επιτρέπει να ελέγχετε κάθε pixel, αυτός ο οδηγός δείχνει ακριβώς πώς να το κάνετε. Θα μάθετε να ορίζετε το πλάτος του μονάδας, να ορίζετε ένα σταθερό ύψος γραμμής, και να δημιουργείτε τόσο κωδικούς Planet όσο και RM4SCC με προβλέψιμες διαστάσεις. + +Οι περισσότεροι προγραμματιστές αντιμετωπίζουν δυσκολίες με εικόνες “πώς να δημιουργήσετε barcode” που φαίνονται διαφορετικές σε κάθε οθόνη ή εκτυπωτή. Τα αποσπάσματα κώδικα παρακάτω λύνουν αυτό το πρόβλημα εκθέτοντας τις παραμέτρους σε επίπεδο pixel της βιβλιοθήκης Aspose.BarCode for .NET, ώστε να μπορείτε να παράγετε συνεπή αποτέλεσμα χωρίς εικασίες. + +## Τι θα μάθετε + +* Πώς να εγκαταστήσετε το απαιτούμενο πακέτο NuGet. +* Πώς να δημιουργήσετε έναν κωδικό Planet με αυτόματα υπολογιζόμενο ύψος. +* Πώς να δημιουργήσετε έναν κωδικό Planet με ρητό ύψος 100 pixel. +* Πώς να δημιουργήσετε έναν κωδικό RM4SCC χρησιμοποιώντας το ίδιο ρητό ύψος. +* Γιατί το **barcode pixel size** είναι σημαντικό για την αξιοπιστία σάρωσης. +* Συμβουλές για την αντιμετώπιση κοινών προβλημάτων κατά τη δημιουργία εικόνων κωδικού Planet. + +Χρειάζεστε μόνο .NET 6 ή νεότερο, ένα βασικό περιβάλλον ανάπτυξης C# και σύνδεση στο διαδίκτυο για τη λήψη του πακέτου NuGet. + +--- + +## γεννήτρια barcode – ρύθμιση του περιβάλλοντος ανάπτυξης + +Πριν γράψετε κώδικα, βεβαιωθείτε ότι η βιβλιοθήκη Aspose.BarCode είναι διαθέσιμη στο έργο σας. + +### Εγκατάσταση του πακέτου Aspose.BarCode + +Ανοίξτε ένα τερματικό στον φάκελο του έργου σας και εκτελέστε: + +```bash +dotnet add package Aspose.BarCode +``` + +Η εντολή προσθέτει την πιο πρόσφατη σταθερή έκδοση του **Aspose.BarCode** στο `csproj` σας. Μετά την ολοκλήρωση της επαναφοράς, μπορείτε να αρχίσετε να χρησιμοποιείτε την κλάση `BarcodeGenerator`. + +> **Pro tip:** Στοχεύστε σε .NET 6 ή .NET 7 για να επωφεληθείτε από τις τελευταίες βελτιώσεις απόδοσης και τη προεπιλεγμένη διαχείριση UTF‑8. + +### Προσθήκη των απαραίτητων `using` δηλώσεων + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Αυτοί οι χώροι ονομάτων εκθέτουν την κλάση `BarcodeGenerator` και το enum `BarCodeImageFormat` που θα χρησιμοποιηθούν αργότερα στο tutorial. + +--- + +## Πώς να δημιουργήσετε barcode με προσαρμοσμένο μέγεθος pixel + +Τα παρακάτω τρία βήματα παρουσιάζουν το πλήρες **παράδειγμα γεννήτριας barcode**. Κάθε βήμα βασίζεται στο προηγούμενο, ώστε να μπορείτε να αντιγράψετε‑επικολλήσετε ολόκληρο το τμήμα σε μια εφαρμογή console και να το εκτελέσετε χωρίς αλλαγές. + +### Βήμα 1 – δημιουργία κωδικού Planet με αυτόματα υπολογιζόμενο ύψος + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Γιατί λειτουργεί:** +*Η ιδιότητα `XDimension` ορίζει το πλάτος μιας μονάδας barcode (το μικρότερο μαύρο ή λευκό στοιχείο). Όταν παραλείψετε το `BarHeight`, η βιβλιοθήκη υπολογίζει ένα ύψος που διατηρεί την τυπική αναλογία διαστάσεων για κωδικούς Planet.* + +**Αναμενόμενο αποτέλεσμα:** Ένα αρχείο PNG με όνομα `PlanetAuto.png` που περιέχει έναν καθαρό κωδικό Planet. Το ύψος του προσαρμόζεται στο πλάτος μονάδας 4 pixel, συνήθως γύρω στα 60 pixel για φορτίο έξι χαρακτήρων. + +### Βήμα 2 – δημιουργία κωδικού Planet με ρητό ύψος 100 pixel + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Γιατί μπορεί να το χρειαστείτε:** +Μερικές φορές ο εξοπλισμός σάρωσης απαιτεί ελάχιστο ύψος γραμμής για αξιόπιστη ανίχνευση. Ορίζοντας το `BarHeight.Pixels`, εξασφαλίζετε ότι κάθε παραγόμενη εικόνα πληροί αυτήν την απαίτηση, ανεξάρτητα από το μήκος των κωδικοποιημένων δεδομένων. + +**Αναμενόμενο αποτέλεσμα:** Το `PlanetHeight100.png` εμφανίζει τα ίδια δεδομένα όπως πριν, αλλά οι γραμμές είναι ακριβώς 100 pixel ψηλές, δίνοντάς σας πλήρη έλεγχο του οπτικού μεγέθους. + +### Βήμα 3 – δημιουργία κωδικού RM4SCC με το ίδιο ρητό ύψος + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Γιατί έχει σημασία:** +`EncodeTypes.RM4SCC` είναι ένας στοίβαγματος γραμμικός κωδικός που χρησιμοποιείται στη λογιστική. Η εναρμόνιση του ύψους γραμμής του με το κωδικό Planet απλοποιεί την επεξεργασία παρτίδας όταν και οι δύο συμβολισμοί εμφανίζονται στην ίδια ετικέτα. + +**Αναμενόμενο αποτέλεσμα:** Το `RM4SCCHeight100.png` εμφανίζει έναν τέλεια διαστασιολογημένο κωδικό RM4SCC, ταιριάζοντας με το ύψος 100 pixel που ορίσατε για τον κωδικό Planet. + +> **Επαλήθευση αποτελέσματος:** Ανοίξτε κάθε PNG σε προβολή εικόνας και επιβεβαιώστε ότι οι μαύρες γραμμές είναι ακριβώς 4 pixel πλάτος και, όπου καθορίσατε, 100 pixel ύψος. Μπορείτε επίσης να τροφοδοτήσετε τα αρχεία σε εφαρμογή σάρωσης barcode για να βεβαιωθείτε ότι αποκωδικοποιούν το “123456”. + +--- + +## Κατανόηση του μεγέθους pixel του barcode και του ύψους γραμμής + +### Τι είναι το **barcode pixel size**; + +*Pixel size* αναφέρεται στον φυσικό αριθμό pixel οθόνης ή εκτυπωτή που αντιπροσωπεύει μια μονάδα (`XDimension`). Μεγαλύτερο pixel size παράγει μεγαλύτερο barcode, που μπορεί να είναι πιο εύκολο για σαρωτές χαμηλής ανάλυσης, αλλά καταναλώνει περισσότερο χώρο στην ετικέτα. + +### Πώς το `BarHeight` επηρεάζει την αναγνωσιμότητα; + +Η ιδιότητα `BarHeight` ελέγχει το κάθετο μήκος των γραμμών. Τα πρότυπα για τις περισσότερες 1‑D barcode (συμπεριλαμβανομένων των Planet και RM4SCC) συνιστούν ελάχιστο ύψος 10 mm όταν εκτυπώνονται στα 300 dpi, που αντιστοιχεί περίπου σε 118 pixel. Η ρύθμιση ύψους κάτω από αυτήν μπορεί να προκαλέσει σφάλματα ανάγνωσης, ειδικά σε κάμερες κινητών. + +### Πότε να αφήσετε τη βιβλιοθήκη να υπολογίζει το ύψος αυτόματα; + +Αν δημιουργείτε barcode μόνο για προβολή στην οθόνη, ο αυτόματος υπολογισμός διατηρεί την αναλογία διαστάσεων συνεπή και μειώνει την ανάγκη χειροκίνητης ρύθμισης. Για ετικέτες που πρέπει να πληρούν αυστηρές προδιαγραφές ISO, θα πρέπει **να ορίσετε ρητά το ύψος γραμμής**. + +--- + +## Συνηθισμένα προβλήματα και βέλτιστες πρακτικές όταν δημιουργείτε κωδικό Planet + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| Οι γραμμές εμφανίζονται πολύ λεπτές ή παχιές | `XDimension` παραμένει στην προεπιλογή (1 pixel) σε οθόνες υψηλής ανάλυσης | Ορίστε `XDimension.Pixels` τουλάχιστον σε 3‑4 για οπτική καθαρότητα | +| Ο σαρωτής δεν μπορεί να διαβάσει τον κωδικό | `BarHeight` είναι πολύ μικρό για το μήκος εστίασης του σαρωτή | Χρησιμοποιήστε `BarHeight.Pixels` ≥ 100 για τους περισσότερους κινητούς σαρωτές | +| Η εικόνα είναι θολή μετά την κλιμάκωση | Η αποθήκευση ως JPEG εισάγει τεχνουργήματα συμπίεσης | Αποθηκεύστε ως PNG (`BarCodeImageFormat.Png`) για απώλεια‑απαράλειψη | +| Απρόσμενος τύπος barcode | Λανθασμένη τιμή enum `EncodeTypes` | Επαληθεύστε ότι χρησιμοποιείτε `EncodeTypes.Planet` για τη συμβολή Planet | + +### Pro tip για απόδοση + +Όταν δημιουργείτε χιλιάδες barcode σε παρτίδα, επαναχρησιμοποιήστε ένα μόνο αντικείμενο `BarcodeGenerator` και αλλάξτε μόνο το `CodeText` και τις παραμέτρους μεγέθους μεταξύ των αποθηκεύσεων. Αυτό αποφεύγει επαναλαμβανόμενες δεσμεύσεις εσωτερικών αντικειμένων απόδοσης και μπορεί να μειώσει τον χρόνο εκτέλεσης έως και 30 %. + +--- + +## Πλήρες λειτουργικό παράδειγμα – ενοποίηση όλων + +Δημιουργήστε ένα νέο έργο console (`dotnet new console -n BarcodeDemo`) και αντικαταστήστε το περιεχόμενο του `Program.cs` με το ακόλουθο: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Εκτελέστε το πρόγραμμα με `dotnet run`. Μετά την εκτέλεση θα βρείτε τρία αρχεία PNG στον φάκελο του έργου, το καθένα απεικονίζει διαφορετικό σενάριο **παραδείγματος γεννήτριας barcode**. + +--- + +## Επόμενα βήματα και συναφή θέματα + +* **Πώς να δημιουργήσετε barcode σε άλλες μορφές** – εξερευνήστε `EncodeTypes.Code128`, `EncodeTypes.QR` και `EncodeTypes.DataMatrix` για ανάγκες 2‑D. +* **Ενσωμάτωση barcode σε PDF** – συνδυάστε Aspose.BarCode με Aspose.PDF για να τοποθετήσετε barcode απευθείας σε πρότυπα τιμολογίων. +* **Δυναμικό μέγεθος barcode βάσει εισόδου χρήστη** – υπολογίστε ... + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κυριαρχήσετε επιπλέον δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/greek/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/greek/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..282fcab94 --- /dev/null +++ b/barcode/greek/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Διαμορφώστε τη διάταξη του barcode Databar σε Python γρήγορα. Μάθετε + πώς να ορίζετε στήλες, σειρές και να αποθηκεύετε εικόνες με τη βιβλιοθήκη δημιουργίας + barcode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: el +lastmod: 2026-08-12 +og_description: Ρυθμίστε τη διάταξη κώδικα γραμμής Databar σε Python για να ελέγχετε + στήλες, σειρές και την έξοδο εικόνας. Ακολουθήστε αυτόν τον οδηγό για μια έτοιμη + για εκτέλεση λύση. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Διαμόρφωση διάταξης barcode Databar σε Python – πλήρης οδηγός +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Διαμόρφωση διάταξης κωδικού Databar σε Python – βήμα‑βήμα οδηγός +url: /el/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Διαμόρφωση διάταξης barcode Databar σε Python – οδηγός βήμα‑βήμα + +Αν χρειάζεστε **διαμόρφωση διάταξης barcode Databar σε Python**, αυτός ο οδηγός σας καθοδηγεί σε όλη τη διαδικασία. Θα δείτε πώς να ορίσετε τον αριθμό των στηλών ή των γραμμών για ένα barcode Databar Expanded Stacked και πώς να αποθηκεύσετε την προκύπτουσα εικόνα με μία μόνο κλήση στη βιβλιοθήκη δημιουργίας barcode. + +Ο έλεγχος της διάταξης είναι απαραίτητος όταν ενσωματώνετε barcodes σε στενά πακέτα, αποδείξεις ή οθόνες κινητών. Στις παρακάτω ενότητες θα καλύψουμε τις απαιτούμενες εισαγωγές, τις δύο επιλογές διάταξης (στήλες και γραμμές) και τις βέλτιστες πρακτικές για αποθήκευση μιας καθαρής εικόνας PNG. + +## Τι θα χρειαστείτε + +* Python 3.8 ή νεότερη +* `aspose.barcode` (ή οποιοδήποτε συμβατό πακέτο δημιουργίας barcode) εγκατεστημένο + ```bash + pip install aspose-barcode + ``` +* Δικαίωμα εγγραφής σε φάκελο όπου θα αποθηκευτούν τα αρχεία PNG + +Δεν απαιτούνται πρόσθετα εξωτερικά εργαλεία — η βιβλιοθήκη διαχειρίζεται την απόδοση, την κλιμάκωση και την κωδικοποίηση εικόνας εσωτερικά. + +## Πώς να διαμορφώσετε τη διάταξη barcode Databar σε Python + +Ο πυρήνας της λύσης είναι η κλάση `BarcodeGenerator`. Δέχεται ένα enum `EncodeTypes` που προσδιορίζει τη συμβολική μορφή του barcode — σε αυτήν την περίπτωση `EncodeTypes.DatabarExpandedStacked`. Αφού δημιουργήσετε το generator, μπορείτε να προσαρμόσετε τη διάταξη ορίζοντας τις ιδιότητες `columns` ή `rows` στο αντικείμενο παραμέτρων `data_bar`. + +### Βήμα 1: Εισαγωγή των απαιτούμενων κλάσεων + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Αυτές οι εισαγωγές σας δίνουν πρόσβαση στον generator, στην απαρίθμηση για τους τύπους Databar και στη σταθερά μορφής εικόνας PNG. + +### Βήμα 2: Δημιουργία ενός barcode generator για Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Γιατί αυτό το βήμα;* +`EncodeTypes.DatabarExpandedStacked` λέει στη βιβλιοθήκη να παραγάγει τη **Databar Expanded Stacked** συμβολική μορφή, η οποία υποστηρίζει μεγαλύτερες αριθμητικές αλυσίδες διατηρώντας ένα συμπαγές αποτύπωμα. Το δεύτερο όρισμα είναι τα δεδομένα προς κωδικοποίηση· μπορεί να είναι οποιαδήποτε συμβολοσειρά που πληροί τις προδιαγραφές Databar. + +### Βήμα 3: Ορισμός του αριθμού των στηλών (οριζόντια διάταξη) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** είναι η βασική φράση για αυτήν τη λειτουργία. Όταν αυξάνετε τον αριθμό των στηλών, το barcode απλώνεται οριζόντια, κάτι που μπορεί να είναι χρήσιμο για πλατιά ετικέτες. Η βιβλιοθήκη επαναϋπολογίζει αυτόματα το πλάτος του μονάδας ώστε το συνολικό μέγεθος να παραμένει συνεπές. + +#### Συμβουλή επαγγελματία +Ο μέγιστος αριθμός στηλών για Databar Expanded Stacked είναι 8. Ο ορισμός τιμής μεγαλύτερης από το όριο θα την περιορίσει στο μέγιστο, αλλά είναι καλύτερο να επικυρώνετε την είσοδό σας εκ των προτέρων. + +### Βήμα 4: Αποθήκευση της εικόνας barcode με τη διάταξη στηλών + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** είναι η ενέργεια που γράφει το παραχθέν barcode στο δίσκο. Το PNG είναι χωρίς απώλειες, διατηρώντας τις αιχμηρές άκρες που απαιτούνται για αξιόπιστη σάρωση. + +### Βήμα 5: Δημιουργία δεύτερου generator για τον ίδιο τύπο barcode (διάταξη γραμμών) + +Αν προτιμάτε κατακόρυφο στοίβαγμα, εργάζεστε με γραμμές αντί για στήλες. Ο κώδικας παρακάτω επαναχρησιμοποιεί την ίδια τιμή αλλά δημιουργεί μια νέα εμφάνιση `BarcodeGenerator` για να αποφευχθεί η ανάμειξη ρυθμίσεων στηλών και γραμμών. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Βήμα 6: Ορισμός του αριθμού των γραμμών (κατακόρυφη διάταξη) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** διατάσσει τις μονάδες του barcode κάθετα. Μια διάταξη τριών γραμμών μειώνει το ύψος κάθε μεμονωμένου στοίβαγματος, καθιστώντας το barcode κατάλληλο για στενές αποδείξεις ή οθόνες κινητών. + +#### Ακραία περίπτωση +Αν ορίσετε `rows` σε 1, η βιβλιοθήκη παράγει ένα single‑row Databar (ισοδύναμο με ένα τυπικό Databar). Τιμές κάτω από 1 αγνοούνται και επαναφέρονται στην προεπιλογή (1 γραμμή). + +### Βήμα 7: Αποθήκευση της εικόνας barcode με τη διάταξη γραμμών + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Ξανά, **save barcode image** χρησιμοποιώντας PNG για να διατηρηθεί η έξοδος καθαρή. + +## Πλήρες εκτελέσιμο παράδειγμα + +Συνδυάζοντας όλα τα κομμάτια παίρνετε ένα αυτόνομο script που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο Python. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Αναμενόμενο αποτέλεσμα** + +Η εκτέλεση του script δημιουργεί δύο αρχεία PNG: + +* `output/ExpandedCols4.png` – ένα barcode τεντωμένο σε τέσσερις στήλες +* `output/ExpandedRows3.png` – ένα barcode συμπιεσμένο σε τρεις γραμμές + +Και οι δύο εικόνες μπορούν να ανοιχτούν σε οποιοδήποτε πρόγραμμα προβολής εικόνων ή να εισαχθούν απευθείας σε τιμολόγια PDF, πρότυπα ετικετών ή ιστοσελίδες. + +## Συχνές ερωτήσεις και αντιμετώπιση προβλημάτων + +| Ερώτηση | Απάντηση | +|----------|--------| +| *Τι γίνεται αν το barcode φαίνεται θολό;* | Αυξήστε την ανάλυση της εικόνας ορίζοντας `barcode_generator.parameters.image_width` και `image_height` πριν καλέσετε το `save`. | +| *Μπορώ να χρησιμοποιήσω άλλες μορφές εικόνας;* | Ναι. Αντικαταστήστε το `BarCodeImageFormat.Png` με `Jpeg`, `Bmp` ή `Gif` ανάλογα με τις ανάγκες. | +| *Υπάρχει όριο στο μήκος των δεδομένων;* | Το Databar Expanded Stacked υποστηρίζει έως 74 αριθμητικούς χαρακτήρες. Η υπέρβαση του ορίου προκαλεί `ArgumentException`. | +| *Πώς αλλάζω το χρώμα του προσκηνίου;* | Χρησιμοποιήστε `barcode_generator.parameters.barcode.color = Color.Blue` (εισαγωγή `System.Drawing.Color`). | +| *Μπορώ να συνδυάσω στήλες και γραμμές;* | Όχι. Το API αντιμετωπίζει τις στήλες και τις γραμμές ως αμοιβαία αποκλειστικούς τρόπους διάταξης. Επιλέξτε έναν για κάθε εμφάνιση barcode. | + +## Επόμενα βήματα + +Τώρα που μπορείτε να **διαμορφώσετε τη διάταξη barcode Databar**, εξετάστε τα παρακάτω συναφή θέματα: + +* **Προσθήκη κειμένου υπότιτλου** – χρησιμοποιήστε `barcode_generator.parameters.barcode.code_text` για να εμφανίσετε την κωδικοποιημένη τιμή κάτω από την εικόνα. +* **Ενσωμάτωση του barcode σε PDF** – συνδυάστε το παραγόμενο PNG με `aspose.pdf` για τη δημιουργία εκτυπώσιμων εγγράφων. +* **Δυναμικό μέγεθος** – υπολογίστε βέλτιστο αριθμό στηλών ή γραμμών βάσει των διαστάσεων της ετικέτας σε χρόνο εκτέλεσης. +* **Επεξεργασία κατά παρτίδες** – κάντε βρόχο πάνω από ένα CSV κωδικών προϊόντων για αυτόματη δημιουργία βιβλιοθήκης εικόνων barcode. + +Δοκιμάστε διαφορετικές τιμές στηλών και γραμμών για να δείτε πώς επηρεάζουν την αξιοπιστία σάρωσης στις συσκευές-στόχους σας. Όσο περισσότερο δοκιμάζετε, τόσο καλύτερα θα κατανοήσετε τις ανταλλαγές μεταξύ μεγέθους barcode, αναγνωσιμότητας και περιορισμών χώρου. + +--- + +*Καλό προγραμματισμό! Αν βρήκατε αυτόν τον οδηγό χρήσιμο, μοιραστείτε τον με συναδέλφους ή αφήστε ένα σχόλιο σχετικά με τις προκλήσεις διάταξης που αντιμετωπίσατε.* + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικά παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κυριαρχήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Create barcode image c# – Configure Codablock F Rows & Columns](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [One-Dimensional Databar Barcode Height Adjustment](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/greek/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/greek/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..a856e5c7d --- /dev/null +++ b/barcode/greek/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: Δημιουργήστε εικόνα barcode σε C# χρησιμοποιώντας το BarCodeGenerator. + Μάθετε πώς να δημιουργείτε DataBar, να ελέγχετε το μέγεθος της εικόνας barcode και + να δημιουργείτε πολλαπλά barcode αποδοτικά. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: el +lastmod: 2026-08-12 +og_description: Δημιουργήστε εικόνα barcode σε C# με το BarCodeGenerator. Αυτό το + σεμινάριο δείχνει βήμα‑βήμα πώς να δημιουργήσετε κώδικες DataBar, να προσαρμόσετε + το μέγεθος της εικόνας barcode και να παράγετε πολλαπλά barcodes. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Δημιουργία εικόνας barcode σε C# – πλήρης οδηγός BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Δημιουργία εικόνας barcode σε C# με BarCodeGenerator +url: /el/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία εικόνας barcode σε C# με BarCodeGenerator + +Αν χρειάζεστε **να δημιουργήσετε εικόνα barcode** σε μια εφαρμογή .NET, αυτός ο οδηγός σας δείχνει ακριβώς πώς να το κάνετε με την κλάση `BarCodeGenerator`. Είτε δημιουργείτε ένα σύστημα POS λιανικής είτε ένα εργαλείο παρακολούθησης αποθεμάτων, θα μάθετε να δημιουργείτε σύμβολα DataBar, να ελέγχετε το μέγεθος της εικόνας barcode και να παράγετε πολλαπλά barcodes σε μία εκτέλεση. + +Θα ανακαλύψετε επίσης πώς το API **barcode generator c#** σας επιτρέπει να ρυθμίζετε διαστάσεις, να αλλάζετε μορφές εξόδου και να αντιμετωπίζετε ειδικές περιπτώσεις όπως μη έγκυρες συμβολοσειρές δεδομένων. Στο τέλος του οδηγού μπορείτε με σιγουριά **να δημιουργήσετε πολλαπλά barcodes** χωρίς να γράφετε επαναλαμβανόμενο κώδικα. + +## Προαπαιτούμενα + +- .NET 6.0 ή νεότερο εγκατεστημένο +- Περιβάλλον ανάπτυξης (Visual Studio, Rider ή VS Code) +- Το πακέτο NuGet Aspose.BarCode for .NET (ή οποιαδήποτε συμβατή βιβλιοθήκη που παρέχει `BarCodeGenerator`) + +Μπορείτε να προσθέσετε το πακέτο με: + +```bash +dotnet add package Aspose.BarCode +``` + +## Τι καλύπτει αυτός ο οδηγός + +1. Ρύθμιση μιας **barcode generator c#** εμφάνισης για κωδικοποίηση DataBar Omni‑directional. +2. Προσαρμογή **μεγέθους εικόνας barcode** με αλλαγή του X‑dimension και του ύψους των γραμμών. +3. Χρήση βρόχου για **δημιουργία πολλαπλών barcode** με διαφορετικά ύψη. +4. Αποθήκευση των εικόνων ως αρχεία PNG και επαλήθευση του αποτελέσματος. + +Όλα τα αποσπάσματα κώδικα είναι πλήρη και έτοιμα για αντιγραφή‑επικόλληση σε ένα νέο έργο console. + +![Παράδειγμα δημιουργίας εικόνας barcode](barcode-example.png){alt="Παράδειγμα δημιουργίας εικόνας barcode"} + +## Βήμα 1: Αρχικοποίηση του γεννήτρια – βασικά δημιουργίας εικόνας barcode + +Το πρώτο βήμα είναι η δημιουργία ενός αντικειμένου `BarCodeGenerator` με τη ζητούμενη συμβολική. Για ένα σύμβολο DataBar Omni‑directional χρησιμοποιείτε το `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Γιατί είναι σημαντικό:** Η δημιουργία του γεννήτρια ορίζει τους κανόνες κωδικοποίησης και το φορτίο δεδομένων. Αν παραλείψετε τη σωστή τιμή `EncodeTypes`, η βιβλιοθήκη θα παράγει ένα μη υποστηριζόμενο barcode ή θα ρίξει εξαίρεση. + +## Βήμα 2: Διαμόρφωση X‑dimension και ύψους γραμμής – έλεγχος μεγέθους εικόνας barcode + +Το οπτικό μέγεθος ενός barcode καθορίζεται από δύο παραμέτρους: + +| Παράμετρος | Τι ελέγχει | Τυπικό εύρος | +|------------|------------|--------------| +| `x_dimension.pixels` | Πλάτος της μικρότερης μονάδας (το “σημείο”) | 1 – 4 px | +| `bar_height.pixels` | Ύψος των κάθετων γραμμών | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Συμβουλή:** Μικρότερο X‑dimension δίνει εικόνα υψηλότερης ανάλυσης αλλά μπορεί να είναι πιο δύσκολο να σαρωθεί με εκτυπωτές χαμηλής ποιότητας. Ρυθμίστε την τιμή ανάλογα με τον εξοπλισμό σάρωσης που στοχεύετε. + +## Βήμα 3: Αποθήκευση του πρώτου barcode – δημιουργία εικόνας barcode για ύψος 30 px + +Τώρα μπορείτε να δημιουργήσετε την εικόνα και να την γράψετε στο δίσκο. Η μέθοδος `Save` δέχεται διαδρομή αρχείου και έναν enum μορφής εικόνας. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Αναμενόμενο αποτέλεσμα:** Ένα αρχείο PNG με όνομα `Databar30.png` εμφανίζεται στο `C:\Barcodes`. Το άνοιγμα του αρχείου δείχνει ένα σύμβολο DataBar Omni‑directional με καθαρό, υψηλής αντίθεσης μοτίβο. + +## Βήμα 4: Αλλαγή του ύψους και δημιουργία επιπλέον εικόνων – δημιουργία πολλαπλών barcode + +Για **να δημιουργήσετε πολλαπλά barcode** με διαφορετικές διαστάσεις, χρειάζεται μόνο να τροποποιήσετε την ιδιότητα `BarHeight` και να καλέσετε ξανά το `Save`. Αυτό αποφεύγει την επανεκκίνηση του γεννήτρια, εξοικονομώντας μνήμη και χρόνο CPU. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Γιατί λειτουργεί:** Το αντικείμενο `BarCodeGenerator` διατηρεί όλη την κατάσταση διαμόρφωσης. Η αλλαγή μιας μόνο ιδιότητας ενημερώνει τη μηχανή απόδοσης για την επόμενη κλήση `Save`, επιτρέποντάς σας να **δημιουργήσετε πολλαπλά barcode** αποδοτικά. + +## Βήμα 5: Προχωρημένα – πώς να δημιουργήσετε DataBar με προσαρμοσμένα δεδομένα + +Το παραπάνω παράδειγμα χρησιμοποιεί ένα στατικό φορτίο GS1. Σε πραγματικές συνθήκες συχνά χρειάζεται να ενσωματώσετε μεταβλητούς αναγνωριστικούς προϊόντων. Η βιβλιοθήκη δέχεται οποιαδήποτε συμβολοσειρά που ταιριάζει με την προδιαγραφή DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Κύριο σημείο:** Η ρύθμιση του `generator.CodeText` ενημερώνει τα κωδικοποιημένα δεδομένα χωρίς επαναδημιουργία του αντικειμένου. Αυτό είναι το προτεινόμενο **πώς να δημιουργήσετε databar** όταν διαχειρίζεστε μεγάλα σύνολα δεδομένων. + +## Βήμα 6: Επαλήθευση και αντιμετώπιση προβλημάτων – διασφάλιση σωστού μεγέθους εικόνας barcode + +Μετά τη δημιουργία των εικόνων, μπορεί να θέλετε προγραμματιστικά να επιβεβαιώσετε ότι οι διαστάσεις ταιριάζουν με τις προσδοκίες σας. Η κλάση `Image` από το `System.Drawing` μπορεί να διαβάσει το αρχείο και να αναφέρει το μέγεθός του. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Αν το ύψος δεν αντανακλά την τιμή που ορίσατε, ελέγξτε: + +- **X‑dimension**: Μια πολύ μικρή τιμή μπορεί να κάνει τον renderer να στρογγυλοποιήσει το ύψος. +- **Image format**: Ορισμένες μορφές (π.χ., JPEG) εφαρμόζουν συμπίεση που μπορεί να αλλάξει τις διαστάσεις των pixel κατά την αποθήκευση. Το PNG διατηρεί ακριβείς διαστάσεις. + +## Βήμα 7: Καλές πρακτικές για το μέγεθος εικόνας barcode και απόδοση + +| Σύσταση | Αιτία | +|---------|-------| +| Διατηρήστε το `x_dimension.pixels` μεταξύ 2 – 3 px για τους περισσότερους σαρωτές. | Ισορροπεί την αναγνωσιμότητα και το μέγεθος του αρχείου. | +| Χρησιμοποιήστε PNG για απώλεια‑απώλειας έξοδο όταν η εικόνα θα εκτυπωθεί. | Εγγυάται ακριβείς διαστάσεις και καθαρά άκρα. | +| Επαναχρησιμοποιήστε ένα μόνο αντικείμενο `BarCodeGenerator` όταν δημιουργείτε πολλά barcode. | Μειώνει το κόστος κατανομής αντικειμένων. | +| Επικυρώστε τη συμβολοσειρά εισόδου έναντι του προτύπου GS1 πριν την αναθέσετε στο `CodeText`. | Αποτρέπει εξαιρέσεις χρόνου εκτέλεσης και μη έγκυρες σάρωσες. | +| Αποθηκεύστε τις παραγόμενες εικόνες σε αφιερωμένο φάκελο με σαφή σύστημα ονοματοδοσίας (π.χ., `Databar_{GTIN}.png`). | Απλοποιεί την επεξεργασία downstream και τα αρχεία ελέγχου. | + +## Πλήρες λειτουργικό παράδειγμα + +Παρακάτω βρίσκεται το πλήρες πρόγραμμα που ενσωματώνει όλα τα βήματα από την αρχικοποίηση μέχρι την επαλήθευση. Αντιγράψτε τον κώδικα σε ένα νέο έργο console και εκτελέστε το. + + + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικά παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Δημιουργία εικόνας barcode – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Δημιουργία εικόνας barcode DotCode – γραμμές & στήλες (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Πώς να δημιουργήσετε ζώνη σιωπής Barcode για ITF-14 χρησιμοποιώντας Aspose.BarCode για .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/greek/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/greek/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..aa14482a6 --- /dev/null +++ b/barcode/greek/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-12 +description: Δημιουργήστε πολυκατευθυντικό databar με Python και μάθετε πώς να δημιουργήσετε + εικόνα barcode με Python χρησιμοποιώντας το Aspose.BarCode. Ακολουθήστε τον οδηγό + βήμα‑βήμα για μια πλήρη λύση. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: el +lastmod: 2026-08-12 +og_description: Δημιουργήστε omni-directional databar με Python και παράγετε μια εικόνα + barcode σε λίγα λεπτά. Αυτό το σεμινάριο παρουσιάζει ένα πλήρες, εκτελέσιμο παράδειγμα. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Δημιουργήστε πανκατευθυντικό databar – πλήρης οδηγός Python +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Δημιουργία εικόνας databar και barcode με πολύπλευρη κατεύθυνση σε Python +url: /el/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία omni directional databar και εικόνας barcode σε Python + +Αν χρειάζεστε **create omni directional databar** σε ένα έργο Python, αυτός ο οδηγός σας δείχνει πώς να το κάνετε και επίσης πώς να **create barcode image python** χρησιμοποιώντας τη βιβλιοθήκη Aspose.BarCode. Θα λάβετε ένα έτοιμο‑για‑εκτέλεση script που παράγει δύο αρχεία PNG με διαφορετικές αναλογίες διαστάσεων. + +Η δημιουργία ενός DataBar που ακολουθεί την προδιαγραφή Omni‑directional είναι μια κοινή απαίτηση για εφαρμογές λιανικής και εφοδιαστικής. Το tutorial καλύπτει την εγκατάσταση, τη ρύθμιση της X‑διάστασης, την προσαρμογή της αναλογίας διαστάσεων και την αποθήκευση των τελικών εικόνων. Δεν απαιτούνται εξωτερικές υπηρεσίες· όλα εκτελούνται τοπικά. + +## Τι θα χρειαστείτε + +* Python 3.8 ή νεότερο εγκατεστημένο στον υπολογιστή σας. +* Πρόσβαση σε τερματικό ή γραμμή εντολών. +* Δικαίωμα εγγραφής σε φάκελο όπου θα αποθηκευτούν οι εικόνες barcode. + +Η μόνη εξωτερική εξάρτηση είναι **Aspose.BarCode for Python via .NET**, η οποία υποστηρίζει τον τύπο Omni‑directional DataBar έτοιμη προς χρήση. + +## Βήμα 1: Εγκατάσταση Aspose.BarCode για Python + +Το Aspose.BarCode παρέχει την κλάση `BarcodeGenerator` που χρησιμοποιείται στον κώδικα παραδείγματος. Εγκαταστήστε το πακέτο με `pip`: + +```bash +pip install aspose-barcode +``` + +Το πακέτο περιλαμβάνει τις απαραίτητες συνδέσεις χρόνου εκτέλεσης .NET, έτσι δεν χρειάζεται να εγκαταστήσετε το .NET SDK ξεχωριστά. + +## Βήμα 2: Εισαγωγή της βιβλιοθήκης και δημιουργία του γεννήτριας + +Η πρώτη γραμμή του script δημιουργεί έναν γεννήτρια για ένα stacked Omni‑directional DataBar. Η τιμή GTIN‑14 `(01)12345678901231` χρησιμοποιείται ως δείγμα δεδομένων. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Γιατί αυτό το βήμα είναι σημαντικό*: Η σταθερά `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` λέει στη βιβλιοθήκη να κωδικοποιήσει την τιμή ως Omni‑directional DataBar, που είναι η μορφή που απαιτείται από πολλούς σαρωτές σημείου πώλησης. + +## Βήμα 3: Ορισμός της X‑διάστασης (πλάτος μονάδας) + +Η X‑διάσταση ορίζει το πλάτος της μικρότερης μονάδας γραμμής. Μια τιμή `2` pixels παράγει ένα καθαρό, ευανάγνωστο barcode χωρίς υπερβολικό μέγεθος αρχείου. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Γιατί αυτό το βήμα είναι σημαντικό*: Η ρύθμιση της X‑διάστασης σας επιτρέπει να ισορροπήσετε την ευανάγνωστη και τις διαστάσεις της εικόνας. Μια X‑διάσταση που είναι πολύ μικρή μπορεί να αποδώσει κακά σε εκτυπωτές χαμηλής ανάλυσης. + +## Βήμα 4: Ρύθμιση της αναλογίας διαστάσεων και αποθήκευση της πρώτης εικόνας + +Η αναλογία διαστάσεων επηρεάζει το συνολικό ύψος του DataBar σε σχέση με το πλάτος του. Μια αναλογία `15` δημιουργεί ένα συμπαγές οπτικό στυλ. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Συμβουλή**: Χρησιμοποιήστε το `pathlib.Path` για να δημιουργήσετε τη διαδρομή εξόδου, η οποία δημιουργεί αυτόματα τους ελλείποντες φακέλους. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Βήμα 5: Αλλαγή της αναλογίας διαστάσεων για δεύτερο οπτικό στυλ και αποθήκευση άλλης εικόνας + +Αλλάζοντας την αναλογία σε `30` παράγει ένα ψηλότερο barcode που μπορεί να απαιτείται από συγκεκριμένο υλικό σαρωτή. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Γιατί αυτό το βήμα είναι σημαντικό*: Διαφορετικοί λιανοπωλητές και συσκευές σάρωσης έχουν διαφορετικούς περιορισμούς μεγέθους. Η παροχή και των δύο αναλογιών σε ένα μόνο script σας επιτρέπει να δημιουργήσετε το ακριβές στυλ που χρειάζεστε χωρίς να διπλασιάζετε κώδικα. + +## Πλήρες script – create omni directional databar και barcode image python + +Παρακάτω βρίσκεται το πλήρες, εκτελέσιμο παράδειγμα που ενσωματώνει όλα τα προηγούμενα βήματα. Αποθηκεύστε το ως `generate_databar.py` και τρέξτε το με `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Αναμενόμενο αποτέλεσμα + +Η εκτέλεση του script δημιουργεί τα παρακάτω αρχεία: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Και οι δύο εικόνες εμφανίζουν ένα έγκυρο Omni‑directional DataBar που μπορεί να σαρωθεί από τυπικό εξοπλισμό λιανικής. + +![παράδειγμα δημιουργίας omni directional databar barcode εικόνας σε Python](example_databar.png "δημιουργία omni directional databar barcode εικόνας python") + +*Η παραπάνω εικόνα είναι ένας placeholder που απεικονίζει τα δύο αποθηκευμένα αρχεία PNG.* + +## Διαχείριση κοινών προβλημάτων + +| Πρόβλημα | Αιτία | Διόρθωση | +|----------|-------|----------| +| `ImportError: No module named aspose` | Το Aspose.BarCode δεν είναι εγκατεστημένο ή είναι εγκατεστημένο σε διαφορετικό περιβάλλον. | Ενεργοποιήστε το σωστό εικονικό περιβάλλον και τρέξτε `pip install aspose-barcode`. | +| `PermissionError` when saving | Το script δεν διαθέτει δικαίωμα εγγραφής στον φάκελο προορισμού. | Επιλέξτε έναν φάκελο που έχετε δικαίωμα ή τρέξτε το script με τις κατάλληλες προνόμια. | +| Barcode does not scan | Η X‑διάσταση είναι πολύ μικρή ή η αναλογία διαστάσεων δεν είναι συμβατή με τον σαρωτή. | Αυξήστε το `x_dimension.pixels` σε 3 ή 4, και δοκιμάστε διαφορετικές τιμές `aspect_ratio` (π.χ., 20, 25). | +| Missing .NET runtime | Το Aspose.BarCode εξαρτάται από το .NET runtime στα Windows/Linux. | Εγκαταστήστε το πιο πρόσφατο .NET runtime από την ιστοσελίδα της Microsoft· η τεκμηρίωση του πακέτου παρέχει οδηγίες ανά πλατφόρμα. | + +## Επέκταση του παραδείγματος + +Μπορείτε να προσαρμόσετε το script για να δημιουργήσετε άλλες παραλλαγές DataBar (π.χ., `DATABAR_STACKED`, `DATABAR_EXPANDED`). Αντικαταστήστε τη σταθερά `EncodeTypes` αναλόγως: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Αν χρειάζεται να ενσωματώσετε το barcode σε PDF, το Aspose.PDF για Python μπορεί να εισάγει το αρχείο PNG απευθείας ή μπορείτε να χρησιμοποιήσετε τη μέθοδο `save` με `BarCodeImageFormat.Pdf`. + +## Συμπέρασμα + +Αυτό το tutorial έδειξε πώς να **create omni directional databar** και πώς να **create barcode image python** χρησιμοποιώντας το Aspose.BarCode. Τώρα έχετε ένα πλήρες, αναπαραγώσιμο script που δημιουργεί δύο αρχεία PNG με διαφορετικές αναλογίες διαστάσεων, αντιμετωπίζει κοινά προβλήματα και μπορεί να επεκταθεί σε άλλες μορφές barcode. + +Στη συνέχεια, εξερευνήστε τη δημιουργία QR codes, την προσθήκη του barcode σε τιμολόγια PDF ή την αυτοματοποίηση επεξεργασίας παρτίδων για μεγάλους καταλόγους προϊόντων. Κάθε ένα από αυτά τα θέματα βασίζεται στο ίδιο πρότυπο `BarcodeGenerator` που παρουσιάστηκε εδώ. Καλή προγραμματιστική! + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Δημιουργία εικόνας barcode – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Δημιουργία εικόνας DotCode barcode – γραμμές & στήλες (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Πώς να δημιουργήσετε εικόνα barcode και να την αποδώσετε σε Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/greek/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/greek/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..682acc72e --- /dev/null +++ b/barcode/greek/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Πώς να δημιουργήσετε γρήγορα barcode χρησιμοποιώντας Python. Μάθετε πώς + να δημιουργήσετε barcode από δεδομένα και να εξάγετε την εικόνα του barcode με μία + μόνο βιβλιοθήκη. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: el +lastmod: 2026-08-12 +og_description: Πώς να δημιουργήσετε γραμμωτό κώδικα σε Python με το Aspose.BarCode. + Ακολουθήστε αυτόν τον οδηγό για να δημιουργήσετε γραμμωτό κώδικα από δεδομένα και + να εξάγετε την εικόνα του γραμμωτού κώδικα ως PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Πώς να δημιουργήσετε γραμμωτό κώδικα σε Python – γρήγορος, αξιόπιστος οδηγός +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Πώς να δημιουργήσετε γραμμικό κώδικα σε Python – πλήρης οδηγός βήμα‑βήμα +url: /el/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να δημιουργήσετε barcode σε Python – πλήρης οδηγός βήμα‑βήμα + +Αν χρειάζεστε **πώς να δημιουργήσετε barcode** σε μια εφαρμογή Python, αυτό το tutorial σας δείχνει τον ακριβή κώδικα που χρειάζεστε. Θα μάθετε να **δημιουργείτε barcode από δεδομένα**, να προσαρμόζετε την εμφάνισή του και να **εξάγετε εικόνα barcode** ως αρχείο PNG—όλα σε λιγότερο από δέκα γραμμές κώδικα. + +Η δημιουργία ενός barcode μπορεί να φαίνεται σαν ξεχωριστό ζήτημα από την υπόλοιπη λογική της εφαρμογής σας, αλλά με μία μόνο βιβλιοθήκη μπορείτε να κρατήσετε τη διαδικασία ενσωματωμένη στον υπάρχοντα κώδικα. Στις επόμενες ενότητες θα δείτε ένα πλήρες, εκτελέσιμο παράδειγμα, θα καταλάβετε γιατί κάθε γραμμή είναι σημαντική και θα ανακαλύψετε κοινές παραλλαγές όπως η αλλαγή του πλάτους του μοντέλου ή η σχεδίαση ενός barcode μόνο με περίγραμμα. + +## Πώς να δημιουργήσετε barcode με τη βιβλιοθήκη Aspose.BarCode + +Η βιβλιοθήκη Aspose.BarCode για Python (μέσω .NET) παρέχει ένα απλό API για πολλές συμβολογίες, συμπεριλαμβανομένου του Planet barcode που χρησιμοποιείται σε αυτόν τον οδηγό. Πριν ξεκινήσετε, βεβαιωθείτε ότι έχετε εγκαταστήσει το πακέτο: + +```bash +pip install aspose-barcode +``` + +> **Pro tip:** Χρησιμοποιήστε ένα εικονικό περιβάλλον για να αποφύγετε συγκρούσεις εκδόσεων με άλλα έργα. + +### 1. Εισαγωγή των απαιτούμενων κλάσεων + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Αυτές οι εισαγωγές σας δίνουν πρόσβαση στην κλάση δημιουργού, στην απαρίθμηση των τύπων barcode και στην enum μορφής εικόνας που χρησιμοποιείται κατά την αποθήκευση του αποτελέσματος. + +### 2. Δημιουργία barcode από δεδομένα + +Το πρώτο βήμα είναι να **δημιουργήσετε barcode από δεδομένα**. Ο κατασκευαστής `BarcodeGenerator` δέχεται τη συμβολογία και τη ακατέργαστη συμβολοσειρά που θέλετε να κωδικοποιήσετε. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +Η τιμή `EncodeTypes.Planet` επιλέγει το Planet barcode, ενώ το `"123456"` είναι το φορτίο που θα εμφανιστεί στην τελική εικόνα. + +### 3. Ρύθμιση της διάστασης X (πλάτος μονάδας) + +Η διάσταση X ελέγχει το πλάτος κάθε μονάδας του barcode (η λεπτή μπάρα). Ορίζοντάς το σε 4 pixel παίρνετε μια καθαρή, ευανάγνωστη εικόνα χωρίς να αυξήσετε υπερβολικά το μέγεθος του αρχείου. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Γιατί είναι σημαντικό:** Μια μεγαλύτερη διάσταση X βελτιώνει την αξιοπιστία σάρωσης σε εκτυπωτές χαμηλής ανάλυσης, ενώ μια μικρότερη τιμή μειώνει το μέγεθος του αρχείου για χρήση στο web. + +### 4. Εξαγωγή εικόνας barcode (στυλ γεμισμένο) + +Τώρα μπορείτε να **εξάγετε εικόνα barcode** χρησιμοποιώντας τη μέθοδο `save`. Το παράδειγμα αποθηκεύει ένα αρχείο PNG, αλλά μπορείτε να επιλέξετε JPEG, BMP ή TIFF αλλάζοντας την enum `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +Το αρχείο `PlanetFilled.png` περιέχει ένα πλήρως γεμιστό Planet barcode, έτοιμο για εκτύπωση ή ενσωμάτωση σε PDF. + +### 5. Δημιουργία δεύτερου δημιουργού για barcode μόνο με περίγραμμα + +Αν χρειάζεστε μια έκδοση με περίγραμμα (κενές μπάρες), πρέπει να δημιουργήσετε νέο generator επειδή η σημαία `filled_bars` δεν μπορεί να αλλάξει μετά την αποθήκευση της εικόνας. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Εφαρμογή της ίδιας ρύθμισης διάστασης X + +Όταν δημιουργείτε δεύτερο generator, πρέπει να επαναλάβετε όλες τις οπτικές ρυθμίσεις που θέλετε να διατηρήσετε συνεπείς. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Απενεργοποίηση γεμιστών μπαρών για barcode με περίγραμμα + +Ορίζοντας `filled_bars` σε `False` λέτε στον renderer να σχεδιάσει μόνο τα περιγράμματα κάθε μονάδας, παράγοντας μια πιο ελαφριά εικόνα που μπορεί να είναι χρήσιμη για σχεδιαστικούς σκοπούς. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Εξαγωγή της εικόνας barcode με περίγραμμα + +Τέλος, **εξάγετε εικόνα barcode** ξανά, αυτή τη φορά αποθηκεύοντας την έκδοση με περίγραμμα. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Τώρα έχετε δύο αρχεία PNG: ένα με γεμάτες μπάρες (`PlanetFilled.png`) και ένα μόνο με περιγράμματα (`PlanetEmpty.png`). + +## Εξαγωγή εικόνας barcode σε άλλες μορφές (προαιρετικό) + +Η μέθοδος `save` υποστηρίζει πολλές μορφές. Για εξαγωγή ως JPEG με ποιότητα 90 %: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Αν χρειάζεστε διαφανές φόντο για χρήση στο web, επιλέξτε PNG με κανάλι αλφα: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Κοινές παραλλαγές και ειδικές περιπτώσεις + +| Σενάριο | Απαιτούμενη αλλαγή | Απόσπασμα κώδικα | +|----------|-------------------|-----------------| +| **Διαφορετική συμβολογία** (π.χ., QR) | Χρησιμοποιήστε διαφορετική τιμή `EncodeTypes` | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Προσαρμοσμένο χρώμα προσκηνίου** | Ορίστε `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Υψηλότερη ανάλυση** | Αυξήστε το DPI μέσω `image_width` και `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Μεγάλες αλφαριθμητικές συμβολοσειρές** | Βεβαιωθείτε ότι το μήκος των δεδομένων ταιριάζει με τις προδιαγραφές της συμβολογίας | Validate length before creating the generator | + +> **Προσοχή:** Η παροχή δεδομένων που υπερβαίνουν το μέγιστο μήκος για την επιλεγμένη συμβολογία προκαλεί εξαίρεση χρόνου εκτέλεσης. Πάντα επικυρώστε το μήκος της συμβολοσειράς ή πιάστε το `ArgumentException`. + +## Πλήρες, εκτελέσιμο παράδειγμα + +Παρακάτω βρίσκεται το πλήρες script που μπορείτε να αντιγράψετε‑και‑επικολλήσετε σε ένα αρχείο με όνομα `generate_planet_barcode.py`. Προσαρμόστε το `YOUR_DIRECTORY` σε έναν φάκελο που υπάρχει στο σύστημά σας. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Η εκτέλεση αυτού του script δημιουργεί δύο αρχεία PNG στον καθορισμένο φάκελο. Επαληθεύστε το αποτέλεσμα ανοίγοντας τις εικόνες με οποιονδήποτε προβολέα εικόνων· και τα δύο θα πρέπει να εμφανίζουν ένα Planet barcode που κωδικοποιεί τη συμβολοσειρά `123456`. + +## Συμπέρασμα + +Τώρα γνωρίζετε **πώς να δημιουργήσετε barcode** σε Python χρησιμοποιώντας το Aspose.BarCode, **πώς να δημιουργήσετε barcode από δεδομένα**, και **πώς να εξάγετε εικόνα barcode** τόσο σε γεμιστό όσο και σε στυλ μόνο με περίγραμμα. Το ίδιο μοτίβο ισχύει για άλλες συμβολογίες, μορφές εικόνας και οπτικές προσαρμογές, παρέχοντάς σας μια ευέλικτη βάση για οποιοδήποτε χαρακτηριστικό σχετικό με barcode στην εφαρμογή σας. + +### Επόμενα βήματα + +* Εξερευνήστε άλλες συμβολογίες όπως QR, Code‑128 ή DataMatrix αντικαθιστώντας το `EncodeTypes.Planet` με την επιθυμητή τιμή. +* Ενσωματώστε τα παραγόμενα αρχεία PNG σε PDF αναφορές χρησιμοποιώντας βιβλιοθήκες όπως `ReportLab` ή `PyPDF2`. +* Πειραματιστείτε με δυναμικές τιμές διάστασης X για να προσαρμόζετε το μέγεθος του barcode ανάλογα με την ανάλυση της οθόνης ή το DPI του εκτυπωτή. + +Καλή προγραμματιστική δουλειά, και μη διστάσετε να προσαρμόσετε το παράδειγμα ώστε να ταιριάζει στις δικές σας απαιτήσεις έργου! + +## Τι Θα Πρέπει Να Μάθετε Στη Σύντομη Μελλοντική; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικά παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετα χαρακτηριστικά του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να δημιουργήσετε εικόνα Barcode σε Java με Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Πώς να δημιουργήσετε Barcode Java – Πλήρης Οδηγός Διαμόρφωσης](/barcode/english/java/barcode-configuration/) +- [Πώς να δημιουργήσετε εικόνες barcode code128 σε Java με Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hindi/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/hindi/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..e5596b58e --- /dev/null +++ b/barcode/hindi/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-08-12 +description: बारकोड जेनरेटर उदाहरण जो दिखाता है कि सटीक पिक्सेल आकार के साथ बारकोड + कैसे बनाएं। मॉड्यूल की चौड़ाई, बार की ऊँचाई सेट करना सीखें और प्लैनेट बारकोड बनाएं। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: hi +lastmod: 2026-08-12 +og_description: बारकोड जनरेटर उदाहरण दिखाता है कि सटीक पिक्सेल आयामों के साथ बारकोड + कैसे उत्पन्न किया जाए। प्लैनेट और RM4SCC कोड्स के लिए मॉड्यूल चौड़ाई और बार की ऊँचाई + को नियंत्रित करने के लिए इस गाइड का पालन करें। +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: बारकोड जेनरेटर उदाहरण – C# में पिक्सेल आकार को अनुकूलित करें +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: बारकोड जेनरेटर उदाहरण – कस्टम पिक्सेल आकारों के लिए चरण‑दर‑चरण मार्गदर्शिका +url: /hi/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# barcode generator example – कस्टम पिक्सेल आकारों के लिए चरण‑दर‑चरण गाइड + +यदि आपको एक **barcode generator example** चाहिए जो आपको प्रत्येक पिक्सेल को नियंत्रित करने की अनुमति देता है, तो यह गाइड बिल्कुल दिखाता है कि इसे कैसे किया जाए। आप मॉड्यूल की चौड़ाई सेट करना, एक निश्चित बार ऊँचाई निर्धारित करना, और Planet तथा RM4SCC दोनों बारकोड को पूर्वानुमेय आयामों के साथ जेनरेट करना सीखेंगे। + +अधिकांश डेवलपर्स “how to generate barcode” इमेज़ों के साथ संघर्ष करते हैं जो हर स्क्रीन या प्रिंटर पर एक जैसी नहीं दिखतीं। नीचे दिए गए कोड स्निपेट्स इस समस्या को हल करते हैं, Aspose.BarCode for .NET लाइब्रेरी के पिक्सेल‑लेवल पैरामीटर को उजागर करके, ताकि आप अनुमान के बिना सुसंगत आउटपुट बना सकें। + +## What you’ll learn + +* आवश्यक NuGet पैकेज को कैसे इंस्टॉल करें। +* स्वचालित रूप से गणना की गई ऊँचाई के साथ Planet बारकोड कैसे जेनरेट करें। +* स्पष्ट 100‑पिक्सेल ऊँचाई के साथ Planet बारकोड कैसे जेनरेट करें। +* समान स्पष्ट ऊँचाई का उपयोग करके RM4SCC बारकोड कैसे जेनरेट करें। +* स्कैनिंग विश्वसनीयता के लिए **barcode pixel size** क्यों महत्वपूर्ण है। +* Planet बारकोड इमेज़ बनाते समय सामान्य समस्याओं को हल करने के टिप्स। + +आपको केवल .NET 6 या बाद का संस्करण, एक बेसिक C# डेवलपमेंट एनवायरनमेंट, और NuGet पैकेज को पुल करने के लिए इंटरनेट कनेक्शन की आवश्यकता है। + +--- + +## barcode generator example – विकास पर्यावरण सेट अप करें + +कोड लिखने से पहले, सुनिश्चित करें कि Aspose.BarCode लाइब्रेरी आपके प्रोजेक्ट में उपलब्ध है। + +### Install the Aspose.BarCode package + +अपने प्रोजेक्ट फ़ोल्डर में एक टर्मिनल खोलें और चलाएँ: + +```bash +dotnet add package Aspose.BarCode +``` + +यह कमांड **Aspose.BarCode** का नवीनतम स्थिर संस्करण आपके `csproj` में जोड़ता है। रिस्टोर समाप्त होने के बाद, आप `BarcodeGenerator` क्लास का उपयोग शुरू कर सकते हैं। + +> **Pro tip:** नवीनतम प्रदर्शन सुधार और डिफ़ॉल्ट UTF‑8 हैंडलिंग का लाभ उठाने के लिए .NET 6 या .NET 7 को टार्गेट करें। + +### Add the necessary `using` directives + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +ये नेमस्पेसेस `BarcodeGenerator` क्लास और `BarCodeImageFormat` एनेम को उजागर करते हैं, जिसका उपयोग ट्यूटोरियल में बाद में किया जाएगा। + +--- + +## How to generate barcode with custom pixel size + +निम्नलिखित तीन चरण पूरी **barcode generator example** को दर्शाते हैं। प्रत्येक चरण पिछले पर आधारित है, इसलिए आप पूरे ब्लॉक को कॉपी‑पेस्ट करके एक कंसोल ऐप में रख सकते हैं और बिना बदलाव के चला सकते हैं। + +### Step 1 – generate a Planet barcode with automatically calculated height + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Why this works:** +*`XDimension` प्रॉपर्टी एकल बारकोड मॉड्यूल (सबसे छोटा काला या सफ़ेद तत्व) की चौड़ाई निर्धारित करती है। जब आप `BarHeight` को छोड़ देते हैं, तो लाइब्रेरी एक ऐसी ऊँचाई गणना करती है जो Planet कोड के मानक अनुपात को बनाए रखती है।* + +**Expected output:** `PlanetAuto.png` नामक PNG फ़ाइल जिसमें एक साफ़ Planet बारकोड होगा। इसकी ऊँचाई 4‑पिक्सेल मॉड्यूल चौड़ाई के अनुसार अनुकूलित होती है, आमतौर पर छह‑अक्षर पेलोड के लिए लगभग 60 पिक्सेल। + +### Step 2 – generate a Planet barcode with an explicit 100‑pixel height + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Why you might need this:** +कभी‑कभी स्कैनिंग उपकरण विश्वसनीय पहचान के लिए न्यूनतम बार ऊँचाई की अपेक्षा करता है। `BarHeight.Pixels` सेट करके आप सुनिश्चित करते हैं कि हर जेनरेट की गई इमेज़ उस आवश्यकता को पूरा करे, चाहे एन्कोडेड डेटा की लंबाई कुछ भी हो। + +**Expected output:** `PlanetHeight100.png` वही डेटा दिखाता है, लेकिन बार ठीक 100 पिक्सेल ऊँचे होते हैं, जिससे आप दृश्य आकार पर पूर्ण नियंत्रण पा सकते हैं। + +### Step 3 – generate an RM4SCC barcode with the same explicit height + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Why this matters:** +`EncodeTypes.RM4SCC` एक स्टैक्ड लीनियर बारकोड है जो लॉजिस्टिक्स में उपयोग होता है। इसकी बार ऊँचाई को Planet बारकोड के साथ संरेखित करने से बैच प्रोसेसिंग सरल हो जाता है जब दोनों सिम्बोलॉजी एक ही लेबल पर दिखाई देती हैं। + +**Expected output:** `RM4SCCHeight100.png` एक बिल्कुल सही आकार का RM4SCC बारकोड दिखाता है, जो Planet कोड के लिए सेट की गई 100‑पिक्सेल ऊँचाई से मेल खाता है। + +> **Result verification:** प्रत्येक PNG को इमेज़ व्यूअर में खोलें और पुष्टि करें कि काले बार ठीक 4 पिक्सेल चौड़े और जहाँ आपने निर्दिष्ट किया है, 100 पिक्सेल ऊँचे हैं। आप फ़ाइलों को एक बारकोड स्कैनर ऐप में भी फीड कर सकते हैं यह सुनिश्चित करने के लिए कि वे “123456” को डिकोड करते हैं। + +--- + +## Understanding barcode pixel size and bar height + +### What is **barcode pixel size**? + +*Pixel size* उस भौतिक पिक्सेल संख्या को दर्शाता है जो एकल मॉड्यूल (`XDimension`) को प्रदर्शित करती है। बड़ा पिक्सेल आकार बड़ा बारकोड बनाता है, जो लो‑रेज़ोल्यूशन स्कैनर के लिए आसान हो सकता है, लेकिन लेबल की जगह अधिक लेता है। + +### How does `BarHeight` affect readability? + +`BarHeight` प्रॉपर्टी बार की लंबवत लंबाई को नियंत्रित करती है। अधिकांश 1‑D बारकोड (Planet और RM4SCC सहित) के मानक 300 dpi पर प्रिंट होने पर न्यूनतम 10 mm ऊँचाई की सिफ़ारिश करते हैं, जो लगभग 118 पिक्सेल के बराबर है। इससे कम ऊँचाई सेट करने से पढ़ने में त्रुटियाँ हो सकती हैं, विशेषकर मोबाइल कैमरों पर। + +### When should you let the library calculate height automatically? + +यदि आप केवल ऑन‑स्क्रीन डिस्प्ले के लिए बारकोड जेनरेट कर रहे हैं, तो स्वचालित गणना अनुपात को स्थिर रखती है और मैन्युअल ट्यूनिंग की आवश्यकता कम करती है। प्रिंटेड लेबल जो कड़े ISO स्पेसिफ़िकेशन को पूरा करना चाहते हैं, उनके लिए **बार ऊँचाई को स्पष्ट रूप से सेट** करना चाहिए। + +--- + +## Common pitfalls and best practices when you generate Planet barcode + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| Bars appear too thin or thick | `XDimension` को डिफ़ॉल्ट (1 pixel) पर छोड़ दिया गया है हाई‑रेज़ोल्यूशन डिस्प्ले पर | दृश्य स्पष्टता के लिए `XDimension.Pixels` को कम से कम 3‑4 सेट करें | +| Scanner cannot read the code | `BarHeight` स्कैनर की फोकल लंबाई के लिए बहुत छोटा है | अधिकांश मोबाइल स्कैनर के लिए `BarHeight.Pixels` ≥ 100 उपयोग करें | +| Image is blurry after scaling | JPEG के रूप में सेव करने से कम्प्रेशन आर्टिफैक्ट्स आते हैं | लॉसलेस आउटपुट के लिए PNG (`BarCodeImageFormat.Png`) के रूप में सेव करें | +| Unexpected barcode type | गलत `EncodeTypes` एनेम वैल्यू चुनी गई | दोबारा जाँचें कि आप Planet सिम्बोलॉजी के लिए `EncodeTypes.Planet` उपयोग कर रहे हैं | + +### Pro tip on performance + +हज़ारों बारकोड को बैच जॉब में जेनरेट करते समय, एक ही `BarcodeGenerator` इंस्टेंस को पुन: उपयोग करें और केवल `CodeText` तथा आकार पैरामीटर को सेव के बीच बदलें। यह आंतरिक रेंडरिंग ऑब्जेक्ट्स के पुनः आवंटन को रोकता है और निष्पादन समय को लगभग 30 % तक कम कर सकता है। + +--- + +## Full working example – put everything together + +एक नया कंसोल प्रोजेक्ट बनाएं (`dotnet new console -n BarcodeDemo`) और `Program.cs` की सामग्री को नीचे दिए गए कोड से बदलें: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +प्रोग्राम को `dotnet run` के साथ चलाएँ। निष्पादन के बाद आपको प्रोजेक्ट फ़ोल्डर में तीन PNG फ़ाइलें मिलेंगी, जो प्रत्येक अलग **barcode generator example** परिदृश्य को दर्शाती हैं। + +--- + +## Next steps and related topics + +* **How to generate barcode in other formats** – 2‑D जरूरतों के लिए `EncodeTypes.Code128`, `EncodeTypes.QR`, और `EncodeTypes.DataMatrix` का अन्वेषण करें। +* **Embedding barcodes in PDFs** – बारकोड को सीधे इनवॉइस टेम्पलेट पर रखने के लिए Aspose.BarCode को Aspose.PDF के साथ संयोजित करें। +* **Dynamic barcode size based on user input** – गणना करें + + +## What Should You Learn Next? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोच का पता लगा सकें। + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hindi/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/hindi/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..04be4c2cc --- /dev/null +++ b/barcode/hindi/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-08-12 +description: Python में Databar बारकोड लेआउट को जल्दी कॉन्फ़िगर करें। कॉलम, पंक्तियों + को सेट करना और बारकोड जेनरेटर लाइब्रेरी से छवियों को सहेजना सीखें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: hi +lastmod: 2026-08-12 +og_description: Python में Databar बारकोड लेआउट को कॉन्फ़िगर करके कॉलम, रो और इमेज + आउटपुट को नियंत्रित करें। तैयार‑से‑चलाने वाले समाधान के लिए इस गाइड का पालन करें। +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Python में Databar बारकोड लेआउट कॉन्फ़िगर करें – पूर्ण ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Python में Databar बारकोड लेआउट को कॉन्फ़िगर करें – चरण‑दर‑चरण गाइड +url: /hi/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में Databar बारकोड लेआउट कॉन्फ़िगर करें – चरण‑दर‑चरण गाइड + +यदि आपको **Python में Databar बारकोड लेआउट कॉन्फ़िगर** करने की आवश्यकता है, तो यह गाइड आपको पूरी प्रक्रिया के माध्यम से ले जाएगा। आप देखेंगे कि Databar Expanded Stacked बारकोड के लिए कॉलम या रो की संख्या कैसे सेट करें और बारकोड जेनरेटर लाइब्रेरी को एक ही कॉल से परिणामी इमेज कैसे सहेजें। + +जब आप बारकोड को संकरी पैकेजिंग, रसीदों या मोबाइल स्क्रीन पर एम्बेड करते हैं, तो लेआउट को नियंत्रित करना आवश्यक होता है। नीचे के सेक्शनों में हम आवश्यक इम्पोर्ट्स, दो लेआउट विकल्प (कॉलम और रो), और साफ़ PNG इमेज सहेजने के सर्वोत्तम अभ्यासों को कवर करेंगे। + +## आपको क्या चाहिए + +* Python 3.8 या उससे नया +* `aspose.barcode` (या कोई भी संगत बारकोड‑जनरेशन पैकेज) स्थापित + ```bash + pip install aspose-barcode + ``` +* PNG फ़ाइलों को संग्रहीत करने वाले फ़ोल्डर में लिखने की अनुमति + +कोई अतिरिक्त बाहरी टूल आवश्यक नहीं है—लाइब्रेरी रेंडरिंग, स्केलिंग और इमेज एन्कोडिंग को आंतरिक रूप से संभालती है। + +## Python में Databar बारकोड लेआउट कैसे कॉन्फ़िगर करें + +समाधान का मूल `BarcodeGenerator` क्लास है। यह `EncodeTypes` एन्नुम को स्वीकार करता है जो बारकोड सिम्बोलॉजी को पहचानता है—इस मामले में `EncodeTypes.DatabarExpandedStacked`। जेनरेटर बनाने के बाद आप `data_bar` पैरामीटर ऑब्जेक्ट पर `columns` या `rows` प्रॉपर्टी सेट करके लेआउट को समायोजित कर सकते हैं। + +### चरण 1: आवश्यक क्लासेस इम्पोर्ट करें + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +इन इम्पोर्ट्स से आपको जेनरेटर, Databar प्रकारों के लिए एन्नुमरेशन, और PNG इमेज फ़ॉर्मेट कॉन्स्टेंट तक पहुँच मिलती है। + +### चरण 2: Databar Expanded Stacked के लिए बारकोड जेनरेटर बनाएं + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*इस चरण का कारण?* +`EncodeTypes.DatabarExpandedStacked` लाइब्रेरी को **Databar Expanded Stacked** सिम्बोलॉजी उत्पन्न करने के लिए बताता है, जो लंबी संख्यात्मक स्ट्रिंग्स को सपोर्ट करता है जबकि कॉम्पैक्ट फुटप्रिंट रखता है। दूसरा आर्ग्यूमेंट एन्कोड करने के लिए डेटा है; यह कोई भी स्ट्रिंग हो सकती है जो Databar स्पेसिफिकेशन को पूरा करती हो। + +### चरण 3: कॉलम की संख्या सेट करें (क्षैतिज लेआउट) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** इस ऑपरेशन के लिए मुख्य वाक्यांश है। जब आप कॉलम काउंट बढ़ाते हैं, तो बारकोड क्षैतिज रूप से फैलता है, जो विस्तृत लेबल्स के लिए उपयोगी हो सकता है। लाइब्रेरी स्वचालित रूप से मॉड्यूल चौड़ाई को पुनः गणना करती है ताकि कुल आकार समान बना रहे। + +#### प्रो टिप +Databar Expanded Stacked के लिए अधिकतम कॉलम काउंट 8 है। सीमा से अधिक मान सेट करने पर इसे अधिकतम तक सीमित कर दिया जाएगा, लेकिन बेहतर है कि आप इनपुट को पहले ही वैलिडेट कर लें। + +### चरण 4: कॉलम लेआउट के साथ बारकोड इमेज सहेजें + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** वह कार्रवाई है जो रेंडर किए गए बारकोड को डिस्क पर लिखती है। PNG लॉसलेस है, जो विश्वसनीय स्कैनिंग के लिए आवश्यक तेज़ किनारों को संरक्षित रखता है। + +### चरण 5: समान बारकोड प्रकार के लिए दूसरा जेनरेटर बनाएं (रो लेआउट) + +यदि आप वर्टिकल स्टैक पसंद करते हैं, तो आप कॉलम की बजाय रो के साथ काम करेंगे। नीचे का कोड वही वैल्यू पुनः उपयोग करता है लेकिन एक नया `BarcodeGenerator` इंस्टेंस बनाता है ताकि कॉलम और रो सेटिंग्स के मिश्रण से बचा जा सके। + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### चरण 6: रो की संख्या सेट करें (ऊर्ध्वाधर लेआउट) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** बारकोड मॉड्यूल्स को ऊर्ध्वाधर रूप से व्यवस्थित करता है। तीन‑रो लेआउट प्रत्येक व्यक्तिगत स्टैक की ऊँचाई को कम करता है, जिससे बारकोड संकरी रसीदों या मोबाइल स्क्रीन के लिए उपयुक्त बनता है। + +#### किनारा मामला +यदि आप `rows` को 1 सेट करते हैं, तो लाइब्रेरी एक सिंगल‑रो Databar उत्पन्न करती है (स्टैंडर्ड Databar के बराबर)। 1 से नीचे के मानों को अनदेखा कर दिया जाता है और डिफ़ॉल्ट (1 रो) पर रीसेट कर दिया जाता है। + +### चरण 7: रो लेआउट के साथ बारकोड इमेज सहेजें + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +फिर भी, हम **save barcode image** को PNG के साथ उपयोग करते हैं ताकि आउटपुट तेज़ बना रहे। + +## पूर्ण चलाने योग्य उदाहरण + +सभी हिस्सों को एक साथ जोड़ने से आपको एक स्व-निहित स्क्रिप्ट मिलती है जिसे आप किसी भी Python प्रोजेक्ट में डाल सकते हैं। + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**अपेक्षित आउटपुट** + +स्क्रिप्ट चलाने से दो PNG फ़ाइलें बनती हैं: + +* `output/ExpandedCols4.png` – चार कॉलम में विस्तारित बारकोड +* `output/ExpandedRows3.png` – तीन रो में संकुचित बारकोड + +दोनों इमेज किसी भी इमेज व्यूअर में खोली जा सकती हैं या सीधे PDF इनवॉइस, लेबल टेम्प्लेट, या वेब पेज में इम्पोर्ट की जा सकती हैं। + +## सामान्य प्रश्न और समस्या निवारण + +| Question | Answer | +|----------|--------| +| *What if the barcode looks blurry?* | Increase the image resolution by setting `barcode_generator.parameters.image_width` and `image_height` before calling `save`. | +| *Can I use other image formats?* | Yes. Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. | +| *Is there a limit on the data length?* | Databar Expanded Stacked supports up to 74 numeric characters. Exceeding the limit raises a `ArgumentException`. | +| *How do I change the foreground color?* | Use `barcode_generator.parameters.barcode.color = Color.Blue` (import `System.Drawing.Color`). | +| *Can I combine columns and rows?* | No. The API treats columns and rows as mutually exclusive layout modes. Choose one per barcode instance. | + +## अगले कदम + +अब जब आप **Databar बारकोड लेआउट कॉन्फ़िगर** कर सकते हैं, तो इन संबंधित विषयों का अन्वेषण करें: + +* **Add text captions** – `barcode_generator.parameters.barcode.code_text` का उपयोग करके एन्कोडेड वैल्यू को इमेज के नीचे दिखाएँ। +* **Embed the barcode in a PDF** – जेनरेटेड PNG को `aspose.pdf` के साथ मिलाकर प्रिंटेबल डॉक्यूमेंट बनाएँ। +* **Dynamic sizing** – रनटाइम पर लेबल डायमेंशन के आधार पर इष्टतम कॉलम या रो काउंट की गणना करें। +* **Batch processing** – प्रोडक्ट कोड्स की CSV पर लूप चलाकर स्वचालित रूप से बारकोड इमेज की लाइब्रेरी जनरेट करें। + +विभिन्न कॉलम और रो वैल्यूज़ के साथ प्रयोग करें ताकि आप देख सकें कि वे आपके टार्गेट डिवाइसों पर स्कैन विश्वसनीयता को कैसे प्रभावित करते हैं। जितना अधिक आप टेस्ट करेंगे, उतना ही आप बारकोड आकार, पठनीयता और स्थान प्रतिबंधों के बीच के ट्रेड‑ऑफ़ को समझ पाएँगे। + +--- + +*हैप्पी कोडिंग! यदि आपको यह ट्यूटोरियल उपयोगी लगा, तो इसे टीममेट्स के साथ शेयर करें या लेआउट चुनौतियों के बारे में टिप्पणी छोड़ें।* + + +## अब आपको क्या सीखना चाहिए? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोचेज़ का अन्वेषण करने में मदद करेंगे। + +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Create barcode image c# – Configure Codablock F Rows & Columns](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [One-Dimensional Databar Barcode Height Adjustment](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hindi/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/hindi/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..9eaa033a0 --- /dev/null +++ b/barcode/hindi/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-08-12 +description: BarCodeGenerator का उपयोग करके C# में बारकोड इमेज बनाएं। जानें कैसे DataBar + जनरेट करें, बारकोड इमेज का आकार नियंत्रित करें, और कई बारकोड को कुशलतापूर्वक बनाएं। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: hi +lastmod: 2026-08-12 +og_description: BarCodeGenerator के साथ C# में बारकोड इमेज बनाएं। यह ट्यूटोरियल चरण‑दर‑चरण + दिखाता है कि कैसे DataBar कोड जेनरेट करें, बारकोड इमेज का आकार समायोजित करें, और + कई बारकोड बनाएं। +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: C# में बारकोड छवि बनाएं – पूर्ण BarCodeGenerator गाइड +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: BarCodeGenerator के साथ C# में बारकोड इमेज बनाएं +url: /hi/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में BarCodeGenerator के साथ बारकोड इमेज बनाएं + +यदि आपको .NET एप्लिकेशन में **बारकोड इमेज बनानी** है, तो यह गाइड आपको `BarCodeGenerator` क्लास का उपयोग करके ठीक‑ठीक बताता है कि कैसे करें। चाहे आप रिटेल POS सिस्टम बना रहे हों या इन्वेंटरी‑ट्रैकिंग टूल, आप DataBar प्रतीक जेनरेट करना, बारकोड इमेज का आकार नियंत्रित करना, और एक ही रन में कई बारकोड बनाना सीखेंगे। + +आप यह भी जानेंगे कि **barcode generator c#** API आपको आयाम बदलने, आउटपुट फ़ॉर्मेट बदलने, और अवैध डेटा स्ट्रिंग जैसी किनारी स्थितियों को संभालने की सुविधा कैसे देता है। ट्यूटोरियल के अंत तक आप बिना दोहराव वाले कोड लिखे **कई बारकोड बना** सकते हैं। + +## आवश्यकताएँ + +- .NET 6.0 या बाद का संस्करण स्थापित हो +- एक विकास पर्यावरण (Visual Studio, Rider, या VS Code) +- Aspose.BarCode for .NET NuGet पैकेज (या कोई भी संगत लाइब्रेरी जो `BarCodeGenerator` प्रदान करती है) + +आप पैकेज इस प्रकार जोड़ सकते हैं: + +```bash +dotnet add package Aspose.BarCode +``` + +## इस ट्यूटोरियल में क्या कवर किया गया है + +1. DataBar Omni‑directional एन्कोडिंग के लिए **barcode generator c#** इंस्टेंस सेटअप करना। +2. X‑dimension और बार ऊँचाई बदलकर **barcode image size** को समायोजित करना। +3. विभिन्न ऊँचाइयों के साथ **multiple barcodes** बनाने के लिए लूप का उपयोग करना। +4. इमेज को PNG फ़ाइलों के रूप में सहेजना और आउटपुट की पुष्टि करना। + +सभी कोड स्निपेट पूर्ण हैं और नई कंसोल प्रोजेक्ट में कॉपी‑पेस्ट करने के लिए तैयार हैं। + +![Create barcode image example](barcode-example.png){alt="बारकोड इमेज उदाहरण बनाएं"} + +## चरण 1: जेनरेटर को इनिशियलाइज़ करें – बारकोड इमेज की बुनियादी बातें + +पहला कदम है इच्छित सिम्बोलॉजी के साथ `BarCodeGenerator` को इंस्टैंसिएट करना। DataBar Omni‑directional प्रतीक के लिए आप `EncodeTypes.DatabarOmniDirectional` का उपयोग करते हैं। + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**यह क्यों महत्वपूर्ण है:** जेनरेटर को इंस्टैंसिएट करने से एन्कोडिंग नियम और डेटा पेलोड निर्धारित होते हैं। यदि आप सही `EncodeTypes` मान को छोड़ देते हैं, तो लाइब्रेरी एक असमर्थित बारकोड उत्पन्न करेगी या अपवाद फेंकेगी। + +## चरण 2: X‑dimension और बार ऊँचाई कॉन्फ़िगर करें – बारकोड इमेज का आकार नियंत्रित करें + +बारकोड का दृश्य आकार दो पैरामीटर द्वारा निर्धारित होता है: + +| पैरामीटर | यह क्या नियंत्रित करता है | सामान्य रेंज | +|-----------|--------------------------|---------------| +| `x_dimension.pixels` | सबसे छोटे मॉड्यूल (डॉट) की चौड़ाई | 1 – 4 px | +| `bar_height.pixels` | ऊर्ध्वाधर बार की ऊँचाई | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**प्रो टिप:** छोटा X‑dimension उच्च‑रिज़ॉल्यूशन इमेज देता है लेकिन कम‑गुणवत्ता वाले प्रिंटर पर स्कैन करना कठिन हो सकता है। अपने लक्ष्य स्कैनिंग उपकरण के आधार पर मान को समायोजित करें। + +## चरण 3: पहला बारकोड सहेजें – 30 px ऊँचाई के लिए बारकोड इमेज बनाएं + +अब आप इमेज जेनरेट कर सकते हैं और उसे डिस्क पर लिख सकते हैं। `Save` मेथड एक फ़ाइल पाथ और इमेज फ़ॉर्मेट एन्‍उम स्वीकार करता है। + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**अपेक्षित परिणाम:** `C:\Barcodes` में `Databar30.png` नाम की PNG फ़ाइल दिखाई देती है। फ़ाइल खोलने पर एक स्पष्ट, उच्च‑कॉन्ट्रास्ट पैटर्न वाला DataBar Omni‑directional प्रतीक दिखता है। + +## चरण 4: ऊँचाई बदलें और अतिरिक्त इमेज जेनरेट करें – कई बारकोड बनाएं + +विभिन्न आयामों के साथ **multiple barcodes** बनाने के लिए आपको केवल `BarHeight` प्रॉपर्टी को बदलना है और फिर `Save` को फिर से कॉल करना है। इससे जेनरेटर को पुनः‑इंस्टैंसिएट करने से बचा जाता है, जो मेमोरी और CPU समय बचाता है। + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**यह क्यों काम करता है:** `BarCodeGenerator` ऑब्जेक्ट सभी कॉन्फ़िगरेशन स्टेट को रखता है। एक प्रॉपर्टी बदलने से अगली `Save` कॉल के लिए रेंडरिंग इंजन अपडेट हो जाता है, जिससे आप **multiple barcodes** को प्रभावी ढंग से बना सकते हैं। + +## चरण 5: उन्नत – कस्टम डेटा के साथ DataBar कैसे जेनरेट करें + +उपरोक्त उदाहरण एक स्थिर GS1 पेलोड का उपयोग करता है। वास्तविक दुनिया के परिदृश्यों में अक्सर आपको परिवर्तनीय प्रोडक्ट आइडेंटिफ़ायर एम्बेड करने की आवश्यकता होती है। लाइब्रेरी कोई भी स्ट्रिंग स्वीकार करती है जो DataBar स्पेसिफिकेशन से मेल खाती हो। + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**मुख्य बिंदु:** `generator.CodeText` सेट करने से ऑब्जेक्ट को पुनः‑निर्माण किए बिना एन्कोडेड डेटा अपडेट हो जाता है। बड़े डेटा सेट को संभालते समय यह अनुशंसित **how to generate databar** पैटर्न है। + +## चरण 6: सत्यापित करें और समस्या निवारण करें – सही बारकोड इमेज आकार सुनिश्चित करना + +इमेज जेनरेट करने के बाद, आप प्रोग्रामेटिक रूप से यह पुष्टि करना चाह सकते हैं कि आयाम आपकी अपेक्षाओं से मेल खाते हैं। `System.Drawing` की `Image` क्लास फ़ाइल को पढ़ सकती है और उसका आकार रिपोर्ट कर सकती है। + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +यदि ऊँचाई आपके द्वारा सेट किए गए मान को नहीं दर्शाती है, तो जांचें: + +- **X‑dimension**: बहुत छोटा मान रेंडरर को ऊँचाई को राउंड करने का कारण बन सकता है। +- **Image format**: कुछ फ़ॉर्मेट (जैसे JPEG) संपीड़न लागू करते हैं जो सहेजने पर पिक्सेल आयाम बदल सकते हैं। PNG सटीक आयाम बनाए रखता है। + +## चरण 7: बारकोड इमेज आकार और प्रदर्शन के लिए सर्वोत्तम प्रथाएँ + +| सिफ़ारिश | कारण | +|----------------|--------| +| `x_dimension.pixels` को अधिकांश स्कैनरों के लिए 2 – 3 px के बीच रखें। | पढ़ने की आसानी और फ़ाइल आकार के बीच संतुलन बनाता है। | +| जब इमेज प्रिंट की जाएगी तो लॉसलेस आउटपुट के लिए PNG का उपयोग करें। | सटीक आयाम और तेज़ किनारे सुनिश्चित करता है। | +| कई बारकोड जेनरेट करते समय एक ही `BarCodeGenerator` इंस्टेंस को पुनः उपयोग करें। | ऑब्जेक्ट अलोकेशन ओवरहेड को कम करता है। | +| `CodeText` को असाइन करने से पहले इनपुट स्ट्रिंग को GS1 मानक के विरुद्ध वैधता जांचें। | रनटाइम अपवाद और अमान्य स्कैन को रोकता है। | +| जेनरेट की गई इमेज को स्पष्ट नामकरण नियम (जैसे `Databar_{GTIN}.png`) के साथ एक समर्पित फ़ोल्डर में रखें। | डाउनस्ट्रीम प्रोसेसिंग और ऑडिट ट्रेल को सरल बनाता है। | + +## पूर्ण कार्यशील उदाहरण + +नीचे वह पूर्ण प्रोग्राम है जो इनिशियलाइज़ेशन से लेकर सत्यापन तक सभी चरणों को सम्मिलित करता है। कोड को नई कंसोल प्रोजेक्ट में कॉपी करें और चलाएँ। + + + +## अब आपको आगे क्या सीखना चाहिए? + +- [बारकोड इमेज जेनरेट करें – GS1 कूपन UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode बारकोड इमेज बनाएं – पंक्तियाँ और कॉलम (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Aspose.BarCode for .NET का उपयोग करके ITF-14 के लिए बारकोड क्वाइट ज़ोन कैसे बनाएं](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hindi/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/hindi/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..43d5f1e63 --- /dev/null +++ b/barcode/hindi/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-12 +description: Python के साथ ओम्नि‑डायरेक्शनल डेटाबार बनाएं और Aspose.BarCode का उपयोग + करके Python में बारकोड इमेज बनाना सीखें। पूर्ण समाधान के लिए चरण‑दर‑चरण गाइड का + पालन करें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: hi +lastmod: 2026-08-12 +og_description: Python के साथ ओम्नी‑डायरेक्शनल डेटाबार बनाएं और मिनटों में एक बारकोड + इमेज जनरेट करें। यह ट्यूटोरियल एक पूर्ण, चलाने योग्य उदाहरण दिखाता है। +og_image_alt: example of create omni directional databar barcode image in Python +og_title: ओम्नि-डायरेक्शनल डेटाबार बनाएं – पूर्ण पायथन गाइड +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Python में सर्वदिशात्मक डेटाबार और बारकोड छवि बनाएं +url: /hi/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में Omni Directional DataBar और बारकोड इमेज बनाएं + +यदि आपको **create omni directional databar** Python प्रोजेक्ट में बनाना है, तो यह गाइड आपको यह करने का तरीका दिखाएगा और साथ ही Aspose.BarCode लाइब्रेरी का उपयोग करके **create barcode image python** बनाने का तरीका भी बताएगा। आपको एक तैयार‑से‑चलाने योग्य स्क्रिप्ट मिलेगी जो विभिन्न aspect ratios के साथ दो PNG फ़ाइलें उत्पन्न करती है। + +Omni‑directional स्पेसिफिकेशन का पालन करने वाला DataBar उत्पन्न करना रिटेल और लॉजिस्टिक्स एप्लिकेशन्स के लिए एक सामान्य आवश्यकता है। यह ट्यूटोरियल इंस्टॉलेशन, X‑dimension की कॉन्फ़िगरेशन, aspect ratio के समायोजन, और अंतिम इमेज को सेव करने को कवर करता है। कोई बाहरी सेवाएँ आवश्यक नहीं हैं; सब कुछ स्थानीय रूप से चलता है। + +## आपको क्या चाहिए + +* आपके मशीन पर स्थापित Python 3.8 या उससे नया संस्करण। +* टर्मिनल या कमांड प्रॉम्प्ट तक पहुंच। +* उस फ़ोल्डर में लिखने की अनुमति जहाँ बारकोड इमेज सेव की जाएँगी। + +एकमात्र थर्ड‑पार्टी डिपेंडेंसी **Aspose.BarCode for Python via .NET** है, जो बॉक्स से ही Omni‑directional DataBar प्रकार का समर्थन करती है। + +## चरण 1: Aspose.BarCode for Python स्थापित करें + +Aspose.BarCode उदाहरण कोड में उपयोग की गई `BarcodeGenerator` क्लास प्रदान करता है। पैकेज को `pip` के साथ स्थापित करें: + +```bash +pip install aspose-barcode +``` + +पैकेज में आवश्यक .NET रनटाइम बाइंडिंग्स शामिल हैं, इसलिए आपको अलग से .NET SDK स्थापित करने की जरूरत नहीं है। + +## चरण 2: लाइब्रेरी इम्पोर्ट करें और जनरेटर बनाएं + +स्क्रिप्ट की पहली पंक्ति एक stacked Omni‑directional DataBar के लिए जनरेटर बनाती है। GTIN‑14 मान `(01)12345678901231` को नमूना डेटा के रूप में उपयोग किया गया है। + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*इस चरण का महत्व*: `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` कॉन्स्टेंट लाइब्रेरी को बताता है कि मान को Omni‑directional DataBar के रूप में एन्कोड किया जाए, जो कई point‑of‑sale स्कैनरों के लिए आवश्यक फॉर्मेट है। + +## चरण 3: X‑dimension सेट करें (मॉड्यूल चौड़ाई) + +X‑dimension सबसे छोटे बार मॉड्यूल की चौड़ाई निर्धारित करता है। `2` पिक्सेल का मान स्पष्ट, पठनीय बारकोड बनाता है बिना अत्यधिक फ़ाइल आकार के। + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*इस चरण का महत्व*: X‑dimension को समायोजित करने से आप पठनीयता और इमेज आकार के बीच संतुलन बना सकते हैं। बहुत छोटा X‑dimension कम‑रिज़ॉल्यूशन प्रिंटरों पर खराब रेंडर हो सकता है। + +## चरण 4: aspect ratio कॉन्फ़िगर करें और पहली इमेज सेव करें + +aspect ratio DataBar की कुल ऊँचाई को उसकी चौड़ाई के सापेक्ष प्रभावित करता है। `15` का aspect ratio एक कॉम्पैक्ट विज़ुअल स्टाइल बनाता है। + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Pro tip**: आउटपुट पाथ बनाने के लिए `pathlib.Path` का उपयोग करें, जो स्वचालित रूप से गायब डायरेक्टरीज़ बना देता है। + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## चरण 5: दूसरे विज़ुअल स्टाइल के लिए aspect ratio बदलें और एक और इमेज सेव करें + +aspect ratio को `30` करने से एक ऊँचा बारकोड बनता है जो कुछ विशेष स्कैनर हार्डवेयर द्वारा आवश्यक हो सकता है। + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*इस चरण का महत्व*: विभिन्न रिटेलर्स और स्कैनिंग डिवाइसों की आकार संबंधी अलग-अलग सीमाएँ होती हैं। एक ही स्क्रिप्ट में दोनों aspect ratios प्रदान करने से आप बिना कोड दोहराए आवश्यक स्टाइल जनरेट कर सकते हैं। + +## पूर्ण स्क्रिप्ट – create omni directional databar और barcode image python + +नीचे पूरा, चलाने योग्य उदाहरण है जो सभी पिछले चरणों को सम्मिलित करता है। इसे `generate_databar.py` के रूप में सेव करें और `python generate_databar.py` के साथ चलाएँ। + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### अपेक्षित आउटपुट + +स्क्रिप्ट चलाने से निम्नलिखित फ़ाइलें बनती हैं: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +दोनों इमेज एक वैध Omni‑directional DataBar दिखाती हैं जिसे मानक रिटेल उपकरण द्वारा स्कैन किया जा सकता है। + +![Python में create omni directional databar barcode image का उदाहरण](example_databar.png "Python में create omni directional databar barcode image") + +*ऊपर की इमेज एक प्लेसहोल्डर है जो दो सेव की गई PNG फ़ाइलों को दर्शाती है।* + +## सामान्य समस्याओं का समाधान + +| समस्या | कारण | समाधान | +|-------|--------|-----| +| `ImportError: No module named aspose` | Aspose.BarCode स्थापित नहीं है या अलग पर्यावरण में स्थापित है। | सही वर्चुअल एनवायरनमेंट सक्रिय करें और `pip install aspose-barcode` चलाएँ। | +| `PermissionError` when saving | स्क्रिप्ट के पास लक्ष्य फ़ोल्डर के लिए लिखने की अनुमति नहीं है। | ऐसा डायरेक्टरी चुनें जिसका आप मालिक हों या स्क्रिप्ट को उपयुक्त विशेषाधिकारों के साथ चलाएँ। | +| बारकोड स्कैन नहीं हो रहा है | X‑dimension बहुत कम है या aspect ratio स्कैनर के साथ असंगत है। | `x_dimension.pixels` को 3 या 4 तक बढ़ाएँ, और विभिन्न `aspect_ratio` मानों (जैसे 20, 25) का परीक्षण करें। | +| .NET रनटाइम अनुपलब्ध | Aspose.BarCode को Windows/Linux पर .NET रनटाइम की आवश्यकता होती है। | Microsoft की साइट से नवीनतम .NET रनटाइम स्थापित करें; पैकेज दस्तावेज़ प्लेटफ़ॉर्म‑विशिष्ट मार्गदर्शन प्रदान करता है। | + +## उदाहरण का विस्तार + +आप स्क्रिप्ट को अन्य DataBar वैरिएंट्स (जैसे `DATABAR_STACKED`, `DATABAR_EXPANDED`) उत्पन्न करने के लिए अनुकूलित कर सकते हैं। `EncodeTypes` कॉन्स्टेंट को उसी अनुसार बदलें: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +यदि आपको बारकोड को PDF में एम्बेड करना है, तो Aspose.PDF for Python PNG फ़ाइल को सीधे इम्पोर्ट कर सकता है या आप `save` मेथड को `BarCodeImageFormat.Pdf` के साथ उपयोग कर सकते हैं। + +## निष्कर्ष + +इस ट्यूटोरियल ने Aspose.BarCode का उपयोग करके **create omni directional databar** और **create barcode image python** कैसे बनाएं, दिखाया। अब आपके पास एक पूर्ण, पुनरुत्पादनीय स्क्रिप्ट है जो विभिन्न aspect ratios के साथ दो PNG फ़ाइलें उत्पन्न करती है, सामान्य समस्याओं को संभालती है, और अन्य बारकोड फ़ॉर्मेट्स के लिए विस्तारित की जा सकती है। + +अब, QR कोड जनरेट करना, बारकोड को PDF इनवॉइस में जोड़ना, या बड़े प्रोडक्ट कैटलॉग के लिए बैच प्रोसेसिंग को ऑटोमेट करना एक्सप्लोर करें। इन सभी विषयों का आधार यहाँ प्रदर्शित `BarcodeGenerator` पैटर्न है। कोडिंग का आनंद लें! + +## अगला आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स इस गाइड में दिखाए गए तकनीकों पर आधारित निकट-संबंधित विषयों को कवर करते हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में निपुण बनने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर करने में मदद करती हैं। + +- [बारकोड इमेज जनरेट करें – GS1 कूपन UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode बारकोड इमेज बनाएं – पंक्तियाँ और कॉलम (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [बारकोड इमेज कैसे बनाएं और Java में रेंडर करें](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hindi/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/hindi/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..1c52a724c --- /dev/null +++ b/barcode/hindi/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: Python का उपयोग करके बारकोड जल्दी कैसे बनाएं। डेटा से बारकोड बनाना सीखें + और एक ही लाइब्रेरी के साथ बारकोड इमेज निर्यात करें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: hi +lastmod: 2026-08-12 +og_description: Python में Aspose.BarCode के साथ बारकोड कैसे बनाएं। डेटा से बारकोड + बनाकर और बारकोड छवि को PNG के रूप में निर्यात करने के लिए इस गाइड का पालन करें। +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Python में बारकोड कैसे बनाएं – तेज़, विश्वसनीय गाइड +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Python में बारकोड कैसे बनाएं – पूर्ण चरण‑दर‑चरण मार्गदर्शिका +url: /hi/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में बारकोड कैसे जनरेट करें – पूर्ण चरण‑दर‑चरण गाइड + +यदि आपको **बारकोड कैसे जनरेट करें** Python एप्लिकेशन में चाहिए, तो यह ट्यूटोरियल आपको आवश्यक सटीक कोड दिखाता है। आप सीखेंगे **डेटा से बारकोड बनाना**, उसकी उपस्थिति समायोजित करना, और **बारकोड इमेज एक्सपोर्ट करना** PNG फ़ाइल के रूप में—सभी दस लाइनों से कम कोड में। + +बारकोड जनरेट करना आपके बाकी बिज़नेस लॉजिक से अलग लग सकता है, लेकिन एक ही लाइब्रेरी के साथ आप इस प्रक्रिया को अपने मौजूदा कोड बेस के साथ सहजता से जोड़ सकते हैं। आगे के सेक्शन में आप एक पूर्ण, रन‑एबल उदाहरण देखेंगे, समझेंगे कि प्रत्येक लाइन क्यों महत्वपूर्ण है, और सामान्य वैरिएशन जैसे मॉड्यूल चौड़ाई बदलना या केवल आउटलाइन वाला बारकोड बनाना भी जानेंगे। + +## Aspose.BarCode लाइब्रेरी के साथ बारकोड कैसे जनरेट करें + +Python (via .NET) के लिए Aspose.BarCode लाइब्रेरी कई सिम्बोलॉजीज के लिए एक सीधा API प्रदान करती है, जिसमें इस गाइड में उपयोग किया गया Planet बारकोड भी शामिल है। शुरू करने से पहले सुनिश्चित करें कि पैकेज इंस्टॉल हो: + +```bash +pip install aspose-barcode +``` + +> **Pro tip:** अन्य प्रोजेक्ट्स के साथ संस्करण टकराव से बचने के लिए एक वर्चुअल एनवायरनमेंट का उपयोग करें। + +### 1. आवश्यक क्लासेज़ इम्पोर्ट करें + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +इन इम्पोर्ट्स से आपको जेनरेटर क्लास, बारकोड टाइप्स की एनेमरेशन, और इमेज सेव करते समय उपयोग होने वाले इमेज फ़ॉर्मेट एनेम तक पहुँच मिलती है। + +### 2. डेटा से बारकोड बनाएं + +पहला कदम **डेटा से बारकोड बनाना** है। `BarcodeGenerator` कंस्ट्रक्टर सिम्बोलॉजी और वह रॉ स्ट्रिंग लेता है जिसे आप एन्कोड करना चाहते हैं। + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +`EncodeTypes.Planet` वैल्यू Planet बारकोड चुनती है, जबकि `"123456"` वह पेलोड है जो अंतिम इमेज में दिखेगा। + +### 3. X‑डायमेंशन (मॉड्यूल चौड़ाई) समायोजित करें + +X‑डायमेंशन प्रत्येक बारकोड मॉड्यूल (पतली बार) की चौड़ाई नियंत्रित करता है। इसे 4 पिक्सेल पर सेट करने से इमेज स्पष्ट और पढ़ने योग्य बनती है, बिना फ़ाइल को बहुत बड़ा किए। + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Why this matters:** बड़ी X‑डायमेंशन कम‑रिज़ॉल्यूशन प्रिंटरों पर स्कैन विश्वसनीयता बढ़ाती है, जबकि छोटी वैल्यू वेब उपयोग के लिए फ़ाइल आकार घटाती है। + +### 4. बारकोड इमेज एक्सपोर्ट करें (filled style) + +अब आप `save` मेथड का उपयोग करके **बारकोड इमेज एक्सपोर्ट** कर सकते हैं। उदाहरण PNG फ़ाइल सेव करता है, लेकिन आप `BarCodeImageFormat` एनेम को बदलकर JPEG, BMP, या TIFF भी चुन सकते हैं। + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +फ़ाइल `PlanetFilled.png` में पूरी तरह से भरा हुआ Planet बारकोड होता है, जिसे प्रिंट या PDF में एम्बेड किया जा सकता है। + +### 5. आउटलाइन‑only बारकोड के लिए दूसरा जेनरेटर बनाएं + +यदि आपको आउटलाइन संस्करण (खाली बार) चाहिए, तो आपको नया जेनरेटर बनाना होगा क्योंकि `filled_bars` फ़्लैग इमेज सेव होने के बाद टॉगल नहीं किया जा सकता। + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. वही X‑डायमेंशन सेटिंग लागू करें + +जब आप दूसरा जेनरेटर बनाते हैं, तो आपको सभी विज़ुअल सेटिंग्स को दोहराना होगा जिन्हें आप लगातार रखना चाहते हैं। + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. आउटलाइन बारकोड के लिए filled bars को डिसेबल करें + +`filled_bars` को `False` सेट करने से रेंडरर प्रत्येक मॉड्यूल की केवल आउटलाइन ड्रॉ करता है, जिससे एक हल्की इमेज बनती है जो डिज़ाइन उद्देश्यों के लिए उपयोगी हो सकती है। + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. आउटलाइन बारकोड इमेज एक्सपोर्ट करें + +अंत में, **बारकोड इमेज एक्सपोर्ट** फिर से करें, इस बार आउटलाइन संस्करण को सेव करें। + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +अब आपके पास दो PNG फ़ाइलें हैं: एक सॉलिड बार्स (`PlanetFilled.png`) के साथ और एक केवल आउटलाइन (`PlanetEmpty.png`) के साथ। + +## अन्य फ़ॉर्मेट में बारकोड इमेज एक्सपोर्ट करें (वैकल्पिक) + +`save` मेथड कई फ़ॉर्मेट सपोर्ट करता है। 90 % क्वालिटी के साथ JPEG में एक्सपोर्ट करने के लिए: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +यदि आपको वेब उपयोग के लिए ट्रांसपेरेंट बैकग्राउंड चाहिए, तो अल्फा चैनल के साथ PNG चुनें: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## सामान्य वैरिएशन और एज केस + +| परिदृश्य | आवश्यक परिवर्तन | कोड स्निपेट | +|----------|----------------|--------------| +| **विभिन्न सिम्बोलॉजी** (जैसे, QR) | अलग `EncodeTypes` वैल्यू उपयोग करें | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **कस्टम फ़ोरग्राउंड रंग** | `fore_color` सेट करें | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **उच्च रेज़ॉल्यूशन** | `image_width` और `image_height` के माध्यम से DPI बढ़ाएँ | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **बड़ी डेटा स्ट्रिंग्स** | सुनिश्चित करें कि डेटा लंबाई सिम्बोलॉजी स्पेक के अनुरूप है | जनरेटर बनाने से पहले लंबाई वैलिडेट करें | + +> **Watch out for:** चुनी गई सिम्बोलॉजी के अधिकतम लंबाई से अधिक डेटा देने पर रन‑टाइम एक्सेप्शन उठता है। हमेशा स्ट्रिंग लंबाई वैलिडेट करें या `ArgumentException` को कैच करें। + +## पूर्ण, रन‑एबल उदाहरण + +नीचे पूरा स्क्रिप्ट है जिसे आप `generate_planet_barcode.py` नाम की फ़ाइल में कॉपी‑पेस्ट कर सकते हैं। `YOUR_DIRECTORY` को अपने मशीन पर मौजूद फ़ोल्डर से बदलें। + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +इस स्क्रिप्ट को चलाने पर निर्दिष्ट डायरेक्टरी में दो PNG फ़ाइलें बनेंगी। आउटपुट को किसी भी इमेज व्यूअर में खोलकर सत्यापित करें; दोनों में स्ट्रिंग `123456` को एन्कोड करने वाला Planet बारकोड दिखना चाहिए। + +## निष्कर्ष + +अब आप Python में Aspose.BarCode का उपयोग करके **बारकोड कैसे जनरेट करें**, **डेटा से बारकोड बनाना**, और **बारकोड इमेज एक्सपोर्ट करना** दोनों फ़िल्ड और आउटलाइन स्टाइल में जानते हैं। वही पैटर्न अन्य सिम्बोलॉजीज, इमेज फ़ॉर्मेट, और विज़ुअल कस्टमाइज़ेशन पर भी लागू होता है, जिससे आपके एप्लिकेशन में किसी भी बारकोड‑संबंधित फीचर के लिए एक लचीला आधार मिलता है। + +### अगले कदम + +* `EncodeTypes.Planet` को इच्छित वैल्यू से बदलकर QR, Code‑128, या DataMatrix जैसी अन्य सिम्बोलॉजीज एक्सप्लोर करें। +* `ReportLab` या `PyPDF2` जैसी लाइब्रेरीज़ का उपयोग करके जेनरेटेड PNG फ़ाइलों को PDF रिपोर्ट में इंटीग्रेट करें। +* स्क्रीन रिज़ॉल्यूशन या प्रिंटर DPI के आधार पर बारकोड आकार को अनुकूलित करने के लिए डायनामिक X‑डायमेंशन वैल्यूज़ के साथ प्रयोग करें। + +हैप्पी कोडिंग, और अपने प्रोजेक्ट की आवश्यकताओं के अनुसार उदाहरण को अनुकूलित करने में संकोच न करें! + +## आप आगे क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक रिसोर्स में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फ़ीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ का अन्वेषण कर सकें। + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hongkong/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/hongkong/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..2bf426c7f --- /dev/null +++ b/barcode/hongkong/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-08-12 +description: 條碼產生器範例,示範如何以精確的像素尺寸產生條碼。學習設定模組寬度、條碼高度,並建立 Planet 條碼。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: zh-hant +lastmod: 2026-08-12 +og_description: 條碼產生器範例示範如何以精確的像素尺寸產生條碼。請遵循本指南,控制 Planet 與 RM4SCC 代碼的模組寬度與條碼高度。 +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: 條碼產生器範例 – 在 C# 中自訂像素大小 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: 條碼產生器範例 – 自訂像素尺寸的逐步指南 +url: /zh-hant/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 條碼產生器範例 – 自訂像素尺寸的逐步指南 + +如果你需要一個 **條碼產生器範例**,讓你能夠控制每一個像素,這份指南會一步步說明如何做到。你將學會設定模組寬度、定義固定條高,並產生 Planet 與 RM4SCC 條碼,確保尺寸可預測。 + +大多數開發者在「如何產生條碼」圖像時,會遇到在不同螢幕或印表機上顯示不一致的問題。以下程式碼片段透過公開 Aspose.BarCode for .NET 函式庫的像素層級參數,解決了這個問題,讓你不必猜測即可產生一致的輸出。 + +## 你將學到 + +* 如何安裝所需的 NuGet 套件。 +* 如何產生自動計算高度的 Planet 條碼。 +* 如何產生高度明確為 100 像素的 Planet 條碼。 +* 如何使用相同的明確高度產生 RM4SCC 條碼。 +* 為什麼 **條碼像素尺寸** 會影響掃描可靠性。 +* 產生 Planet 條碼圖像時常見問題的除錯技巧。 + +你只需要 .NET 6 或更新版本、基本的 C# 開發環境,以及下載 NuGet 套件的網路連線。 + +--- + +## 條碼產生器範例 – 建置開發環境 + +在撰寫任何程式碼之前,請先確保 Aspose.BarCode 函式庫已加入你的專案。 + +### 安裝 Aspose.BarCode 套件 + +在專案資料夾的終端機中執行: + +```bash +dotnet add package Aspose.BarCode +``` + +此指令會將最新的穩定版 **Aspose.BarCode** 加入你的 `csproj`。還原完成後,即可開始使用 `BarcodeGenerator` 類別。 + +> **專業提示:** 目標設定為 .NET 6 或 .NET 7,可享受最新的效能提升與預設 UTF‑8 處理。 + +### 加入必要的 `using` 指令 + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +這些命名空間會公開稍後教學中使用的 `BarcodeGenerator` 類別與 `BarCodeImageFormat` 列舉。 + +--- + +## 如何產生自訂像素尺寸的條碼 + +以下三個步驟示範完整的 **條碼產生器範例**。每一步都以先前的結果為基礎,你可以直接將整段程式碼貼到 Console 應用程式中執行,無需修改。 + +### 步驟 1 – 產生自動計算高度的 Planet 條碼 + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**為什麼這樣可行:** +`XDimension` 屬性定義單一條碼模組(最小的黑白單元)的寬度。當你省略 `BarHeight` 時,函式庫會自動計算一個保持 Planet 代碼標準長寬比的高度。 + +**預期輸出:** 產生名為 `PlanetAuto.png` 的 PNG 檔案,內含乾淨的 Planet 條碼。其高度會根據 4 像素的模組寬度自動調整,通常約為 60 像素(六字元資料)。 + +### 步驟 2 – 產生高度明確為 100 像素的 Planet 條碼 + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**為什麼可能需要這樣做:** +某些掃描設備要求最小條高才能可靠偵測。透過設定 `BarHeight.Pixels`,你可以保證每張產生的圖像皆符合此需求,無論編碼資料長度為何。 + +**預期輸出:** `PlanetHeight100.png` 與前一步的資料相同,但條碼高度正好為 100 像素,讓你完全掌控視覺大小。 + +### 步驟 3 – 產生相同高度的 RM4SCC 條碼 + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**為什麼重要:** +`EncodeTypes.RM4SCC` 是物流領域常用的堆疊線性條碼。將其條高與 Planet 條碼對齊,可在同一標籤上同時出現兩種符號時,簡化批次處理流程。 + +**預期輸出:** `RM4SCCHeight100.png` 顯示尺寸恰當的 RM4SCC 條碼,條高與 Planet 條碼設定的 100 像素相同。 + +> **結果驗證:** 用圖像檢視器開啟每個 PNG,確認黑條寬度正好為 4 像素,且在你指定的情況下高度為 100 像素。亦可將檔案匯入條碼掃描應用程式,確認解碼結果為「123456」。 + +--- + +## 了解條碼像素尺寸與條高 + +### 什麼是 **條碼像素尺寸**? + +*Pixel size*(像素尺寸)指的是螢幕或印表機上,用來表示單一模組 (`XDimension`) 的實際像素數量。較大的像素尺寸會產生較大的條碼,對低解析度掃描器較友善,但會佔用更多標籤空間。 + +### `BarHeight` 如何影響可讀性? + +`BarHeight` 屬性控制條碼的垂直長度。大多數 1‑D 條碼(包括 Planet 與 RM4SCC)的標準建議在 300 dpi 印刷時,最小高度為 10 mm,約等於 118 像素。低於此高度可能導致讀取錯誤,尤其在手機相機掃描時更為明顯。 + +### 何時讓函式庫自動計算高度? + +如果條碼僅用於螢幕顯示,自動計算可保持長寬比一致,且減少手動調整的工作。若是必須符合嚴格 ISO 規範的印刷標籤,則應 **明確設定條高**。 + +--- + +## 產生 Planet 條碼時的常見陷阱與最佳實踐 + +| 陷阱 | 為什麼會發生 | 解決方式 | +|------|--------------|----------| +| 條太細或太粗 | 高解析度螢幕上 `XDimension` 預設為 1 像素 | 將 `XDimension.Pixels` 設為至少 3‑4,以提升可視性 | +| 掃描器讀不到碼 | `BarHeight` 對掃描器焦距太小 | 大多數行動掃描器使用 `BarHeight.Pixels` ≥ 100 | +| 圖片縮放後模糊 | 以 JPEG 儲存產生壓縮雜訊 | 使用 PNG (`BarCodeImageFormat.Png`) 以獲得無損輸出 | +| 條碼類型不符預期 | 使用錯誤的 `EncodeTypes` 列舉值 | 再次確認使用 `EncodeTypes.Planet` 產生 Planet 符號 | + +### 專業提示:效能最佳化 + +在批次產生上千條條碼時,請重複使用同一個 `BarcodeGenerator` 實例,僅在每次儲存前變更 `CodeText` 與尺寸參數。這樣可避免重複分配內部渲染物件,執行時間最高可縮短約 30 %。 + +--- + +## 完整範例 – 整合所有步驟 + +建立新的 Console 專案(`dotnet new console -n BarcodeDemo`),然後將 `Program.cs` 內容取代為下列程式碼: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +使用 `dotnet run` 執行程式。執行完畢後,你會在專案資料夾中看到三個 PNG 檔案,分別示範不同的 **條碼產生器範例** 情境。 + +--- + +## 往後的學習方向與相關主題 + +* **如何產生其他格式的條碼** – 探索 `EncodeTypes.Code128`、`EncodeTypes.QR` 與 `EncodeTypes.DataMatrix` 以滿足 2‑D 需求。 +* **在 PDF 中嵌入條碼** – 結合 Aspose.BarCode 與 Aspose.PDF,直接在發票範本上放置條碼。 +* **根據使用者輸入動態調整條碼尺寸** – 計算 + +## 接下來該學什麼? + +以下教學與本指南緊密相關,能進一步深化你所學的技巧。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助你掌握更多 API 功能,並在自己的專案中探索其他實作方式。 + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hongkong/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/hongkong/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..52f7b2f3a --- /dev/null +++ b/barcode/hongkong/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-08-12 +description: 快速在 Python 中配置 Databar 條碼佈局。學習設定欄位、列,並使用條碼產生器函式庫儲存圖像。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: zh-hant +lastmod: 2026-08-12 +og_description: 在 Python 中配置 Databar 條碼佈局,以控制列、行和圖像輸出。按照本指南即可獲得可直接執行的解決方案。 +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: 在 Python 中設定 Databar 條碼佈局 – 完整教學 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: 在 Python 中設定 Databar 條碼版面 – 步驟指南 +url: /zh-hant/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中配置 Databar 條碼佈局 – 步驟指南 + +如果您需要 **在 Python 中配置 Databar 條碼佈局**,本指南將帶您完整操作。您將了解如何為 Databar Expanded Stacked 條碼設定欄位(columns)或列(rows)的數量,以及如何僅透過一次呼叫條碼產生器函式庫即保存產生的圖像。 + +在窄小的包裝、收據或行動裝置螢幕上嵌入條碼時,控制佈局尤為重要。以下各節將說明必要的匯入、兩種佈局選項(欄位與列),以及保存乾淨 PNG 圖像的最佳實踐。 + +## 您需要的環境 + +在開始之前,請確保您已具備: + +* Python 3.8 或更新版本 +* 已安裝 `aspose.barcode`(或任何相容的條碼產生套件) + ```bash + pip install aspose-barcode + ``` +* 具寫入權限的資料夾,用於存放 PNG 檔案 + +不需要額外的外部工具——函式庫會在內部處理渲染、縮放與圖像編碼。 + +## 如何在 Python 中配置 Databar 條碼佈局 + +解決方案的核心是 `BarcodeGenerator` 類別。它接受一個 `EncodeTypes` 列舉,用以指定條碼符號系統——此例為 `EncodeTypes.DatabarExpandedStacked`。建立產生器後,您可以透過設定 `data_bar` 參數物件的 `columns` 或 `rows` 屬性來調整佈局。 + +### 步驟 1:匯入必要的類別 + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +上述匯入讓您可以存取產生器、Databar 類型的列舉,以及 PNG 圖像格式常數。 + +### 步驟 2:為 Databar Expanded Stacked 建立條碼產生器 + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*為什麼要這麼做?* +`EncodeTypes.DatabarExpandedStacked` 告訴函式庫產生 **Databar Expanded Stacked** 符號,該符號可容納較長的數字字串,同時保持緊湊的佔位空間。第二個參數是要編碼的資料;只要符合 Databar 規範的字串皆可。 + +### 步驟 3:設定欄位數量(水平佈局) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** 是此操作的關鍵語句。當您增加欄位數時,條碼會水平展開,適合寬標籤使用。函式庫會自動重新計算模組寬度,以維持整體尺寸的一致性。 + +#### 專業提示 +Databar Expanded Stacked 的最大欄位數為 8。設定超過上限的值會被限制為最大值,但建議事先驗證輸入。 + +### 步驟 4:使用欄位佈局保存條碼圖像 + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** 為將渲染好的條碼寫入磁碟的動作。PNG 為無損格式,可保留掃描所需的銳利邊緣。 + +### 步驟 5:為相同條碼類型建立第二個產生器(列佈局) + +如果您偏好垂直堆疊,則使用列(rows)而非欄位(columns)。以下程式碼重新使用相同的資料值,但會建立全新的 `BarcodeGenerator` 實例,以避免欄位與列設定混用。 + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### 步驟 6:設定列數量(垂直佈局) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** 會將條碼模組垂直排列。三列佈局會降低每個堆疊的高度,使條碼適用於窄收據或行動螢幕。 + +#### 邊緣情況 +若將 `rows` 設為 1,函式庫會產生單列 Databar(等同於標準 Databar)。小於 1 的值會被忽略,並重設為預設值(1 列)。 + +### 步驟 7:使用列佈局保存條碼圖像 + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +同樣,我們 **save barcode image**,使用 PNG 以保持輸出清晰。 + +## 完整可執行範例 + +將所有片段組合起來,即可得到一個可直接放入任何 Python 專案的自包含腳本。 + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**預期輸出** + +執行腳本後會產生兩個 PNG 檔案: + +* `output/ExpandedCols4.png` – 以四欄方式展開的條碼 +* `output/ExpandedRows3.png` – 以三列方式壓縮的條碼 + +兩張圖皆可在任何圖像檢視器中開啟,或直接匯入 PDF 發票、標籤範本或網頁。 + +## 常見問題與疑難排解 + +| 問題 | 解答 | +|----------|--------| +| *條碼看起來模糊怎麼辦?* | 在呼叫 `save` 前,透過設定 `barcode_generator.parameters.image_width` 與 `image_height` 來提升圖像解析度。 | +| *可以使用其他圖像格式嗎?* | 可以。將 `BarCodeImageFormat.Png` 替換為 `Jpeg`、`Bmp` 或 `Gif` 即可。 | +| *資料長度有上限嗎?* | Databar Expanded Stacked 最多支援 74 個數字字元。超過上限會拋出 `ArgumentException`。 | +| *如何變更前景顏色?* | 使用 `barcode_generator.parameters.barcode.color = Color.Blue`(需匯入 `System.Drawing.Color`)。 | +| *可以同時使用欄位與列嗎?* | 不行。API 將欄位與列視為互斥的佈局模式,每個條碼實例只能選擇其一。 | + +## 後續步驟 + +既然您已能 **配置 Databar 條碼佈局**,不妨進一步探索以下相關主題: + +* **加入文字說明** – 使用 `barcode_generator.parameters.barcode.code_text` 在圖像下方顯示編碼值。 +* **將條碼嵌入 PDF** – 結合產生的 PNG 與 `aspose.pdf`,建立可列印的文件。 +* **動態尺寸調整** – 在執行時根據標籤尺寸計算最佳的欄位或列數。 +* **批次處理** – 迭代 CSV 中的產品代碼,自動產生條碼圖像庫。 + +嘗試不同的欄位與列設定,觀察它們對目標裝置掃描可靠性的影響。測試越多,您對條碼大小、可讀性與空間限制之間的取捨就越了解。 + +--- + +*祝編程愉快!若本教學對您有幫助,請與同事分享,或留下您在佈局上遇到的挑戰評論。* + + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,能在本篇示範的技巧之上,協助您掌握更多 API 功能並探索其他實作方式: + +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Create barcode image c# – Configure Codablock F Rows & Columns](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [One-Dimensional Databar Barcode Height Adjustment](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hongkong/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/hongkong/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..431435885 --- /dev/null +++ b/barcode/hongkong/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,230 @@ +--- +category: general +date: 2026-08-12 +description: 使用 BarCodeGenerator 在 C# 中建立條碼圖像。了解如何產生 DataBar、控制條碼圖像尺寸,以及有效率地建立多個條碼。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: zh-hant +lastmod: 2026-08-12 +og_description: 使用 BarCodeGenerator 在 C# 中建立條碼圖像。本教學逐步說明如何產生 DataBar 條碼、調整條碼圖像大小,以及產生多個條碼。 +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: 在 C# 中建立條碼圖像 – 完整的 BarCodeGenerator 指南 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: 使用 BarCodeGenerator 在 C# 中建立條碼圖像 +url: /zh-hant/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中使用 BarCodeGenerator 建立條碼圖像 + +如果您需要在 .NET 應用程式中 **建立條碼圖像**,本指南將向您展示如何使用 `BarCodeGenerator` 類別完成。無論您是構建零售 POS 系統或庫存追蹤工具,您都將學會產生 DataBar 符號、控制條碼圖像大小,並一次產生多個條碼。 + +您還會發現 **barcode generator c#** API 如何讓您調整尺寸、切換輸出格式,並處理如無效資料字串等邊緣情況。完成本教學後,您即可自信地 **建立多個條碼**,而無需撰寫重複程式碼。 + +## 前置條件 + +- 已安裝 .NET 6.0 或更新版本 +- 開發環境 (Visual Studio、Rider 或 VS Code) +- Aspose.BarCode for .NET NuGet 套件(或任何提供 `BarCodeGenerator` 的相容函式庫) + +您可以使用以下方式加入套件: + +```bash +dotnet add package Aspose.BarCode +``` + +## 本教學涵蓋內容 + +1. 為 DataBar Omni‑directional 編碼設定 **barcode generator c#** 實例。 +2. 透過變更 X‑dimension 與 bar height 來調整 **barcode image size**。 +3. 使用迴圈 **create multiple barcodes**,並設定不同高度。 +4. 將圖像儲存為 PNG 檔案並驗證輸出。 + +所有程式碼片段皆完整,可直接複製貼上至新的主控台專案。 + +![Create barcode image example](barcode-example.png){alt="建立條碼圖像範例"} + +## 步驟 1:初始化產生器 – 建立條碼圖像基礎 + +第一步是以所需的符號實例化 `BarCodeGenerator`。若要產生 DataBar Omni‑directional 符號,請使用 `EncodeTypes.DatabarOmniDirectional`。 + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**為什麼重要:** 實例化產生器會定義編碼規則與資料負載。若省略正確的 `EncodeTypes` 值,函式庫將產生不支援的條碼或拋出例外。 + +## 步驟 2:設定 X‑dimension 與 bar height – 控制條碼圖像大小 + +條碼的視覺大小由兩個參數決定: + +| 參數 | 控制項目 | 典型範圍 | +|-----------|------------------|---------------| +| `x_dimension.pixels` | 最小模組(「點」)的寬度 | 1 – 4 px | +| `bar_height.pixels` | 垂直條的高度 | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**專業提示:** 較小的 X‑dimension 會產生較高解析度的圖像,但在低品質印表機上可能較難掃描。請根據目標掃描設備調整此數值。 + +## 步驟 3:儲存第一個條碼 – 為 30 px 高度建立條碼圖像 + +現在您可以產生圖像並寫入磁碟。`Save` 方法接受檔案路徑與圖像格式列舉值。 + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**預期結果:** 會在 `C:\Barcodes` 中產生名為 `Databar30.png` 的 PNG 檔案。開啟該檔案可看到 DataBar Omni‑directional 符號,圖案清晰且高對比。 + +## 步驟 4:變更高度並產生其他圖像 – 建立多個條碼 + +若要 **create multiple barcodes** 且使用不同尺寸,只需修改 `BarHeight` 屬性並再次呼叫 `Save`。此方式避免重新實例化產生器,可節省記憶體與 CPU 時間。 + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**為什麼可行:** `BarCodeGenerator` 物件保存所有設定狀態。變更單一屬性即會更新渲染引擎,供下一次 `Save` 呼叫使用,讓您能有效率地 **create multiple barcodes**。 + +## 步驟 5:進階 – 如何以自訂資料產生 DataBar + +上述範例使用靜態 GS1 負載。在實務情境中,您常需嵌入可變的產品識別碼。函式庫接受任何符合 DataBar 規範的字串。 + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**重點:** 設定 `generator.CodeText` 可在不重新建立物件的情況下更新編碼資料。這是在處理大量資料時,建議的 **how to generate databar** 模式。 + +## 步驟 6:驗證與除錯 – 確保條碼圖像尺寸正確 + +產生圖像後,您可能想以程式方式確認尺寸是否符合預期。`System.Drawing` 中的 `Image` 類別可讀取檔案並回報其大小。 + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +如果高度未反映您設定的值,請檢查: + +- **X‑dimension**:過小的數值可能導致渲染器將高度四捨五入。 +- **Image format**:某些格式(例如 JPEG)在儲存時會進行壓縮,可能改變像素尺寸。PNG 可保留精確尺寸。 + +## 步驟 7:條碼圖像尺寸與效能的最佳實踐 + +| 建議 | 原因 | +|----------------|--------| +| 對大多數掃描器,將 `x_dimension.pixels` 保持在 2 – 3 px 之間。 | 在可讀性與檔案大小之間取得平衡。 | +| 在圖像將被列印時,使用 PNG 以獲得無損輸出。 | 確保精確尺寸與銳利邊緣。 | +| 產生大量條碼時,重複使用單一 `BarCodeGenerator` 實例。 | 減少物件分配的開銷。 | +| 在指派給 `CodeText` 前,先根據 GS1 標準驗證輸入字串。 | 避免執行時例外與無效掃描。 | +| 將產生的圖像存放於專用資料夾,並使用清晰的命名規則(例如 `Databar_{GTIN}.png`)。 | 簡化後續處理與稽核追蹤。 | + +## 完整範例程式 + +以下為完整程式,涵蓋從初始化到驗證的所有步驟。將程式碼複製到新的主控台專案並執行。 + + + +## 接下來您應該學習什麼? + +以下教學涵蓋與本指南示範技術密切相關的主題。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助您精通其他 API 功能,並在自己的專案中探索替代實作方式。 + +- [產生條碼圖像 – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [建立 DotCode 條碼圖像 – 行與列 (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [如何使用 Aspose.BarCode for .NET 為 ITF-14 建立條碼安靜區](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hongkong/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/hongkong/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..156af8020 --- /dev/null +++ b/barcode/hongkong/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-08-12 +description: 使用 Python 建立全方向 DataBar 條碼,並學習如何使用 Aspose.BarCode 在 Python 中產生條碼圖像。跟隨逐步指南,即可獲得完整解決方案。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: zh-hant +lastmod: 2026-08-12 +og_description: 使用 Python 建立全向 DataBar,並在數分鐘內產生條碼圖像。此教學提供完整且可執行的範例。 +og_image_alt: example of create omni directional databar barcode image in Python +og_title: 建立全向資料條 – 完整 Python 指南 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: 在 Python 中產生全向 DataBar 與條碼圖像 +url: /zh-hant/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中建立全向 DataBar 與條碼圖像 + +如果您需要在 Python 專案中 **建立全向 DataBar**,本指南將示範如何操作,同時說明如何使用 Aspose.BarCode 函式庫 **建立條碼圖像(Python)**。您將獲得一個可直接執行的腳本,產生兩個具有不同長寬比的 PNG 檔案。 + +產生符合全向規範的 DataBar 是零售與物流應用的常見需求。本教學涵蓋安裝、X‑dimension 設定、長寬比調整,以及最終圖像的儲存。無需外部服務,全部在本機執行。 + +## 您需要的條件 + +在開始之前,請確保您具備: + +* 已在機器上安裝 Python 3.8 或更新版本。 +* 可使用終端機或命令提示字元。 +* 具有寫入條碼圖像儲存資料夾的權限。 + +唯一的第三方相依性是 **Aspose.BarCode for Python via .NET**,它內建支援全向 DataBar 類型。 + +## 步驟 1:安裝 Aspose.BarCode for Python + +Aspose.BarCode 提供範例程式碼中使用的 `BarcodeGenerator` 類別。使用 `pip` 安裝套件: + +```bash +pip install aspose-barcode +``` + +此套件已包含必要的 .NET 執行時綁定,無需額外安裝 .NET SDK。 + +## 步驟 2:匯入函式庫並建立產生器 + +腳本的第一行會為堆疊式全向 DataBar 建立產生器。範例資料使用 GTIN‑14 值 `(01)12345678901231`。 + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Why this step matters*: `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` 常數告訴函式庫將值編碼為全向 DataBar,這是許多 POS 掃描器所要求的格式。 + +## 步驟 3:設定 X‑dimension(模組寬度) + +X‑dimension 定義最小條模組的寬度。設定為 `2` 像素即可產生清晰、易讀的條碼,同時不會產生過大的檔案。 + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Why this step matters*: 調整 X‑dimension 可在可讀性與圖像尺寸之間取得平衡。若 X‑dimension 設定過小,低解析度印表機的列印效果可能不佳。 + +## 步驟 4:設定長寬比並儲存第一張圖像 + +長寬比會影響 DataBar 相對於寬度的整體高度。設定為 `15` 可產生緊湊的視覺風格。 + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Pro tip**: 使用 `pathlib.Path` 來建立輸出路徑,系統會自動建立缺失的目錄。 + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## 步驟 5:變更長寬比以產生第二種視覺樣式並儲存另一張圖像 + +將長寬比改為 `30` 會產生較高的條碼,某些掃描硬體可能需要此尺寸。 + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Why this step matters*: 不同零售商與掃描設備有各自的尺寸限制。一次腳本同時提供兩種長寬比,可在不重複程式碼的情況下產出所需樣式。 + +## 完整腳本 – 在 Python 中建立全向 DataBar 與條碼圖像 + +以下為完整、可執行的範例,結合前述所有步驟。將其儲存為 `generate_databar.py`,並以 `python generate_databar.py` 執行。 + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### 預期輸出 + +執行腳本後會產生以下檔案: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +兩張圖像皆為可被標準零售設備掃描的有效全向 DataBar。 + +![在 Python 中建立全向 DataBar 條碼圖像範例](example_databar.png "在 Python 中建立全向 DataBar 條碼圖像") + +*上圖僅為示意圖,展示兩個已儲存的 PNG 檔案。* + +## 常見問題處理 + +| 問題 | 原因 | 解決方案 | +|------|------|----------| +| `ImportError: No module named aspose` | Aspose.BarCode 未安裝或安裝於不同的環境。 | 啟動正確的虛擬環境,並執行 `pip install aspose-barcode`。 | +| `PermissionError` when saving | 腳本缺乏目標資料夾的寫入權限。 | 選擇您擁有寫入權限的目錄,或以適當的權限執行腳本。 | +| Barcode does not scan | X‑dimension 太低或長寬比與掃描器不相容。 | 將 `x_dimension.pixels` 提升至 3 或 4,並測試不同的 `aspect_ratio`(例如 20、25)。 | +| Missing .NET runtime | Aspose.BarCode 依賴 Windows/Linux 上的 .NET 執行時。 | 從 Microsoft 官方網站安裝最新的 .NET 執行時;套件文件提供平台特定的指引。 | + +## 擴充範例 + +您可以將腳本改寫為產生其他 DataBar 變體(例如 `DATABAR_STACKED`、`DATABAR_EXPANDED`),只需相應替換 `EncodeTypes` 常數: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +若需將條碼嵌入 PDF,Aspose.PDF for Python 可直接匯入 PNG 檔,或使用 `save` 方法搭配 `BarCodeImageFormat.Pdf`。 + +## 結論 + +本教學示範了如何使用 Aspose.BarCode **建立全向 DataBar** 以及 **建立條碼圖像(Python)**。您現在擁有一個完整且可重現的腳本,能產生兩個不同長寬比的 PNG 檔案,處理常見問題,且可延伸至其他條碼格式。 + +接下來,您可以探索產生 QR Code、將條碼加入 PDF 發票,或為大型商品目錄自動化批次處理。上述主題皆以本範例中的 `BarcodeGenerator` 模式為基礎。祝開發順利! + +## 接下來您可以學習什麼? + +以下教學涵蓋與本指南技術緊密相關的主題,每篇都提供完整可執行的程式碼範例與逐步說明,協助您掌握更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [產生條碼圖像 – GS1 Coupon UPC-A DataBar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [建立 DotCode 條碼圖像 – 行與列(Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [如何在 Java 中建立條碼圖像並渲染](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hongkong/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/hongkong/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..073509a61 --- /dev/null +++ b/barcode/hongkong/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,251 @@ +--- +category: general +date: 2026-08-12 +description: 如何使用 Python 快速產生條碼。學習從資料建立條碼,並使用單一函式庫匯出條碼圖像。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: zh-hant +lastmod: 2026-08-12 +og_description: 如何使用 Aspose.BarCode 在 Python 中生成條碼。請參考本指南,從資料建立條碼並將條碼圖像匯出為 PNG。 +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: 如何在 Python 中生成條碼 – 快速、可靠指南 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: 如何在 Python 中生成條碼 – 完整逐步指南 +url: /zh-hant/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 Python 中產生條碼 – 完整逐步指南 + +如果您需要在 Python 應用程式中 **產生條碼**,本教學會展示您所需的完整程式碼。您將學會 **從資料建立條碼**、調整其外觀,並將 **匯出條碼影像** 為 PNG 檔案——全部只需不到十行程式碼。 + +產生條碼感覺好像與其他業務邏輯無關,但只要使用單一函式庫,就能將此流程直接整合到現有程式碼中。接下來的章節會示範完整可執行的範例、說明每一行程式碼的意義,並探討常見的變化,例如調整模組寬度或繪製僅輪廓的條碼。 + +## 使用 Aspose.BarCode 函式庫產生條碼 + +Aspose.BarCode 函式庫(透過 .NET)為多種條碼符號提供直觀的 API,本文使用的 Planet 條碼即是其中之一。開始之前,請先確定已安裝套件: + +```bash +pip install aspose-barcode +``` + +> **專業提示:** 使用虛擬環境以避免與其他專案的版本衝突。 + +### 1. 匯入所需類別 + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +這些匯入讓您可以存取產生器類別、條碼類型列舉,以及儲存結果時使用的影像格式列舉。 + +### 2. 從資料建立條碼 + +第一步是 **從資料建立條碼**。`BarcodeGenerator` 建構子接受條碼符號與您想編碼的原始字串。 + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +`EncodeTypes.Planet` 會選擇 Planet 條碼,而 `"123456"` 則是最終影像中顯示的資料。 + +### 3. 調整 X‑dimension(模組寬度) + +X‑dimension 控制每個條碼模組(細條)的寬度。將其設為 4 像素即可產生清晰、易讀的影像,同時不會使檔案過大。 + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **為什麼重要:** 較大的 X‑dimension 可提升低解析度印表機的掃描可靠性,而較小的數值則可減少網路使用的檔案大小。 + +### 4. 匯出條碼影像(實心樣式) + +現在您可以使用 `save` 方法 **匯出條碼影像**。範例會儲存為 PNG 檔案,您也可以透過變更 `BarCodeImageFormat` 列舉改為 JPEG、BMP 或 TIFF。 + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +`PlanetFilled.png` 檔案包含完整實心的 Planet 條碼,可直接列印或嵌入 PDF 中。 + +### 5. 為僅輪廓條碼建立第二個產生器 + +若需要僅輪廓版本(空白條),必須建立新產生器,因為 `filled_bars` 旗標在影像儲存後無法再切換。 + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. 套用相同的 X‑dimension 設定 + +建立第二個產生器時,必須再次設定所有想保持一致的視覺參數。 + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. 停用實心條以產生輪廓條碼 + +將 `filled_bars` 設為 `False` 會讓渲染器只繪製每個模組的輪廓,產生較輕的影像,適合設計用途。 + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. 匯出輪廓條碼影像 + +最後,再次 **匯出條碼影像**,這次儲存為輪廓版本。 + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +現在您擁有兩個 PNG 檔案:一個實心條碼 (`PlanetFilled.png`) 與一個僅輪廓條碼 (`PlanetEmpty.png`)。 + +## 以其他格式匯出條碼影像(可選) + +`save` 方法支援多種格式。若要以 90% 品質匯出 JPEG: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +若需要透明背景以供網頁使用,請選擇具 alpha 通道的 PNG: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## 常見變化與邊緣情況 + +| 情境 | 需要的變更 | Code snippet | +|----------|---------------|--------------| +| **不同的符號系統**(例如 QR) | 使用不同的 `EncodeTypes` 值 | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **自訂前景色** | 設定 `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **較高解析度** | 透過 `image_width` 與 `image_height` 提升 DPI | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **大型資料字串** | 確保資料長度符合符號系統規範 | Validate length before creating the generator | + +> **注意:** 提供超過所選符號系統最大長度的資料會拋出執行時例外。請務必驗證字串長度或捕獲 `ArgumentException`。 + +## 完整、可執行的範例 + +以下是完整腳本,您可以直接複製貼上至名為 `generate_planet_barcode.py` 的檔案。請將 `YOUR_DIRECTORY` 調整為您機器上實際存在的資料夾路徑。 + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +執行此腳本會在指定目錄產生兩個 PNG 檔案。打開任意影像檢視器確認輸出,兩者皆應顯示編碼為 `123456` 的 Planet 條碼。 + +## 結論 + +您現在已了解如何使用 Aspose.BarCode 在 Python 中 **產生條碼**、**從資料建立條碼**,以及如何 **匯出條碼影像**(實心與輪廓兩種樣式)。相同的模式同樣適用於其他符號系統、影像格式與視覺自訂,為您在應用程式中加入任何條碼相關功能提供彈性基礎。 + +### 後續步驟 + +* 探索其他符號系統,如 QR、Code‑128 或 DataMatrix,只需將 `EncodeTypes.Planet` 替換為目標值。 +* 使用 `ReportLab` 或 `PyPDF2` 等函式庫,將產生的 PNG 檔案整合至 PDF 報告中。 +* 嘗試動態調整 X‑dimension,以因應螢幕解析度或印表機 DPI 的不同需求。 + +祝程式開發順利,隨時依需求調整範例以符合您的專案。 + +## 接下來該學什麼? + +以下教學涵蓋與本指南技術緊密相關的主題,能在您掌握本篇示範的技巧後,進一步學習更多 API 功能與替代實作方式。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助您在自己的專案中靈活運用。 + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hungarian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/hungarian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..5949dee24 --- /dev/null +++ b/barcode/hungarian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,291 @@ +--- +category: general +date: 2026-08-12 +description: Vonalkód-generátor példa, amely bemutatja, hogyan lehet pontos képpontmérettel + vonalkódot generálni. Tanulja meg a modul szélességét, a vonalmagasságot beállítani, + és Planet vonalkódokat létrehozni. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: hu +lastmod: 2026-08-12 +og_description: A vonalkód-generátor példa bemutatja, hogyan lehet pontos pixelméretekkel + vonalkódot generálni. Kövesse ezt az útmutatót a modul szélességének és a vonal + magasságának szabályozásához a Planet és RM4SCC kódok esetén. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: Vonalkód-generátor példa – pixelméret testreszabása C#‑ban +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Vonalkód-generátor példa – lépésről‑lépésre útmutató egyedi pixelméretekhez +url: /hu/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# barcode generator example – lépésről‑lépésre útmutató egyedi pixelméretekhez + +Ha **barcode generator example**-ra van szükséged, amely lehetővé teszi minden pixel vezérlését, ez az útmutató pontosan megmutatja, hogyan kell ezt megtenni. Megtanulod beállítani a modul szélességét, meghatározni egy rögzített sávmagasságot, és generálni a Planet és RM4SCC vonalkódokat előre meghatározott méretekkel. + +A legtöbb fejlesztő nehezen tud “how to generate barcode” képeket készíteni, amelyek minden képernyőn vagy nyomtatón ugyanúgy néznek ki. Az alábbi kódrészletek megoldják ezt a problémát az Aspose.BarCode for .NET könyvtár pixel‑szintű paramétereinek feltárásával, így találgatás nélkül tudsz konzisztens kimenetet előállítani. + +## Mit fogsz megtanulni + +* Hogyan telepítsd a szükséges NuGet csomagot. +* Hogyan generálj Planet vonalkódot automatikusan kiszámított magassággal. +* Hogyan generálj Planet vonalkódot kifejezett 100‑pixel magassággal. +* Hogyan generálj RM4SCC vonalkódot ugyanazzal a kifejezett magassággal. +* Miért fontos a **barcode pixel size** a szkennelés megbízhatósága szempontjából. +* Tippek a gyakori problémák hibaelhárításához, amikor Planet vonalkód képeket generálsz. + +Csak .NET 6 vagy újabb, egy alap C# fejlesztői környezet, és internetkapcsolat szükséges a NuGet csomag letöltéséhez. + +--- + +## barcode generator example – a fejlesztői környezet beállítása + +Mielőtt kódot írnál, győződj meg arról, hogy az Aspose.BarCode könyvtár elérhető a projekted számára. + +### Az Aspose.BarCode csomag telepítése + +Nyiss egy terminált a projekt mappádban, és futtasd: + +```bash +dotnet add package Aspose.BarCode +``` + +A parancs hozzáadja a **Aspose.BarCode** legújabb stabil verzióját a `csproj` fájlodhoz. A visszaállítás befejezése után elkezdheted használni a `BarcodeGenerator` osztályt. + +> **Pro tipp:** Célozd meg a .NET 6 vagy .NET 7 verziót, hogy élvezd a legújabb teljesítményjavulásokat és az alapértelmezett UTF‑8 kezelés előnyeit. + +### A szükséges `using` direktívák hozzáadása + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Ezek a névterek teszik elérhetővé a `BarcodeGenerator` osztályt és a `BarCodeImageFormat` enumot, amelyeket később a tutorialban használunk. + +--- + +## Hogyan generálj vonalkódot egyedi pixelmérettel + +A következő három lépés bemutatja a teljes **barcode generator example**-t. Minden lépés az előzőre épül, így a teljes blokkot egyszerűen átmásolhatod egy konzolos alkalmazásba, és változtatás nélkül futtathatod. + +### 1. lépés – Planet vonalkód generálása automatikusan kiszámított magassággal + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Miért működik:** +*A `XDimension` tulajdonság határozza meg egyetlen vonalkód modul (a legkisebb fekete vagy fehér elem) szélességét. Ha kihagyod a `BarHeight`-t, a könyvtár kiszámít egy magasságot, amely megőrzi a Planet kódok standard képarányát.* + +**Várható kimenet:** Egy `PlanetAuto.png` nevű PNG fájl, amely tiszta Planet vonalkódot tartalmaz. A magassága a 4‑pixel modul szélességhez igazodik, általában körülbelül 60 pixel egy hat karakteres adat esetén. + +### 2. lépés – Planet vonalkód generálása kifejezett 100‑pixel magassággal + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Miért lehet erre szükséged:** +Néha a szkennelő berendezés minimális sávmagasságot igényel a megbízható felismeréshez. A `BarHeight.Pixels` beállításával garantálod, hogy minden generált kép megfelel ennek a követelménynek, függetlenül a kódolt adat hosszától. + +**Várható kimenet:** A `PlanetHeight100.png` ugyanazt az adatot mutatja, mint korábban, de a sávok pontosan 100 pixel magasak, így teljes kontrollt kapsz a vizuális méret felett. + +### 3. lépés – RM4SCC vonalkód generálása ugyanazzal a kifejezett magassággal + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Miért fontos:** +Az `EncodeTypes.RM4SCC` egy logisztikában használt réteges lineáris vonalkód. A sávmagasságának a Planet vonalkóddal való egyeztetése egyszerűsíti a kötegelt feldolgozást, amikor mindkét szimbólum ugyanazon a címkén jelenik meg. + +**Várható kimenet:** A `RM4SCCHeight100.png` tökéletes méretű RM4SCC vonalkódot jelenít meg, amely megegyezik a Planet kódhoz beállított 100‑pixel magassággal. + +> **Eredmény ellenőrzése:** Nyisd meg minden PNG-t egy képnézőben, és ellenőrizd, hogy a fekete sávok pontosan 4 pixel szélesek, és ahol megadtad, 100 pixel magasak. A fájlokat betáplálhatod egy vonalkódolvasó alkalmazásba is, hogy megbizonyosodj arról, hogy a „123456” kódot dekódolják. + +## A vonalkód pixelméretének és sávmagasságának megértése + +### Mi az a **barcode pixel size**? + +*Pixel size* a képernyő vagy nyomtató pixelének fizikai számát jelenti, amely egyetlen modult (`XDimension`) reprezentál. A nagyobb pixelméret nagyobb vonalkódot eredményez, ami alacsony felbontású szkennerek számára könnyebb lehet, de több címkehelyet foglal. + +### Hogyan befolyásolja a `BarHeight` az olvashatóságot? + +A `BarHeight` tulajdonság szabályozza a sávok függőleges hosszát. A legtöbb 1‑D vonalkód (köztük a Planet és az RM4SCC) szabványa minimum 10 mm magasságot javasol 300 dpi nyomtatás esetén, ami nagyjából 118 pixelnek felel meg. Alatta a magasság beállítása olvasási hibákat okozhat, különösen mobil kameráknál. + +### Mikor hagyd, hogy a könyvtár automatikusan számolja ki a magasságot? + +Ha csak képernyőn történő megjelenítéshez generálsz vonalkódokat, az automatikus számítás fenntartja a képarányt, és csökkenti a szükséges manuális finomhangolás mennyiségét. Nyomtatott címkék esetén, amelyeknek szigorú ISO előírásoknak kell megfelelniük, **kifejezetten állítsd be a sávmagasságot**. + +## Gyakori buktatók és legjobb gyakorlatok a Planet vonalkód generálásakor + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| A sávok túl vékonyak vagy túl vastagok | `XDimension` alapértelmezett (1 pixel) maradt a nagy felbontású kijelzőkön | Állítsd be a `XDimension.Pixels` értékét legalább 3‑4-re a vizuális tisztaság érdekében | +| A szkenner nem tudja beolvasni a kódot | `BarHeight` túl kicsi a szkenner fókusztávolságához | Használd a `BarHeight.Pixels` ≥ 100 értéket a legtöbb mobil szkennerhez | +| A kép elmosódott a méretezés után | JPEG formátumban mentés kompressziós hibákat okoz | Ments PNG-ként (`BarCodeImageFormat.Png`) a veszteségmentes kimenethez | +| Váratlan vonalkód típus | Helytelen `EncodeTypes` enum érték | Ellenőrizd, hogy a Planet szimbólumhoz a `EncodeTypes.Planet` értéket használod | + +### Pro tipp a teljesítményhez + +Több ezer vonalkód batch feladatban történő generálásakor használj újra egyetlen `BarcodeGenerator` példányt, és csak a `CodeText` és a méretparaméterek módosításával mentsd el újra. Ez elkerüli a belső renderelő objektumok ismételt lefoglalását, és akár 30 %-kal is csökkentheti a végrehajtási időt. + +--- + +## Teljes működő példa – minden összeállítása + +Hozz létre egy új konzolos projektet (`dotnet new console -n BarcodeDemo`), és cseréld le a `Program.cs` tartalmát a következőre: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Futtasd a programot a `dotnet run` paranccal. A futtatás után három PNG fájlt találsz a projekt mappájában, amelyek mindegyike egy különböző **barcode generator example** szcenáriót mutat be. + +--- + +## Következő lépések és kapcsolódó témák + +* **How to generate barcode in other formats** – fedezd fel a `EncodeTypes.Code128`, `EncodeTypes.QR`, és `EncodeTypes.DataMatrix` opciókat 2‑D igényekhez. +* **Embedding barcodes in PDFs** – kombináld az Aspose.BarCode-ot az Aspose.PDF-fel, hogy a vonalkódokat közvetlenül a számla sablonokra helyezd. +* **Dynamic barcode size based on user input** – számold ki + +## Mit kellene most tanulnod? + +A következő oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljesen működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Hogyan generáljunk vonalkódot Java-ban: pontos vonalkód kép létrehozása](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [Hogyan generáljunk vonalkódot Java-ban: teljes kép méretének létrehozása és beállítása](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [Hogyan hozzunk létre code128 vonalkódot Java-ban és állítsuk be a sávmagasságot](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hungarian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/hungarian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..e386eeeae --- /dev/null +++ b/barcode/hungarian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Állítsd be gyorsan a Databar vonalkód elrendezését Pythonban. Tanuld + meg, hogyan állíts be oszlopokat, sorokat, és ments képeket a vonalkód-generátor + könyvtárral. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: hu +lastmod: 2026-08-12 +og_description: Állítsd be a Databar vonalkód elrendezését Pythonban, hogy szabályozd + az oszlopokat, sorokat és a képkimenetet. Kövesd ezt az útmutatót egy azonnal futtatható + megoldáshoz. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Databar vonalkód elrendezés beállítása Pythonban – teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Databar vonalkód elrendezés konfigurálása Pythonban – lépésről lépésre útmutató +url: /hu/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Databar vonalkód elrendezésének konfigurálása Pythonban – lépésről‑lépésre útmutató + +Ha **Databar vonalkód elrendezését szeretné konfigurálni Pythonban**, ez az útmutató végigvezeti a teljes folyamaton. Megmutatjuk, hogyan állíthatja be az oszlopok vagy sorok számát egy Databar Expanded Stacked vonalkódhoz, és hogyan mentheti el a keletkezett képet egyetlen hívással a vonalkód generátor könyvtárból. + +Az elrendezés szabályozása elengedhetetlen, amikor szűk csomagolásra, nyugtákra vagy mobil képernyőkre ágyaz vonalkódokat. Az alábbi szakaszokban bemutatjuk a szükséges importálásokat, a két elrendezési lehetőséget (oszlopok és sorok), valamint a tiszta PNG kép mentésének legjobb gyakorlatait. + +## Amire szüksége lesz + +* Python 3.8 vagy újabb +* `aspose.barcode` (vagy bármely kompatibilis vonalkód‑generáló csomag) telepítve + ```bash + pip install aspose-barcode + ``` +* Írási jogosultság egy olyan mappához, ahol a PNG fájlok tárolva lesznek + +Nem szükséges további külső eszköz – a könyvtár belsőleg kezeli a renderelést, méretezést és a kép kódolását. + +## Hogyan konfigurálja a Databar vonalkód elrendezését Pythonban + +A megoldás központja a `BarcodeGenerator` osztály. Egy `EncodeTypes` enumerációt fogad, amely meghatározza a vonalkód szimbólumát – ebben az esetben `EncodeTypes.DatabarExpandedStacked`. A generátor létrehozása után a `columns` vagy `rows` tulajdonságok beállításával módosíthatja az elrendezést a `data_bar` paraméterobjektumban. + +### 1. lépés: A szükséges osztályok importálása + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Ezek az importálások hozzáférést biztosítanak a generátorhoz, a Databar típusok enumerációjához és a PNG képformátum állandóhoz. + +### 2. lépés: Vonalkód generátor létrehozása a Databar Expanded Stacked számára + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Miért ez a lépés?* +`EncodeTypes.DatabarExpandedStacked` azt mondja a könyvtárnak, hogy a **Databar Expanded Stacked** szimbólumot állítsa elő, amely hosszabb numerikus karakterláncokat támogat, miközben kompakt lábnyomot tart meg. A második argumentum a kódolandó adat; lehet bármely olyan karakterlánc, amely megfelel a Databar specifikációnak. + +### 3. lépés: Az oszlopok számának beállítása (vízszintes elrendezés) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** a kulcsfontosságú kifejezés ehhez a művelethez. Ha növeli az oszlopszámot, a vonalkód vízszintesen terjed, ami széles címkék esetén hasznos lehet. A könyvtár automatikusan újraszámolja a modul szélességét, hogy az összméret konzisztens maradjon. + +#### Profi tipp +A Databar Expanded Stacked maximális oszlopszáma 8. Ha a limitnél nagyobb értéket állít be, azt a maximumra korlátozza, de jobb előre ellenőrizni a bemenetet. + +### 4. lépés: A vonalkód kép mentése oszlopos elrendezéssel + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** az a művelet, amely a renderelt vonalkódot lemezre írja. A PNG veszteségmentes, ami megőrzi a megbízható beolvasáshoz szükséges éles éleket. + +### 5. lépés: Második generátor létrehozása ugyanarra a vonalkódtípusra (soros elrendezés) + +Ha inkább függőleges halmot szeretne, sorokkal dolgozik az oszlopok helyett. Az alábbi kód ugyanazt az értéket használja újra, de egy új `BarcodeGenerator` példányt hoz létre, hogy elkerülje az oszlop- és sorbeállítások keverését. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### 6. lépés: A sorok számának beállítása (függőleges elrendezés) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** függőlegesen rendezi a vonalkód modulokat. A három soros elrendezés csökkenti az egyes halmok magasságát, így a vonalkód szűk nyugtákra vagy mobil képernyőkre alkalmas. + +#### Szélsőséges eset +Ha a `rows` értékét 1‑re állítja, a könyvtár egy soros Databar‑t generál (ami egy standard Databar‑nak felel meg). Az 1‑nél kisebb értékeket figyelmen kívül hagyja, és az alapértelmezett (1 sor) értékre állítja vissza. + +### 7. lépés: A vonalkód kép mentése soros elrendezéssel + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Ismét a **save barcode image** művelettel PNG‑t használunk, hogy a kimenet éles maradjon. + +## Teljes futtatható példa + +Az összes rész összeállításával egy önálló szkriptet kap, amelyet bármely Python projektbe beilleszthet. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Várható kimenet** + +A szkript futtatása két PNG fájlt hoz létre: + +* `output/ExpandedCols4.png` – egy vonalkód, amely négy oszlopra nyúlik +* `output/ExpandedRows3.png` – egy vonalkód, amely három sorba van tömörítve + +Mindkét kép megnyitható bármely képnézőben, vagy közvetlenül importálható PDF számlákba, címke sablonokba vagy weboldalakba. + +## Gyakori kérdések és hibaelhárítás + +| Question | Answer | +|----------|--------| +| *Mi van, ha a vonalkód elmosódottnak tűnik?* | Növelje a kép felbontását a `barcode_generator.parameters.image_width` és `image_height` beállításával a `save` hívása előtt. | +| *Használhatok más képformátumokat?* | Igen. Cserélje a `BarCodeImageFormat.Png`-t a szükséges `Jpeg`, `Bmp` vagy `Gif` értékre. | +| *Van korlát az adat hosszára?* | A Databar Expanded Stacked legfeljebb 74 numerikus karaktert támogat. A limit túllépése `ArgumentException`-t eredményez. | +| *Hogyan változtathatom meg az előtér színét?* | Használja a `barcode_generator.parameters.barcode.color = Color.Blue` kifejezést (importálja a `System.Drawing.Color`-t). | +| *Kombinálhatom az oszlopokat és sorokat?* | Nem. Az API az oszlopokat és sorokat kölcsönösen kizáró elrendezési módokként kezeli. Válasszon egyet vonalkód példányonként. | + +## Következő lépések + +Most, hogy **konfigurálhatja a Databar vonalkód elrendezését**, érdemes megvizsgálni ezeket a kapcsolódó témákat: + +* **Add text captions** – használja a `barcode_generator.parameters.barcode.code_text`-et a kódolt érték kép alatti megjelenítéséhez. +* **Embed the barcode in a PDF** – kombinálja a generált PNG-t az `aspose.pdf`-vel nyomtatható dokumentumok létrehozásához. +* **Dynamic sizing** – számolja ki a megfelelő oszlop- vagy sor számot a címke méretei alapján futásidőben. +* **Batch processing** – iteráljon egy termékkódok CSV-n, hogy automatikusan generáljon egy könyvtárat vonalkód képekből. + +Kísérletezzen különböző oszlop- és sorértékekkel, hogy lássa, hogyan befolyásolják a beolvasás megbízhatóságát a céleszközökön. Minél többet tesztel, annál jobban megérti a vonalkód mérete, olvashatósága és a helykorlátok közötti kompromisszumokat. + +--- + +*Boldog kódolást! Ha hasznosnak találta ezt az útmutatót, ossza meg csapattársaival, vagy hagyjon megjegyzést a felmerült elrendezési kihívásokról.* + +## Mit érdemes legközelebb megtanulni? + +Az alábbi oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsen elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket saját projektjeiben. + +- [DotCode vonalkód kép létrehozása – sorok és oszlopok (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Vonalkód kép létrehozása C# – Codablock F sorok és oszlopok konfigurálása](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [Egydimenziós Databar vonalkód magasság beállítása](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hungarian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/hungarian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..a4a7c2c9b --- /dev/null +++ b/barcode/hungarian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: Készítsen vonalkód képet C#-ban a BarCodeGenerator használatával. Tanulja + meg, hogyan generáljon DataBar-t, szabályozza a vonalkód kép méretét, és hatékonyan + hozzon létre több vonalkódot. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: hu +lastmod: 2026-08-12 +og_description: C#-ban készítsen vonalkód képet a BarCodeGenerator segítségével. Ez + az útmutató lépésről lépésre bemutatja, hogyan generáljon DataBar kódokat, állítsa + be a vonalkód kép méretét, és készítsen több vonalkódot. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Vonalkód kép létrehozása C#-ban – teljes BarCodeGenerator útmutató +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Vonalkód kép létrehozása C#‑ban a BarCodeGenerator‑rel +url: /hu/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vonalkód kép létrehozása C#-ban a BarCodeGenerator segítségével + +Ha .NET alkalmazásban **vonalkód képet** kell létrehoznod, ez az útmutató pontosan megmutatja, hogyan teheted ezt meg a `BarCodeGenerator` osztállyal. Akár kiskereskedelmi POS rendszert, akár készletkövető eszközt építesz, megtanulod, hogyan generálj DataBar szimbólumokat, szabályozd a vonalkód kép méretét, és több vonalkódot állíts elő egy futtatás során. + +Felfedezheted, hogyan teszi lehetővé a **barcode generator c#** API a méretek finomhangolását, a kimeneti formátumok váltását, és a szélhelyzetek kezelését, például az érvénytelen adatkarakterláncokat. A tutorial végére magabiztosan **több vonalkódot hozhatsz létre** anélkül, hogy ismétlődő kódot írnál. + +## Előkövetelmények + +- .NET 6.0 vagy újabb telepítve +- Fejlesztői környezet (Visual Studio, Rider vagy VS Code) +- Az Aspose.BarCode for .NET NuGet csomag (vagy bármely kompatibilis könyvtár, amely biztosítja a `BarCodeGenerator`-t) + +A csomagot a következővel adhatod hozzá: + +```bash +dotnet add package Aspose.BarCode +``` + +## A tutorial tartalma + +1. **barcode generator c#** példány beállítása DataBar Omni‑directional kódoláshoz. +2. **barcode image size** módosítása X‑dimenzió és sávmagasság változtatásával. +3. Ciklus használata **multiple barcodes** létrehozásához különböző magasságokkal. +4. A képek PNG fájlként mentése és a kimenet ellenőrzése. + +Minden kódrészlet teljes és készen áll a másolásra‑beillesztésre egy új konzol projektbe. + +![Vonalkód kép példa](barcode-example.png){alt="Vonalkód kép példa"} + +## 1. lépés: Inicializáld a generátort – vonalkód kép alapjai + +Az első lépés a `BarCodeGenerator` példányosítása a kívánt szimbólummal. DataBar Omni‑directional szimbólumhoz a `EncodeTypes.DatabarOmniDirectional` értéket használod. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Miért fontos:** A generátor példányosítása meghatározza a kódolási szabályokat és az adatpayloadot. Ha kihagyod a megfelelő `EncodeTypes` értéket, a könyvtár nem támogatott vonalkódot generál, vagy kivételt dob. + +## 2. lépés: X‑dimenzió és sávmagasság beállítása – a vonalkód kép méretének szabályozása + +A vonalkód vizuális méretét két paraméter határozza meg: + +| Paraméter | Mit szabályoz | Tipikus tartomány | +|-----------|----------------|-------------------| +| `x_dimension.pixels` | A legkisebb modul (a „pont”) szélessége | 1 – 4 px | +| `bar_height.pixels` | A függőleges sávok magassága | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Pro tipp:** A kisebb X‑dimenzió nagyobb felbontású képet eredményez, de alacsony minőségű nyomtatókon nehezebb lehet beolvasni. Állítsd az értéket a célbeolvasó eszközödnek megfelelően. + +## 3. lépés: Az első vonalkód mentése – vonalkód kép 30 px magassággal + +Most már generálhatod a képet és írhatod a lemezre. A `Save` metódus egy fájlútvonalat és egy képformátum enumot fogad. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Várható eredmény:** Egy `Databar30.png` nevű PNG fájl jelenik meg a `C:\Barcodes` mappában. A fájl megnyitása egy DataBar Omni‑directional szimbólumot mutat tiszta, nagy kontrasztú mintával. + +## 4. lépés: Magasság módosítása és további képek generálása – több vonalkód létrehozása + +A **több vonalkód** különböző méretekkel való létrehozásához csak módosítanod kell a `BarHeight` tulajdonságot, és újra meghívni a `Save`-et. Ez elkerüli a generátor újra‑példányosítását, ami memóriát és CPU‑időt takarít meg. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Miért működik:** A `BarCodeGenerator` objektum tárolja az összes konfigurációs állapotot. Egyetlen tulajdonság módosítása frissíti a renderelő motorját a következő `Save` hívásra, lehetővé téve, hogy hatékonyan **több vonalkódot hozz létre**. + +## 5. lépés: Haladó – hogyan generáljunk DataBar-t egyedi adatokkal + +A fenti példa egy statikus GS1 payload-ot használ. Valós környezetben gyakran kell változó termékazonosítókat beágyazni. A könyvtár bármely, a DataBar specifikációnak megfelelő karakterláncot elfogad. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Kulcspont:** A `generator.CodeText` beállítása frissíti a kódolt adatot az objektum újra‑létrehozása nélkül. Ez a javasolt **how to generate databar** minta nagy adathalmazok kezelésekor. + +## 6. lépés: Ellenőrzés és hibaelhárítás – a megfelelő vonalkód kép méretének biztosítása + +A képek generálása után programozottan is ellenőrizheted, hogy a méretek megfelelnek-e az elvárásoknak. A `System.Drawing`-ből származó `Image` osztály képes beolvasni a fájlt és jelenteni a méretét. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Ha a magasság nem egyezik a beállított értékkel, ellenőrizd: + +- **X‑dimension**: Egy nagyon kis érték miatt a renderelő lekerekítheti a magasságot. +- **Image format**: Néhány formátum (pl. JPEG) tömörítést alkalmaz, ami a mentéskor megváltoztathatja a pixelméreteket. A PNG pontos méreteket őriz. + +## 7. lépés: Legjobb gyakorlatok a vonalkód kép méretéhez és teljesítményhez + +| Ajánlás | Ok | +|----------------|--------| +| Tartsd a `x_dimension.pixels` értékét 2‑3 px között a legtöbb szkennerhez. | Kiegyensúlyozza az olvashatóságot és a fájlméretet. | +| Használj PNG-t veszteségmentes kimenethez, ha a képet nyomtatni fogod. | Biztosítja a pontos méreteket és a tiszta éleket. | +| Használd újra egyetlen `BarCodeGenerator` példányt sok vonalkód generálásakor. | Csökkenti az objektum‑allokáció terhelését. | +| Érvényesítsd a bemeneti karakterláncot a GS1 szabvány szerint, mielőtt a `CodeText`-hez rendelnéd. | Megakadályozza a futásidejű kivételeket és az érvénytelen beolvasásokat. | +| Tárold a generált képeket egy dedikált mappában, egyértelmű elnevezési konvencióval (pl. `Databar_{GTIN}.png`). | Egyszerűsíti a későbbi feldolgozást és az audit nyomvonalakat. | + +## Teljes működő példa + +Az alábbiakban a teljes program látható, amely magában foglalja az összes lépést az inicializálástól az ellenőrzésig. Másold a kódot egy új konzol projektbe és futtasd. + + + +## Mit érdemes következőként megtanulni? + +A következő tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljes működő kódrészleteket lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Vonalkód kép generálása – GS1 Kupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode vonalkód kép létrehozása – sorok és oszlopok (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Hogyan hozzunk létre vonalkód csendes zónát ITF-14-hez az Aspose.BarCode for .NET használatával](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hungarian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/hungarian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..5a3de4291 --- /dev/null +++ b/barcode/hungarian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-08-12 +description: Hozzon létre omnidirekcionális databar kódot Pythonban, és tanulja meg, + hogyan készítsen vonalkód képet Pythonban az Aspose.BarCode segítségével. Kövesse + a lépésről‑lépésre útmutatót a teljes megoldáshoz. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: hu +lastmod: 2026-08-12 +og_description: Készíts omnidirekcionális databar kódot Pythonban, és generálj vonalkód + képet percek alatt. Ez az útmutató egy teljes, futtatható példát mutat be. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Készíts többirányú adatbárt – teljes Python útmutató +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Omnidirekcionális databar és vonalkód kép létrehozása Pythonban +url: /hu/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Omni‑directional DataBar és vonalkódkép létrehozása Pythonban + +Ha **omni directional databar**‑t szeretnél létrehozni egy Python‑projektben, ez az útmutató megmutatja, hogyan teheted meg, valamint hogyan **hozhatsz létre vonalkódképet Pythonban** az Aspose.BarCode könyvtár segítségével. Kész, azonnal futtatható szkriptet kapsz, amely két különböző képarányú PNG‑fájlt hoz létre. + +Az Omni‑directional specifikációnak megfelelő DataBar generálása gyakori igény a kiskereskedelmi és logisztikai alkalmazásokban. A tutorial bemutatja a telepítést, az X‑dimenzió beállítását, a képarány módosítását és a végső képek mentését. Külső szolgáltatásra nincs szükség; minden helyben fut. + +## Amire szükséged lesz + +Mielőtt elkezdenéd, győződj meg róla, hogy: + +* Python 3.8 vagy újabb telepítve van a gépeden. +* Hozzáférésed van egy terminálhoz vagy parancssorhoz. +* Írási jogosultságod van egy olyan mappához, ahová a vonalkódképeket menteni szeretnéd. + +Az egyetlen harmadik‑fél függőség a **Aspose.BarCode for Python via .NET**, amely alapból támogatja az Omni‑directional DataBar típust. + +## 1. lépés: Aspose.BarCode telepítése Pythonhoz + +Az Aspose.BarCode biztosítja a példakódban használt `BarcodeGenerator` osztályt. Telepítsd a csomagot a `pip`‑kel: + +```bash +pip install aspose-barcode +``` + +A csomag tartalmazza a szükséges .NET futtatókörnyezet kötéseket, így nem kell külön .NET SDK‑t telepítened. + +## 2. lépés: Könyvtár importálása és a generátor létrehozása + +A szkript első sorában egy generátort hozunk létre egy stacked Omni‑directional DataBar‑hoz. Mintadatként a GTIN‑14 értéket `(01)12345678901231` használjuk. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Miért fontos ez a lépés*: Az `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` konstans azt mondja a könyvtárnak, hogy a értéket Omni‑directional DataBar‑ként kódolja, ami sok POS‑olvasó számára kötelező formátum. + +## 3. lépés: X‑dimenzió (modulszélesség) beállítása + +Az X‑dimenzió határozza meg a legkisebb vonalmodul szélességét. A `2` pixel érték tiszta, jól olvasható vonalkódot eredményez túl nagy fájlméret nélkül. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Miért fontos ez a lépés*: Az X‑dimenzió finomhangolásával egyensúlyba hozhatod az olvashatóságot és a kép méreteit. Túl kicsi X‑dimenzió rosszul jelenhet meg alacsony felbontású nyomtatókon. + +## 4. lépés: Képarány konfigurálása és az első kép mentése + +A képarány befolyásolja a DataBar magasságát a szélességhez képest. A `15` képarány kompakt vizuális stílust eredményez. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Pro tipp**: Használd a `pathlib.Path`‑t a kimeneti útvonal építéséhez, amely automatikusan létrehozza a hiányzó könyvtárakat. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## 5. lépés: Képarány módosítása a második vizuális stílushoz és egy másik kép mentése + +A képarány `30`‑ra állítása magasabb vonalkódot eredményez, ami egyes szkennerhardvereknél kötelező lehet. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Miért fontos ez a lépés*: Különböző kiskereskedők és szkennereszközök eltérő méretkorlátozásokkal rendelkeznek. A két képarány egyetlen szkriptben való biztosítása lehetővé teszi a pontos stílus generálását kódduplicáció nélkül. + +## Teljes szkript – omni directional databar és vonalkódkép Pythonban + +Az alábbiakban a teljes, futtatható példakód látható, amely tartalmazza az összes korábbi lépést. Mentsd `generate_databar.py` néven, majd futtasd a `python generate_databar.py` paranccsal. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Várható kimenet + +A szkript futtatása a következő fájlokat hozza létre: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Mindkét kép egy érvényes Omni‑directional DataBar‑t jelenít meg, amelyet a szabványos kiskereskedelmi berendezések képesek beolvasni. + +![példa omni directional databar vonalkódkép Pythonban](example_databar.png "omni directional databar vonalkódkép Python") + +*Az előző kép csak egy helyőrző, amely a két mentett PNG‑fájlt szemlélteti.* + +## Gyakori problémák kezelése + +| Probléma | Ok | Megoldás | +|----------|----|----------| +| `ImportError: No module named aspose` | Az Aspose.BarCode nincs telepítve, vagy másik környezetben van. | Aktiváld a megfelelő virtuális környezetet, és futtasd a `pip install aspose-barcode` parancsot. | +| `PermissionError` mentéskor | A szkriptnek nincs írási joga a célmappához. | Válassz egy saját mappát, vagy futtasd a szkriptet megfelelő jogosultságokkal. | +| A vonalkód nem olvasható | Az X‑dimenzió túl alacsony, vagy a képarány nem kompatibilis a szkennerrel. | Növeld az `x_dimension.pixels` értékét 3‑ra vagy 4‑re, és próbálj ki más `aspect_ratio` értékeket (pl. 20, 25). | +| Hiányzó .NET futtatókörnyezet | Az Aspose.BarCode .NET futtatókörnyezetet igényel Windows‑on/Linux‑on. | Telepítsd a legújabb .NET futtatókörnyezetet a Microsoft oldaláról; a csomag dokumentációja platform‑specifikus útmutatót tartalmaz. | + +## A példa bővítése + +A szkriptet módosíthatod más DataBar változatok (pl. `DATABAR_STACKED`, `DATABAR_EXPANDED`) generálására. Cseréld ki az `EncodeTypes` konstansot ennek megfelelően: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Ha a vonalkódot PDF‑be szeretnéd beágyazni, az Aspose.PDF for Python közvetlenül importálhatja a PNG‑fájlt, vagy használhatod a `save` metódust `BarCodeImageFormat.Pdf` paraméterrel. + +## Összegzés + +Ez a tutorial bemutatta, hogyan **hozz létre omni directional databar**‑t és hogyan **hozz létre vonalkódképet Pythonban** az Aspose.BarCode segítségével. Most már rendelkezel egy teljes, reprodukálható szkripttel, amely két különböző képarányú PNG‑fájlt generál, kezeli a gyakori buktatókat, és könnyen bővíthető más vonalkódformátumokra. + +Ezután fedezd fel a QR‑kódok generálását, a vonalkód PDF‑számlákba való beillesztését, vagy a nagy termékkatalógusok kötegelt feldolgozásának automatizálását. Mindegyik téma az itt bemutatott `BarcodeGenerator` mintára épül. Jó kódolást! + + +## Mit érdemes legközelebb megtanulni? + + +Az alábbi tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutató technikáira épülnek. Minden forrás komplett, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy elsajátíthasd az API további funkcióit, és alternatív megvalósítási megközelítéseket alkalmazhass saját projektjeidben. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to create barcode image and render it in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/hungarian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/hungarian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..d0fb3ec7f --- /dev/null +++ b/barcode/hungarian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Hogyan generáljunk gyorsan vonalkódot Python használatával. Tanulja meg, + hogyan hozhat létre vonalkódot adatból, és exportálja a vonalkód képet egyetlen + könyvtárral. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: hu +lastmod: 2026-08-12 +og_description: Hogyan generáljunk vonalkódot Pythonban az Aspose.BarCode segítségével. + Kövesse ezt az útmutatót, hogy adatból vonalkódot hozzon létre, és exportálja a + vonalkód képet PNG formátumban. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Hogyan generáljunk vonalkódot Pythonban – gyors, megbízható útmutató +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Hogyan generáljunk vonalkódot Pythonban – teljes lépésről lépésre útmutató +url: /hu/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan generáljunk vonalkódot Pythonban – teljes lépésről‑lépésre útmutató + +Ha **hogyan generáljunk vonalkódot** kell egy Python alkalmazásban, ez a tutorial megmutatja a pontos kódot, amire szükséged van. Megtanulod, hogyan **hozz létre vonalkódot adatból**, állítsd be a megjelenését, és **exportáld a vonalkód képet** PNG fájlként – mindezt tíz sor kódban. + +A vonalkód generálása úgy érezhető, mintha különálló feladat lenne az üzleti logikádtól, de egyetlen könyvtárral a folyamatot beágyazhatod a meglévő kódbázisba. A következő szakaszokban egy teljes, futtatható példát látsz, megérted, miért fontos minden sor, és felfedezed a gyakori variációkat, például a modul szélességének módosítását vagy egy csak körvonalas vonalkód rajzolását. + +## Hogyan generáljunk vonalkódot az Aspose.BarCode könyvtárral + +Az Aspose.BarCode könyvtár Pythonhoz (a .NET-en keresztül) egyszerű API-t biztosít számos szimbólumhoz, beleértve a jelen útmutatóban használt Planet vonalkódot. Mielőtt elkezdenéd, győződj meg róla, hogy a csomag telepítve van: + +```bash +pip install aspose-barcode +``` + +> **Pro tipp:** Használj virtuális környezetet, hogy elkerüld a verzióütközéseket más projektekkel. + +### 1. Importáld a szükséges osztályokat + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Ezek az importok hozzáférést biztosítanak a generátor osztályhoz, a vonalkód típusok felsorolásához, és a képfájl formátum enumhoz, amelyet a mentéskor használsz. + +### 2. Hozz létre vonalkódot adatból + +Az első lépés a **vonalkód létrehozása adatból**. A `BarcodeGenerator` konstruktor a szimbólumot és a kódolni kívánt nyers karakterláncot várja. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +Az `EncodeTypes.Planet` érték a Planet vonalkódot választja, míg a `"123456"` a payload, amely a végső képen megjelenik. + +### 3. Állítsd be az X‑dimenziót (modul szélesség) + +Az X‑dimenzió szabályozza egy vonalkód modul (a vékony vonal) szélességét. 4 pixelre állítva tiszta, olvasható képet kapsz anélkül, hogy a fájl túl nagy lenne. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Miért fontos:** A nagyobb X‑dimenzió javítja a beolvasás megbízhatóságát alacsony felbontású nyomtatókon, míg a kisebb érték csökkenti a fájlméretet webes használathoz. + +### 4. Exportáld a vonalkód képet (kitöltött stílus) + +Most **exportálhatod a vonalkód képet** a `save` metódussal. A példa PNG fájlt ment, de a `BarCodeImageFormat` enum módosításával választhatsz JPEG, BMP vagy TIFF formátumot is. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +A `PlanetFilled.png` fájl egy teljesen kitöltött Planet vonalkódot tartalmaz, amely készen áll a nyomtatásra vagy PDF-be ágyazásra. + +### 5. Hozz létre egy második generátort csak körvonalas vonalkódhoz + +Ha egy csak körvonalas változatra (üres vonalak) van szükséged, új generátort kell létrehoznod, mert a `filled_bars` flag-et nem lehet a kép mentése után módosítani. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Alkalmazd ugyanazt az X‑dimenzió beállítást + +Amikor második generátort hozol létre, ismételni kell minden vizuális beállítást, amelyet konzisztensen szeretnél használni. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Tiltsd le a kitöltött vonalakat egy körvonalas vonalkódhoz + +A `filled_bars` `False` értékre állítása azt mondja a renderelőnek, hogy csak a modulok körvonalait rajzolja, így könnyebb képet kapunk, amely tervezési célokra hasznos lehet. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Exportáld a körvonalas vonalkód képet + +Végül **exportáld a vonalkód képet** újra, ezúttal a körvonalas változatot tárolva. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Most már két PNG fájlod van: az egyik szilárd vonalakkal (`PlanetFilled.png`), a másik csak körvonalakkal (`PlanetEmpty.png`). + +## Exportáld a vonalkód képet más formátumokban (opcionális) + +A `save` metódus több formátumot támogat. JPEG‑ként 90 % minőséggel exportáláshoz: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Ha átlátszó háttérre van szükséged webes használathoz, válaszd a PNG‑t alfa csatornával: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Gyakori variációk és szélhelyzetek + +| Szenárió | Szükséges módosítás | Kódrészlet | +|----------|---------------------|------------| +| **Másik szimbólum** (pl. QR) | Használj másik `EncodeTypes` értéket | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Egyedi előtérszín** | Állítsd be a `fore_color`‑t | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Magasabb felbontás** | Növeld a DPI‑t az `image_width` és `image_height` segítségével | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Nagy adatkarakterláncok** | Győződj meg róla, hogy az adat hossza illeszkedik a szimbólum specifikációjához | Validate length before creating the generator | + +> **Vigyázz:** Ha olyan adatot adsz meg, amely meghaladja a kiválasztott szimbólum maximális hosszát, futásidejű kivétel keletkezik. Mindig ellenőrizd a karakterlánc hosszát, vagy kezeld a `ArgumentException`‑t. + +## Teljes, futtatható példa + +Az alábbi teljes szkriptet másold be egy `generate_planet_barcode.py` nevű fájlba. A `YOUR_DIRECTORY`‑t állítsd be egy létező mappára a gépeden. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +A szkript futtatása két PNG fájlt hoz létre a megadott könyvtárban. Ellenőrizd a kimenetet bármely képmegjelenítővel; mindkettőnek egy `123456` karakterláncot kódoló Planet vonalkódot kell mutatnia. + +## Összegzés + +Most már tudod, **hogyan generáljunk vonalkódot** Pythonban az Aspose.BarCode használatával, hogyan **hozz létre vonalkódot adatból**, és hogyan **exportáld a vonalkód képet** mind kitöltött, mind körvonalas stílusban. Ugyanez a minta alkalmazható más szimbólumokra, képfájl formátumokra és vizuális testreszabásokra, rugalmas alapot biztosítva minden vonalkód‑kapcsolódó funkcióhoz az alkalmazásodban. + +### Következő lépések + +* Fedezd fel a többi szimbólumot, például QR, Code‑128 vagy DataMatrix, a `EncodeTypes.Planet` helyettesítésével a kívánt értékkel. +* Integráld a generált PNG fájlokat PDF jelentésekbe olyan könyvtárakkal, mint a `ReportLab` vagy a `PyPDF2`. +* Kísérletezz dinamikus X‑dimenzió értékekkel, hogy a vonalkód méretét a képernyő felbontása vagy a nyomtató DPI‑ja alapján állítsd be. + +Boldog kódolást, és nyugodtan igazítsd a példát a saját projekted igényeihez! + +## Mit tanulj meg legközelebb? + +A következő tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás komplett, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/indonesian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/indonesian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..a59d16aae --- /dev/null +++ b/barcode/indonesian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,296 @@ +--- +category: general +date: 2026-08-12 +description: Contoh generator barcode yang menunjukkan cara menghasilkan barcode dengan + ukuran piksel yang tepat. Pelajari cara mengatur lebar modul, tinggi bar, dan membuat + barcode Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: id +lastmod: 2026-08-12 +og_description: Contoh generator barcode menunjukkan cara menghasilkan barcode dengan + dimensi piksel yang tepat. Ikuti panduan ini untuk mengontrol lebar modul dan tinggi + bar untuk kode Planet dan RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: contoh generator barcode – sesuaikan ukuran piksel di C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Contoh generator barcode – panduan langkah demi langkah untuk ukuran piksel + khusus +url: /id/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# contoh generator barcode – panduan langkah‑demi‑langkah untuk ukuran piksel khusus + +Jika Anda membutuhkan **contoh generator barcode** yang memungkinkan Anda mengontrol setiap piksel, panduan ini menunjukkan secara tepat cara melakukannya. Anda akan belajar mengatur lebar modul, menentukan tinggi bar yang tetap, dan menghasilkan barcode Planet serta RM4SCC dengan dimensi yang dapat diprediksi. + +Sebagian besar pengembang mengalami kesulitan dengan gambar “cara menghasilkan barcode” yang terlihat sama di setiap layar atau printer. Potongan kode di bawah ini menyelesaikan masalah tersebut dengan mengekspos parameter tingkat piksel dari pustaka Aspose.BarCode untuk .NET, sehingga Anda dapat menghasilkan output yang konsisten tanpa tebak‑tebakan. + +## Apa yang akan Anda pelajari + +* Cara menginstal paket NuGet yang diperlukan. +* Cara menghasilkan barcode Planet dengan tinggi yang dihitung secara otomatis. +* Cara menghasilkan barcode Planet dengan tinggi 100 piksel yang eksplisit. +* Cara menghasilkan barcode RM4SCC menggunakan tinggi eksplisit yang sama. +* Mengapa **ukuran piksel barcode** penting untuk keandalan pemindaian. +* Tips untuk memecahkan masalah umum saat Anda menghasilkan gambar barcode Planet. + +Anda hanya memerlukan .NET 6 atau yang lebih baru, lingkungan pengembangan C# dasar, dan koneksi internet untuk mengunduh paket NuGet. + +--- + +## contoh generator barcode – menyiapkan lingkungan pengembangan + +Sebelum menulis kode apa pun, pastikan pustaka Aspose.BarCode tersedia untuk proyek Anda. + +### Instal paket Aspose.BarCode + +Buka terminal di folder proyek Anda dan jalankan: + +```bash +dotnet add package Aspose.BarCode +``` + +Perintah ini menambahkan versi stabil terbaru dari **Aspose.BarCode** ke `csproj` Anda. Setelah proses pemulihan selesai, Anda dapat mulai menggunakan kelas `BarcodeGenerator`. + +> **Pro tip:** Target .NET 6 atau .NET 7 untuk mendapatkan manfaat dari peningkatan performa terbaru dan penanganan default UTF‑8. + +### Tambahkan direktif `using` yang diperlukan + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Namespace ini mengekspos kelas `BarcodeGenerator` dan enum `BarCodeImageFormat` yang akan digunakan nanti dalam tutorial. + +--- + +## Cara menghasilkan barcode dengan ukuran piksel khusus + +Tiga langkah berikut menggambarkan **contoh generator barcode** secara lengkap. Setiap langkah membangun dari langkah sebelumnya, sehingga Anda dapat menyalin‑tempel seluruh blok ke dalam aplikasi konsol dan menjalankannya tanpa perubahan. + +### Langkah 1 – menghasilkan barcode Planet dengan tinggi yang dihitung secara otomatis + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Mengapa ini berhasil:** +*Properti `XDimension` menentukan lebar satu modul barcode (elemen hitam atau putih terkecil). Ketika Anda tidak menyertakan `BarHeight`, pustaka menghitung tinggi yang mempertahankan rasio aspek standar untuk kode Planet.* + +**Output yang diharapkan:** File PNG bernama `PlanetAuto.png` yang berisi barcode Planet yang bersih. Tingginya menyesuaikan lebar modul 4 piksel, biasanya sekitar 60 piksel untuk payload enam karakter. + +### Langkah 2 – menghasilkan barcode Planet dengan tinggi 100 piksel yang eksplisit + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Mengapa Anda mungkin memerlukan ini:** +Kadang perangkat pemindai mengharapkan tinggi bar minimum untuk deteksi yang dapat diandalkan. Dengan mengatur `BarHeight.Pixels`, Anda menjamin setiap gambar yang dihasilkan memenuhi persyaratan tersebut, terlepas dari panjang data yang dikodekan. + +**Output yang diharapkan:** `PlanetHeight100.png` menampilkan data yang sama seperti sebelumnya, tetapi bar memiliki tinggi tepat 100 piksel, memberi Anda kontrol penuh atas ukuran visual. + +### Langkah 3 – menghasilkan barcode RM4SCC dengan tinggi eksplisit yang sama + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Mengapa ini penting:** +`EncodeTypes.RM4SCC` adalah barcode linear bertumpuk yang digunakan dalam logistik. Menyelaraskan tinggi bar-nya dengan barcode Planet menyederhanakan pemrosesan batch ketika kedua simbol muncul pada label yang sama. + +**Output yang diharapkan:** `RM4SCCHeight100.png` menampilkan barcode RM4SCC dengan ukuran sempurna, cocok dengan tinggi 100 piksel yang Anda tetapkan untuk kode Planet. + +> **Verifikasi hasil:** Buka setiap PNG di penampil gambar dan pastikan bar hitam berukuran tepat 4 piksel lebar dan, jika Anda menentukan, 100 piksel tinggi. Anda juga dapat memasukkan file ke aplikasi pemindai barcode untuk memastikan mereka terdekripsi menjadi “123456”. + +--- + +## Memahami ukuran piksel barcode dan tinggi bar + +### Apa itu **ukuran piksel barcode**? + +*Ukuran piksel* mengacu pada jumlah fisik piksel layar atau printer yang mewakili satu modul (`XDimension`). Ukuran piksel yang lebih besar menghasilkan barcode yang lebih besar, yang dapat lebih mudah bagi pemindai beresolusi rendah tetapi mengonsumsi lebih banyak ruang pada label. + +### Bagaimana `BarHeight` memengaruhi keterbacaan? + +Properti `BarHeight` mengontrol panjang vertikal bar. Standar untuk kebanyakan barcode 1‑D (termasuk Planet dan RM4SCC) merekomendasikan tinggi minimum 10 mm saat dicetak pada 300 dpi, yang kira‑kira setara dengan 118 piksel. Menetapkan tinggi di bawah itu dapat menyebabkan kesalahan pembacaan, terutama pada kamera seluler. + +### Kapan Anda harus membiarkan pustaka menghitung tinggi secara otomatis? + +Jika Anda menghasilkan barcode hanya untuk tampilan di layar, perhitungan otomatis menjaga rasio aspek tetap konsisten dan mengurangi jumlah penyesuaian manual yang diperlukan. Untuk label cetak yang harus memenuhi spesifikasi ISO yang ketat, Anda harus **menetapkan tinggi bar secara eksplisit**. + +--- + +## Kesalahan umum dan praktik terbaik saat Anda menghasilkan barcode Planet + +| Kesalahan | Mengapa terjadi | Solusi | +|-----------|----------------|--------| +| Bar muncul terlalu tipis atau terlalu tebal | `XDimension` dibiarkan pada default (1 piksel) pada tampilan resolusi tinggi | Setel `XDimension.Pixels` minimal 3‑4 untuk kejelasan visual | +| Pemindai tidak dapat membaca kode | `BarHeight` terlalu kecil untuk panjang fokus pemindai | Gunakan `BarHeight.Pixels` ≥ 100 untuk kebanyakan pemindai seluler | +| Gambar menjadi buram setelah skala | Menyimpan sebagai JPEG memperkenalkan artefak kompresi | Simpan sebagai PNG (`BarCodeImageFormat.Png`) untuk output tanpa kehilangan | +| Tipe barcode tidak terduga | Nilai enum `EncodeTypes` salah | Periksa kembali bahwa Anda menggunakan `EncodeTypes.Planet` untuk simbol Planet | + +### Pro tip tentang kinerja + +Saat menghasilkan ribuan barcode dalam pekerjaan batch, gunakan kembali satu instance `BarcodeGenerator` dan hanya ubah `CodeText` serta parameter ukuran di antara penyimpanan. Ini menghindari alokasi berulang objek rendering internal dan dapat mengurangi waktu eksekusi hingga 30 %. + +--- + +## Contoh lengkap yang berfungsi – gabungkan semuanya + +Buat proyek konsol baru (`dotnet new console -n BarcodeDemo`) dan ganti isi `Program.cs` dengan yang berikut: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Jalankan program dengan `dotnet run`. Setelah eksekusi Anda akan menemukan tiga file PNG di folder proyek, masing‑masing menggambarkan skenario **contoh generator barcode** yang berbeda. + +--- + +## Langkah selanjutnya dan topik terkait + +* **Cara menghasilkan barcode dalam format lain** – jelajahi `EncodeTypes.Code128`, `EncodeTypes.QR`, dan `EncodeTypes.DataMatrix` untuk kebutuhan 2‑D. +* **Menyematkan barcode dalam PDF** – gabungkan Aspose.BarCode dengan Aspose.PDF untuk menempatkan barcode langsung pada templat faktur. +* **Ukuran barcode dinamis berdasarkan input pengguna** – hitung + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Cara menghasilkan barcode java: Membuat Gambar Barcode yang Tepat](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [Cara Menghasilkan Barcode di Java Membuat dan Menetapkan Ukuran untuk Gambar Utuh](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [Cara membuat barcode code128 di Java dan mengatur tinggi bar](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/indonesian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/indonesian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..808601893 --- /dev/null +++ b/barcode/indonesian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-08-12 +description: Konfigurasikan tata letak kode batang Databar di Python dengan cepat. + Pelajari cara mengatur kolom, baris, dan menyimpan gambar dengan perpustakaan generator + kode batang. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: id +lastmod: 2026-08-12 +og_description: Konfigurasikan tata letak barcode Databar di Python untuk mengontrol + kolom, baris, dan output gambar. Ikuti panduan ini untuk solusi siap dijalankan. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Konfigurasikan tata letak kode batang Databar di Python – tutorial lengkap +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Konfigurasikan tata letak kode batang Databar di Python – panduan langkah demi + langkah +url: /id/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konfigurasikan tata letak barcode Databar di Python – panduan langkah demi langkah + +Jika Anda perlu **mengonfigurasi tata letak barcode Databar di Python**, panduan ini akan membawa Anda melalui seluruh proses. Anda akan melihat cara mengatur jumlah kolom atau baris untuk barcode Databar Expanded Stacked dan cara menyimpan gambar yang dihasilkan dengan satu panggilan ke pustaka generator barcode. + +Mengendalikan tata letak sangat penting ketika Anda menyematkan barcode pada kemasan sempit, struk, atau layar seluler. Pada bagian di bawah ini kami akan membahas impor yang diperlukan, dua opsi tata letak (kolom dan baris), serta praktik terbaik untuk menyimpan gambar PNG yang bersih. + +## Apa yang Anda butuhkan + +Sebelum memulai, pastikan Anda memiliki: + +* Python 3.8 atau lebih baru +* `aspose.barcode` (atau paket generasi barcode yang kompatibel) terpasang + ```bash + pip install aspose-barcode + ``` +* Izin menulis ke folder tempat file PNG akan disimpan + +Tidak ada alat eksternal tambahan yang diperlukan—pustaka menangani rendering, skala, dan enkoding gambar secara internal. + +## Cara mengonfigurasi tata letak barcode Databar di Python + +Inti solusi adalah kelas `BarcodeGenerator`. Kelas ini menerima enum `EncodeTypes` yang mengidentifikasi simbolologi barcode—dalam kasus ini `EncodeTypes.DatabarExpandedStacked`. Setelah membuat generator, Anda dapat menyesuaikan tata letak dengan mengatur properti `columns` atau `rows` pada objek parameter `data_bar`. + +### Langkah 1: Impor kelas yang diperlukan + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Impor ini memberi Anda akses ke generator, enumerasi untuk tipe Databar, dan konstanta format gambar PNG. + +### Langkah 2: Buat generator barcode untuk Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Mengapa langkah ini?* +`EncodeTypes.DatabarExpandedStacked` memberi tahu pustaka untuk menghasilkan simbolologi **Databar Expanded Stacked**, yang mendukung string numerik lebih panjang sambil tetap memiliki jejak kompak. Argumen kedua adalah data yang akan dienkode; dapat berupa string apa pun yang memenuhi spesifikasi Databar. + +### Langkah 3: Atur jumlah kolom (tata letak horizontal) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**atur kolom barcode** adalah frasa kunci untuk operasi ini. Ketika Anda meningkatkan jumlah kolom, barcode menyebar secara horizontal, yang dapat berguna untuk label lebar. Pustaka secara otomatis menghitung ulang lebar modul untuk menjaga ukuran keseluruhan tetap konsisten. + +#### Tips pro +Jumlah kolom maksimum untuk Databar Expanded Stacked adalah 8. Menetapkan nilai lebih tinggi dari batas akan dipotong ke maksimum, tetapi sebaiknya validasi masukan Anda terlebih dahulu. + +### Langkah 4: Simpan gambar barcode dengan tata letak kolom + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**simpan gambar barcode** adalah tindakan yang menulis barcode yang dirender ke disk. PNG bersifat lossless, sehingga mempertahankan tepi tajam yang diperlukan untuk pemindaian yang dapat diandalkan. + +### Langkah 5: Buat generator kedua untuk tipe barcode yang sama (tata letak baris) + +Jika Anda lebih suka tumpukan vertikal, Anda bekerja dengan baris alih-alih kolom. Kode di bawah ini menggunakan kembali nilai yang sama tetapi membuat instance `BarcodeGenerator` baru untuk menghindari pencampuran pengaturan kolom dan baris. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Langkah 6: Atur jumlah baris (tata letak vertikal) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**atur baris barcode** menyusun modul barcode secara vertikal. Tata letak tiga baris mengurangi tinggi setiap tumpukan individu, menjadikan barcode cocok untuk struk sempit atau layar seluler. + +#### Kasus khusus +Jika Anda menetapkan `rows` ke 1, pustaka menghasilkan Databar satu‑baris (setara dengan Databar standar). Nilai di bawah 1 diabaikan dan direset ke nilai default (1 baris). + +### Langkah 7: Simpan gambar barcode dengan tata letak baris + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Sekali lagi, kami **simpan gambar barcode** menggunakan PNG agar output tetap tajam. + +## Contoh lengkap yang dapat dijalankan + +Menggabungkan semua bagian memberikan Anda skrip mandiri yang dapat ditempatkan ke proyek Python mana pun. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Output yang diharapkan** + +Menjalankan skrip akan membuat dua file PNG: + +* `output/ExpandedCols4.png` – barcode yang diperluas ke empat kolom +* `output/ExpandedRows3.png` – barcode yang dipadatkan menjadi tiga baris + +Kedua gambar dapat dibuka di penampil gambar apa pun atau diimpor langsung ke faktur PDF, templat label, atau halaman web. + +## Pertanyaan umum dan pemecahan masalah + +| Pertanyaan | Jawaban | +|----------|--------| +| *Bagaimana jika barcode terlihat buram?* | Tingkatkan resolusi gambar dengan mengatur `barcode_generator.parameters.image_width` dan `image_height` sebelum memanggil `save`. | +| *Apakah saya dapat menggunakan format gambar lain?* | Ya. Ganti `BarCodeImageFormat.Png` dengan `Jpeg`, `Bmp`, atau `Gif` sesuai kebutuhan. | +| *Apakah ada batas panjang data?* | Databar Expanded Stacked mendukung hingga 74 karakter numerik. Melebihi batas akan memunculkan `ArgumentException`. | +| *Bagaimana cara mengubah warna latar depan?* | Gunakan `barcode_generator.parameters.barcode.color = Color.Blue` (impor `System.Drawing.Color`). | +| *Bisakah saya menggabungkan kolom dan baris?* | Tidak. API memperlakukan kolom dan baris sebagai mode tata letak yang saling eksklusif. Pilih satu per instance barcode. | + +## Langkah selanjutnya + +Sekarang Anda dapat **mengonfigurasi tata letak barcode Databar**, pertimbangkan untuk menjelajahi topik terkait berikut: + +* **Tambahkan keterangan teks** – gunakan `barcode_generator.parameters.barcode.code_text` untuk menampilkan nilai yang dienkode di bawah gambar. +* **Sematkan barcode dalam PDF** – gabungkan PNG yang dihasilkan dengan `aspose.pdf` untuk membuat dokumen yang dapat dicetak. +* **Ukuran dinamis** – hitung jumlah kolom atau baris optimal berdasarkan dimensi label pada waktu berjalan. +* **Pemrosesan batch** – iterasi melalui CSV kode produk untuk menghasilkan perpustakaan gambar barcode secara otomatis. + +Bereksperimenlah dengan nilai kolom dan baris yang berbeda untuk melihat bagaimana mereka memengaruhi keandalan pemindaian pada perangkat target Anda. Semakin banyak Anda menguji, semakin baik Anda memahami trade‑off antara ukuran barcode, keterbacaan, dan keterbatasan ruang. + +--- + +*Selamat coding! Jika Anda menemukan tutorial ini berguna, bagikan kepada rekan tim atau tinggalkan komentar tentang tantangan tata letak yang Anda hadapi.* + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait dan membangun pada teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Buat gambar barcode DotCode – baris & kolom (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Buat gambar barcode c# – Konfigurasikan Baris & Kolom Codablock F](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [Penyesuaian Tinggi Barcode Databar Satu Dimensi](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/indonesian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/indonesian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..8c1730541 --- /dev/null +++ b/barcode/indonesian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: Buat gambar barcode di C# menggunakan BarCodeGenerator. Pelajari cara + menghasilkan DataBar, mengontrol ukuran gambar barcode, dan membuat banyak barcode + secara efisien. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: id +lastmod: 2026-08-12 +og_description: Buat gambar barcode di C# dengan BarCodeGenerator. Tutorial ini menunjukkan + langkah demi langkah cara menghasilkan kode DataBar, menyesuaikan ukuran gambar + barcode, dan menghasilkan beberapa barcode. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Buat gambar barcode di C# – panduan lengkap BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Buat gambar barcode di C# dengan BarCodeGenerator +url: /id/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat gambar barcode di C# dengan BarCodeGenerator + +Jika Anda perlu **membuat gambar barcode** dalam aplikasi .NET, panduan ini menunjukkan secara tepat cara melakukannya dengan kelas `BarCodeGenerator`. Baik Anda sedang membangun sistem POS ritel atau alat pelacakan inventaris, Anda akan belajar menghasilkan simbol DataBar, mengontrol ukuran gambar barcode, dan menghasilkan beberapa barcode dalam satu kali proses. + +Anda juga akan menemukan bagaimana API **barcode generator c#** memungkinkan Anda menyesuaikan dimensi, mengubah format output, dan menangani kasus tepi seperti string data yang tidak valid. Pada akhir tutorial Anda dapat dengan yakin **membuat banyak barcode** tanpa menulis kode yang berulang. + +## Prasyarat + +- .NET 6.0 atau yang lebih baru terinstal +- Lingkungan pengembangan (Visual Studio, Rider, atau VS Code) +- Paket NuGet Aspose.BarCode untuk .NET (atau perpustakaan kompatibel lain yang menyediakan `BarCodeGenerator`) + +Anda dapat menambahkan paket dengan: + +```bash +dotnet add package Aspose.BarCode +``` + +## Apa yang dibahas dalam tutorial ini + +1. Menyiapkan instance **barcode generator c#** untuk enkoding DataBar Omni‑directional. +2. Menyesuaikan **ukuran gambar barcode** dengan mengubah X‑dimension dan tinggi bar. +3. Menggunakan loop untuk **membuat banyak barcode** dengan tinggi yang berbeda. +4. Menyimpan gambar sebagai file PNG dan memverifikasi output. + +Semua potongan kode lengkap dan siap untuk disalin‑tempel ke dalam proyek konsol baru. + +![Create barcode image example](barcode-example.png){alt="Contoh gambar barcode"} + +## Langkah 1: Inisialisasi generator – dasar pembuatan gambar barcode + +Langkah pertama adalah menginstansiasi `BarCodeGenerator` dengan simbol yang diinginkan. Untuk simbol DataBar Omni‑directional Anda menggunakan `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Mengapa ini penting:** Menginstansiasi generator mendefinisikan aturan enkoding dan muatan data. Jika Anda melewatkan nilai `EncodeTypes` yang tepat, perpustakaan akan menghasilkan barcode yang tidak didukung atau melemparkan pengecualian. + +## Langkah 2: Konfigurasikan X‑dimension dan tinggi bar – kontrol ukuran gambar barcode + +Ukuran visual sebuah barcode dipengaruhi oleh dua parameter: + +| Parameter | Apa yang dikontrol | Rentang tipikal | +|-----------|--------------------|-----------------| +| `x_dimension.pixels` | Lebar modul terkecil (“titik”) | 1 – 4 px | +| `bar_height.pixels` | Tinggi bar vertikal | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Tips profesional:** X‑dimension yang lebih kecil menghasilkan gambar dengan resolusi lebih tinggi tetapi mungkin lebih sulit dipindai pada printer berkualitas rendah. Sesuaikan nilai tersebut berdasarkan peralatan pemindaian target Anda. + +## Langkah 3: Simpan barcode pertama – buat gambar barcode dengan tinggi 30 px + +Sekarang Anda dapat menghasilkan gambar dan menuliskannya ke disk. Metode `Save` menerima jalur file dan enum format gambar. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Hasil yang diharapkan:** File PNG bernama `Databar30.png` muncul di `C:\Barcodes`. Membuka file tersebut menampilkan simbol DataBar Omni‑directional dengan pola yang jelas dan kontras tinggi. + +## Langkah 4: Ubah tinggi dan hasilkan gambar tambahan – buat banyak barcode + +Untuk **membuat banyak barcode** dengan dimensi yang berbeda Anda hanya perlu mengubah properti `BarHeight` dan memanggil `Save` lagi. Ini menghindari penginstansian ulang generator, yang menghemat memori dan waktu CPU. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Mengapa ini berhasil:** Objek `BarCodeGenerator` menyimpan semua status konfigurasi. Mengubah satu properti memperbarui mesin rendering untuk panggilan `Save` berikutnya, memungkinkan Anda **membuat banyak barcode** secara efisien. + +## Langkah 5: Lanjutan – cara menghasilkan DataBar dengan data khusus + +Contoh di atas menggunakan payload GS1 statis. Dalam skenario dunia nyata Anda sering perlu menyematkan pengidentifikasi produk yang variabel. Perpustakaan menerima string apa pun yang sesuai dengan spesifikasi DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Poin penting:** Menetapkan `generator.CodeText` memperbarui data yang dienkode tanpa membuat ulang objek. Ini adalah pola **cara menghasilkan databar** yang direkomendasikan saat menangani kumpulan data besar. + +## Langkah 6: Verifikasi dan pemecahan masalah – memastikan ukuran gambar barcode yang tepat + +Setelah menghasilkan gambar, Anda mungkin ingin secara programatik memastikan bahwa dimensi sesuai dengan harapan Anda. Kelas `Image` dari `System.Drawing` dapat membaca file dan melaporkan ukurannya. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Jika tinggi tidak mencerminkan nilai yang Anda tetapkan, periksa: + +- **X‑dimension**: Nilai yang sangat kecil dapat menyebabkan renderer membulatkan tinggi. +- **Format gambar**: Beberapa format (mis., JPEG) menerapkan kompresi yang dapat mengubah dimensi piksel saat disimpan. PNG mempertahankan dimensi yang tepat. + +## Langkah 7: Praktik terbaik untuk ukuran gambar barcode dan kinerja + +| Rekomendasi | Alasan | +|-------------|--------| +| Pertahankan `x_dimension.pixels` antara 2 – 3 px untuk kebanyakan pemindai. | Menyeimbangkan keterbacaan dan ukuran file. | +| Gunakan PNG untuk output lossless ketika gambar akan dicetak. | Menjamin dimensi yang tepat dan tepi yang tajam. | +| Gunakan kembali satu instance `BarCodeGenerator` saat menghasilkan banyak barcode. | Mengurangi beban alokasi objek. | +| Validasi string input terhadap standar GS1 sebelum menetapkan ke `CodeText`. | Mencegah pengecualian runtime dan pemindaian yang tidak valid. | +| Simpan gambar yang dihasilkan dalam folder khusus dengan konvensi penamaan yang jelas (mis., `Databar_{GTIN}.png`). | Menyederhanakan proses downstream dan jejak audit. | + +## Contoh lengkap yang berfungsi + +Berikut adalah program lengkap yang menggabungkan semua langkah mulai dari inisialisasi hingga verifikasi. Salin kode ke dalam proyek konsol baru dan jalankan. + + + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang terkait erat yang membangun pada teknik yang ditunjukkan dalam panduan ini. Setiap sumber mencakup contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Hasilkan gambar barcode – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Buat gambar barcode DotCode – baris & kolom (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Cara Membuat Zona Tenang Barcode untuk ITF-14 Menggunakan Aspose.BarCode untuk .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/indonesian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/indonesian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..3ada08750 --- /dev/null +++ b/barcode/indonesian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-12 +description: Buat databar omnidirectional dengan Python dan pelajari cara membuat + gambar barcode Python menggunakan Aspose.BarCode. Ikuti panduan langkah demi langkah + untuk solusi lengkap. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: id +lastmod: 2026-08-12 +og_description: Buat databar omnidirectional dengan Python dan hasilkan gambar barcode + dalam hitungan menit. Tutorial ini menampilkan contoh lengkap yang dapat dijalankan. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Buat databar omnidirectional – panduan lengkap Python +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Buat gambar databar dan kode batang omni arah dengan Python +url: /id/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat Omni-directional Databar dan Gambar Barcode di Python + +Jika Anda perlu **membuat omni directional databar** dalam proyek Python, panduan ini menunjukkan cara melakukannya serta cara **membuat barcode image python** menggunakan pustaka Aspose.BarCode. Anda akan mendapatkan skrip siap‑jalankan yang menghasilkan dua file PNG dengan rasio aspek yang berbeda. + +Membuat DataBar yang mengikuti spesifikasi Omni‑directional merupakan kebutuhan umum untuk aplikasi ritel dan logistik. Tutorial ini mencakup instalasi, konfigurasi X‑dimension, penyesuaian rasio aspek, dan penyimpanan gambar akhir. Tidak ada layanan eksternal yang diperlukan; semuanya berjalan secara lokal. + +## Apa yang Anda butuhkan + +Sebelum memulai, pastikan Anda memiliki: + +* Python 3.8 atau yang lebih baru terpasang di mesin Anda. +* Akses ke terminal atau command prompt. +* Izin menulis ke folder tempat gambar barcode akan disimpan. + +Satu‑satunya ketergantungan pihak ketiga adalah **Aspose.BarCode for Python via .NET**, yang mendukung tipe Omni‑directional DataBar secara langsung. + +## Langkah 1: Instal Aspose.BarCode untuk Python + +Aspose.BarCode menyediakan kelas `BarcodeGenerator` yang digunakan dalam contoh kode. Instal paket dengan `pip`: + +```bash +pip install aspose-barcode +``` + +Paket ini menyertakan binding runtime .NET yang diperlukan, sehingga Anda tidak perlu menginstal .NET SDK secara terpisah. + +## Langkah 2: Impor pustaka dan buat generator + +Baris pertama skrip membuat generator untuk Omni‑directional DataBar bertumpuk. Nilai GTIN‑14 `(01)12345678901231` digunakan sebagai data contoh. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Mengapa langkah ini penting*: Konstanta `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` memberi tahu pustaka untuk mengkodekan nilai sebagai Omni‑directional DataBar, yang merupakan format yang dibutuhkan oleh banyak pemindai point‑of‑sale. + +## Langkah 3: Atur X‑dimension (lebar modul) + +X‑dimension menentukan lebar modul bar terkecil. Nilai `2` piksel menghasilkan barcode yang jelas dan dapat dibaca tanpa ukuran file yang berlebihan. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Mengapa langkah ini penting*: Menyesuaikan X‑dimension memungkinkan Anda menyeimbangkan keterbacaan dan dimensi gambar. X‑dimension yang terlalu kecil dapat menghasilkan kualitas buruk pada printer beresolusi rendah. + +## Langkah 4: Konfigurasikan rasio aspek dan simpan gambar pertama + +Rasio aspek memengaruhi tinggi keseluruhan DataBar relatif terhadap lebarnya. Rasio aspek `15` menciptakan gaya visual yang kompak. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Tip Pro**: Gunakan `pathlib.Path` untuk membangun jalur output, yang secara otomatis membuat direktori yang belum ada. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Langkah 5: Ubah rasio aspek untuk gaya visual kedua dan simpan gambar lain + +Mengubah rasio aspek menjadi `30` menghasilkan barcode yang lebih tinggi yang mungkin diperlukan oleh perangkat keras pemindai tertentu. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Mengapa langkah ini penting*: Retailer dan perangkat pemindai memiliki batasan ukuran yang berbeda. Menyediakan kedua rasio aspek dalam satu skrip memungkinkan Anda menghasilkan gaya yang tepat tanpa menduplikasi kode. + +## Skrip lengkap – buat omni directional databar dan gambar barcode python + +Berikut adalah contoh lengkap yang dapat dijalankan dan menggabungkan semua langkah sebelumnya. Simpan sebagai `generate_databar.py` dan jalankan dengan `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Output yang diharapkan + +Menjalankan skrip akan membuat file berikut: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Kedua gambar menampilkan Omni‑directional DataBar yang valid dan dapat dipindai oleh peralatan ritel standar. + +![contoh membuat omni directional databar gambar barcode di Python](example_databar.png "membuat omni directional databar gambar barcode python") + +*Gambar di atas adalah placeholder yang menggambarkan dua file PNG yang disimpan.* + +## Menangani masalah umum + +| Masalah | Alasan | Solusi | +|-------|--------|-----| +| `ImportError: No module named aspose` | Aspose.BarCode belum diinstal atau diinstal di lingkungan yang berbeda. | Aktifkan lingkungan virtual yang tepat dan jalankan `pip install aspose-barcode`. | +| `PermissionError` saat menyimpan | Skrip tidak memiliki izin menulis ke folder target. | Pilih direktori yang Anda miliki atau jalankan skrip dengan hak istimewa yang sesuai. | +| Barcode tidak dapat dipindai | X‑dimension terlalu rendah atau rasio aspek tidak kompatibel dengan pemindai. | Tingkatkan `x_dimension.pixels` menjadi 3 atau 4, dan coba nilai `aspect_ratio` lain (mis., 20, 25). | +| Runtime .NET tidak ada | Aspose.BarCode bergantung pada runtime .NET di Windows/Linux. | Instal runtime .NET terbaru dari situs Microsoft; dokumentasi paket menyediakan panduan khusus platform. | + +## Memperluas contoh + +Anda dapat menyesuaikan skrip untuk menghasilkan varian DataBar lain (mis., `DATABAR_STACKED`, `DATABAR_EXPANDED`). Ganti konstanta `EncodeTypes` sesuai kebutuhan: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Jika Anda perlu menyematkan barcode ke dalam PDF, Aspose.PDF for Python dapat mengimpor file PNG secara langsung atau Anda dapat menggunakan metode `save` dengan `BarCodeImageFormat.Pdf`. + +## Kesimpulan + +Tutorial ini menunjukkan cara **membuat omni directional databar** dan cara **membuat barcode image python** menggunakan Aspose.BarCode. Sekarang Anda memiliki skrip lengkap dan dapat direproduksi yang menghasilkan dua file PNG dengan rasio aspek berbeda, menangani jebakan umum, dan dapat diperluas ke format barcode lainnya. + +Selanjutnya, jelajahi pembuatan QR code, menambahkan barcode ke faktur PDF, atau mengotomatisasi pemrosesan batch untuk katalog produk besar. Semua topik tersebut dibangun di atas pola `BarcodeGenerator` yang sama seperti yang ditunjukkan di sini. Selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to create barcode image and render it in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/indonesian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/indonesian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..38616e7f5 --- /dev/null +++ b/barcode/indonesian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: Cara menghasilkan barcode dengan cepat menggunakan Python. Pelajari cara + membuat barcode dari data dan mengekspor gambar barcode dengan satu pustaka. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: id +lastmod: 2026-08-12 +og_description: Cara menghasilkan barcode di Python dengan Aspose.BarCode. Ikuti panduan + ini untuk membuat barcode dari data dan mengekspor gambar barcode sebagai PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Cara menghasilkan barcode di Python – panduan cepat dan andal +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Cara menghasilkan barcode di Python – panduan lengkap langkah demi langkah +url: /id/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara menghasilkan barcode di Python – panduan lengkap langkah demi langkah + +Jika Anda perlu **cara menghasilkan barcode** dalam aplikasi Python, tutorial ini menunjukkan kode tepat yang Anda butuhkan. Anda akan belajar **membuat barcode dari data**, menyesuaikan tampilannya, dan **mengekspor gambar barcode** sebagai file PNG—semua dalam kurang dari sepuluh baris kode. + +Membuat barcode mungkin terasa seperti hal terpisah dari logika bisnis Anda yang lain, tetapi dengan satu pustaka Anda dapat menjaga proses tetap sejalan dengan basis kode yang ada. Pada bagian-bagian berikut Anda akan melihat contoh lengkap yang dapat dijalankan, memahami mengapa setiap baris penting, dan menemukan variasi umum seperti mengubah lebar modul atau menggambar barcode hanya berupa outline. + +## Cara menghasilkan barcode dengan pustaka Aspose.BarCode + +Pustaka Aspose.BarCode untuk Python (via .NET) menyediakan API yang sederhana untuk banyak simbol, termasuk barcode Planet yang digunakan dalam panduan ini. Sebelum memulai, pastikan Anda telah menginstal paketnya: + +```bash +pip install aspose-barcode +``` + +> **Tip pro:** Gunakan lingkungan virtual untuk menghindari konflik versi dengan proyek lain. + +### 1. Impor kelas yang diperlukan + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Impor ini memberi Anda akses ke kelas generator, enumerasi tipe barcode, dan enum format gambar yang digunakan saat menyimpan hasil. + +### 2. Buat barcode dari data + +Langkah pertama adalah **membuat barcode dari data**. Konstruktor `BarcodeGenerator` menerima simbol dan string mentah yang ingin Anda enkode. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +Nilai `EncodeTypes.Planet` memilih barcode Planet, sementara `"123456"` adalah payload yang akan muncul dalam gambar akhir. + +### 3. Sesuaikan dimensi X (lebar modul) + +Dimensi X mengontrol lebar setiap modul barcode (garis tipis). Mengaturnya menjadi 4 pixel menghasilkan gambar yang jelas dan dapat dibaca tanpa membuat file terlalu besar. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Mengapa ini penting:** Dimensi X yang lebih besar meningkatkan keandalan pemindaian pada printer beresolusi rendah, sementara nilai yang lebih kecil mengurangi ukuran file untuk penggunaan web. + +### 4. Ekspor gambar barcode (gaya terisi) + +Sekarang Anda dapat **mengekspor gambar barcode** menggunakan metode `save`. Contoh ini menyimpan file PNG, tetapi Anda dapat memilih JPEG, BMP, atau TIFF dengan mengubah enum `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +File `PlanetFilled.png` berisi barcode Planet yang sepenuhnya terisi, siap untuk dicetak atau disisipkan dalam PDF. + +### 5. Buat generator kedua untuk barcode hanya outline + +Jika Anda memerlukan versi outline (batang kosong), Anda harus membuat generator baru karena flag `filled_bars` tidak dapat diubah setelah gambar disimpan. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Terapkan pengaturan dimensi X yang sama + +Ketika Anda membuat generator kedua, Anda harus mengulangi semua pengaturan visual yang ingin Anda pertahankan konsistensinya. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Nonaktifkan batang terisi untuk barcode outline + +Mengatur `filled_bars` menjadi `False` memberi tahu renderer untuk menggambar hanya outline setiap modul, menghasilkan gambar yang lebih ringan yang dapat berguna untuk keperluan desain. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Ekspor gambar barcode outline + +Akhirnya, **ekspor gambar barcode** lagi, kali ini menyimpan versi outline. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Sekarang Anda memiliki dua file PNG: satu dengan batang solid (`PlanetFilled.png`) dan satu lagi hanya dengan outline (`PlanetEmpty.png`). + +## Ekspor gambar barcode dalam format lain (opsional) + +Metode `save` mendukung beberapa format. Untuk mengekspor sebagai JPEG dengan kualitas 90 %: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Jika Anda memerlukan latar belakang transparan untuk penggunaan web, pilih PNG dengan saluran alfa: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Variasi umum dan kasus tepi + +| Skenario | Perubahan yang diperlukan | Potongan kode | +|----------|---------------------------|--------------| +| **Simbol berbeda** (misalnya, QR) | Gunakan nilai `EncodeTypes` yang berbeda | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Warna latar depan khusus** | Setel `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Resolusi lebih tinggi** | Tingkatkan DPI melalui `image_width` dan `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **String data besar** | Pastikan panjang data sesuai dengan spesifikasi simbol | Validate length before creating the generator | + +> **Waspadai:** Memberikan data yang melebihi panjang maksimum untuk simbol yang dipilih akan memunculkan pengecualian runtime. Selalu validasi panjang string atau tangkap `ArgumentException`. + +## Contoh lengkap yang dapat dijalankan + +Berikut adalah skrip lengkap yang dapat Anda salin‑tempel ke dalam file bernama `generate_planet_barcode.py`. Sesuaikan `YOUR_DIRECTORY` ke folder yang ada di mesin Anda. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Menjalankan skrip ini menghasilkan dua file PNG di direktori yang ditentukan. Verifikasi output dengan membuka gambar di penampil gambar apa pun; keduanya harus menampilkan barcode Planet yang mengenkode string `123456`. + +## Kesimpulan + +Sekarang Anda tahu **cara menghasilkan barcode** di Python menggunakan Aspose.BarCode, cara **membuat barcode dari data**, dan cara **mengekspor gambar barcode** dalam gaya terisi maupun outline. Pola yang sama berlaku untuk simbol lain, format gambar, dan kustomisasi visual, memberikan Anda fondasi fleksibel untuk fitur apa pun yang terkait barcode dalam aplikasi Anda. + +### Langkah selanjutnya + +* Jelajahi simbol lain seperti QR, Code‑128, atau DataMatrix dengan mengganti `EncodeTypes.Planet` dengan nilai yang diinginkan. +* Integrasikan file PNG yang dihasilkan ke dalam laporan PDF menggunakan pustaka seperti `ReportLab` atau `PyPDF2`. +* Bereksperimen dengan nilai dimensi X dinamis untuk menyesuaikan ukuran barcode berdasarkan resolusi layar atau DPI printer. + +Selamat coding, dan silakan sesuaikan contoh ini agar cocok dengan kebutuhan proyek Anda! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber mencakup contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara Menghasilkan Gambar Barcode di Java dengan Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Cara Menghasilkan Barcode Java – Panduan Konfigurasi Lengkap](/barcode/english/java/barcode-configuration/) +- [Cara membuat gambar barcode code128 di Java dengan Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/italian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/italian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..4cb3f27c3 --- /dev/null +++ b/barcode/italian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,297 @@ +--- +category: general +date: 2026-08-12 +description: Esempio di generatore di codici a barre che mostra come generare un codice + a barre con dimensioni di pixel precise. Impara a impostare la larghezza del modulo, + l'altezza della barra e a creare codici a barre Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: it +lastmod: 2026-08-12 +og_description: L'esempio di generatore di codici a barre dimostra come generare un + codice a barre con dimensioni pixel esatte. Segui questa guida per controllare la + larghezza del modulo e l'altezza della barra per i codici Planet e RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: Esempio di generatore di codici a barre – personalizza la dimensione dei + pixel in C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Esempio di generatore di codici a barre – guida passo passo per dimensioni + pixel personalizzate +url: /it/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# esempio di generatore di codici a barre – guida passo‑passo per dimensioni pixel personalizzate + +Se ti serve un **esempio di generatore di codici a barre** che ti consenta di controllare ogni pixel, questa guida mostra esattamente come farlo. Imparerai a impostare la larghezza del modulo, definire un’altezza fissa delle barre e generare sia codici Planet che RM4SCC con dimensioni prevedibili. + +La maggior parte degli sviluppatori ha difficoltà a creare immagini di “come generare codice a barre” che appaiano identiche su ogni schermo o stampante. Gli snippet di codice qui sotto risolvono il problema esponendo i parametri a livello di pixel della libreria Aspose.BarCode per .NET, così potrai produrre output coerenti senza indovinare. + +## Cosa imparerai + +* Come installare il pacchetto NuGet richiesto. +* Come generare un codice Planet con altezza calcolata automaticamente. +* Come generare un codice Planet con un’altezza esplicita di 100 pixel. +* Come generare un codice RM4SCC usando la stessa altezza esplicita. +* Perché la **dimensione pixel del codice a barre** è importante per l’affidabilità della scansione. +* Suggerimenti per risolvere i problemi più comuni quando generi immagini di codici Planet. + +Hai bisogno solo di .NET 6 o versioni successive, di un ambiente di sviluppo C# di base e di una connessione internet per scaricare il pacchetto NuGet. + +--- + +## esempio di generatore di codici a barre – configurazione dell’ambiente di sviluppo + +Prima di scrivere qualsiasi codice, assicurati che la libreria Aspose.BarCode sia disponibile nel tuo progetto. + +### Installa il pacchetto Aspose.BarCode + +Apri un terminale nella cartella del progetto ed esegui: + +```bash +dotnet add package Aspose.BarCode +``` + +Il comando aggiunge l’ultima versione stabile di **Aspose.BarCode** al tuo `csproj`. Dopo il completamento del restore, potrai iniziare a usare la classe `BarcodeGenerator`. + +> **Consiglio professionale:** Targetizza .NET 6 o .NET 7 per beneficiare delle ultime ottimizzazioni di performance e della gestione predefinita UTF‑8. + +### Aggiungi le direttive `using` necessarie + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Questi namespace espongono la classe `BarcodeGenerator` e l’enum `BarCodeImageFormat` usati più avanti nella guida. + +--- + +## Come generare un codice a barre con dimensione pixel personalizzata + +I tre passaggi seguenti illustrano l’intero **esempio di generatore di codici a barre**. Ogni passo si basa sul precedente, così puoi copiare‑incollare l’intero blocco in un’app console e farlo girare così com’è. + +### Passo 1 – genera un codice Planet con altezza calcolata automaticamente + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Perché funziona:** +*La proprietà `XDimension` definisce la larghezza di un singolo modulo del codice a barre (l’elemento più piccolo, nero o bianco). Quando ometti `BarHeight`, la libreria calcola un’altezza che mantiene il rapporto d’aspetto standard per i codici Planet.* + +**Output previsto:** Un file PNG chiamato `PlanetAuto.png` contenente un codice Planet pulito. La sua altezza si adatta alla larghezza del modulo di 4 pixel, tipicamente intorno ai 60 pixel per un payload di sei caratteri. + +### Passo 2 – genera un codice Planet con un’altezza esplicita di 100 pixel + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Perché potresti averne bisogno:** +Talvolta l’attrezzatura di scansione richiede un’altezza minima delle barre per una rilevazione affidabile. Impostando `BarHeight.Pixels`, garantisci che ogni immagine generata soddisfi tale requisito, indipendentemente dalla lunghezza dei dati codificati. + +**Output previsto:** `PlanetHeight100.png` mostra gli stessi dati di prima, ma le barre sono esattamente alte 100 pixel, dandoti pieno controllo sulla dimensione visiva. + +### Passo 3 – genera un codice RM4SCC con la stessa altezza esplicita + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Perché è importante:** +`EncodeTypes.RM4SCC` è un codice a barre lineare impilato usato nella logistica. Allineare la sua altezza delle barre a quella del codice Planet semplifica l’elaborazione batch quando entrambe le simbologie compaiono sulla stessa etichetta. + +**Output previsto:** `RM4SCCHeight100.png` visualizza un codice RM4SCC perfettamente dimensionato, corrispondente all’altezza di 100 pixel impostata per il codice Planet. + +> **Verifica del risultato:** Apri ciascun PNG in un visualizzatore di immagini e conferma che le barre nere siano esattamente larghe 4 pixel e, dove specificato, alte 100 pixel. Puoi anche inviare i file a un’app scanner di codici a barre per assicurarti che decodifichino “123456”. + +--- + +## Comprendere la dimensione pixel del codice a barre e l’altezza delle barre + +### Che cos’è la **dimensione pixel del codice a barre**? + +*Dimensione pixel* indica il numero fisico di pixel dello schermo o della stampante che rappresentano un singolo modulo (`XDimension`). Una dimensione pixel più grande produce un codice più grande, più facile da leggere per scanner a bassa risoluzione, ma occupa più spazio sull’etichetta. + +### Come influisce `BarHeight` sulla leggibilità? + +La proprietà `BarHeight` controlla la lunghezza verticale delle barre. Gli standard per la maggior parte dei codici 1‑D (inclusi Planet e RM4SCC) raccomandano un’altezza minima di 10 mm quando stampati a 300 dpi, equivalenti a circa 118 pixel. Impostare un’altezza inferiore può provocare errori di lettura, soprattutto con le fotocamere dei dispositivi mobili. + +### Quando lasciare che la libreria calcoli l’altezza automaticamente? + +Se generi codici a barre solo per la visualizzazione su schermo, il calcolo automatico mantiene il rapporto d’aspetto coerente e riduce la necessità di aggiustamenti manuali. Per etichette stampate che devono rispettare specifiche ISO rigorose, dovresti **impostare esplicitamente l’altezza delle barre**. + +--- + +## Ostacoli comuni e migliori pratiche nella generazione di codici Planet + +| Ostacolo | Perché accade | Soluzione | +|----------|----------------|-----------| +| Le barre appaiono troppo sottili o spesse | `XDimension` lasciato al valore predefinito (1 pixel) su display ad alta risoluzione | Imposta `XDimension.Pixels` ad almeno 3‑4 per una migliore chiarezza visiva | +| Lo scanner non riesce a leggere il codice | `BarHeight` è troppo piccolo per la lunghezza focale dello scanner | Usa `BarHeight.Pixels` ≥ 100 per la maggior parte degli scanner mobili | +| L’immagine risulta sfocata dopo il ridimensionamento | Salvataggio in JPEG introduce artefatti di compressione | Salva in PNG (`BarCodeImageFormat.Png`) per output senza perdita | +| Tipo di codice a barre inatteso | Valore enum `EncodeTypes` errato | Ricontrolla di stare usando `EncodeTypes.Planet` per la simbologia Planet | + +### Consiglio professionale sulle performance + +Quando generi migliaia di codici a barre in un processo batch, riutilizza una singola istanza di `BarcodeGenerator` e modifica solo `CodeText` e i parametri di dimensione tra un salvataggio e l’altro. Questo evita l’allocazione ripetuta di oggetti di rendering interni e può ridurre il tempo di esecuzione fino al 30 %. + +--- + +## Esempio completo – metti tutto insieme + +Crea un nuovo progetto console (`dotnet new console -n BarcodeDemo`) e sostituisci il contenuto di `Program.cs` con il seguente: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Esegui il programma con `dotnet run`. Al termine troverai tre file PNG nella cartella del progetto, ognuno dei quali illustra uno scenario diverso del **esempio di generatore di codici a barre**. + +--- + +## Passi successivi e argomenti correlati + +* **Come generare codici a barre in altri formati** – esplora `EncodeTypes.Code128`, `EncodeTypes.QR` e `EncodeTypes.DataMatrix` per esigenze 2‑D. +* **Incorporare codici a barre nei PDF** – combina Aspose.BarCode con Aspose.PDF per inserire i codici direttamente nei modelli di fattura. +* **Dimensione dinamica del codice a barre basata sull’input dell’utente** – calcola + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare ulteriori funzionalità dell’API e a esplorare approcci alternativi nei tuoi progetti. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/italian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/italian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..8fce43789 --- /dev/null +++ b/barcode/italian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-08-12 +description: Configura rapidamente il layout del codice a barre Databar in Python. + Impara a impostare colonne, righe e a salvare le immagini con la libreria generatore + di codici a barre. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: it +lastmod: 2026-08-12 +og_description: Configura il layout del codice a barre Databar in Python per controllare + colonne, righe e output dell'immagine. Segui questa guida per una soluzione pronta + all'uso. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Configura il layout del codice a barre Databar in Python – tutorial completo +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Configura il layout del codice a barre Databar in Python – guida passo passo +url: /it/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Configurare il layout del codice a barre Databar in Python – guida passo‑passo + +Se devi **configurare il layout del codice a barre Databar in Python**, questa guida ti accompagna attraverso l’intero processo. Vedrai come impostare il numero di colonne o righe per un codice a barre Databar Expanded Stacked e come salvare l’immagine risultante con una singola chiamata alla libreria generatore di codici a barre. + +Controllare il layout è essenziale quando inserisci i codici a barre su confezioni strette, ricevute o schermi mobili. Nelle sezioni seguenti copriremo le importazioni necessarie, le due opzioni di layout (colonne e righe) e le migliori pratiche per salvare un’immagine PNG pulita. + +## Cosa ti serve + +Prima di iniziare, assicurati di avere: + +* Python 3.8 o superiore +* `aspose.barcode` (o qualsiasi pacchetto compatibile per la generazione di codici a barre) installato + ```bash + pip install aspose-barcode + ``` +* Permessi di scrittura su una cartella dove verranno salvati i file PNG + +Non sono necessari strumenti esterni aggiuntivi: la libreria gestisce il rendering, il ridimensionamento e la codifica dell’immagine internamente. + +## Come configurare il layout del codice a barre Databar in Python + +Il cuore della soluzione è la classe `BarcodeGenerator`. Accetta un enum `EncodeTypes` che identifica la simbologia del codice a barre—in questo caso `EncodeTypes.DatabarExpandedStacked`. Dopo aver creato il generatore puoi regolare il layout impostando le proprietà `columns` o `rows` sull’oggetto parametro `data_bar`. + +### Passo 1: Importare le classi necessarie + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Queste importazioni ti danno accesso al generatore, all’enumerazione per i tipi Databar e alla costante del formato immagine PNG. + +### Passo 2: Creare un generatore di codici a barre per Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Perché questo passo?* +`EncodeTypes.DatabarExpandedStacked` indica alla libreria di produrre la simbologia **Databar Expanded Stacked**, che supporta stringhe numeriche più lunghe mantenendo un ingombro compatto. Il secondo argomento è il dato da codificare; può essere qualsiasi stringa conforme alla specifica Databar. + +### Passo 3: Impostare il numero di colonne (layout orizzontale) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** è la frase chiave per questa operazione. Quando aumenti il conteggio delle colonne, il codice a barre si espande orizzontalmente, utile per etichette larghe. La libreria ricalcola automaticamente la larghezza del modulo per mantenere le dimensioni complessive coerenti. + +#### Consiglio professionale +Il numero massimo di colonne per Databar Expanded Stacked è 8. Impostare un valore superiore al limite lo ridurrà al massimo consentito, ma è meglio convalidare l’input in anticipo. + +### Passo 4: Salvare l’immagine del codice a barre con il layout a colonne + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** è l’azione che scrive il codice a barre renderizzato su disco. PNG è lossless, quindi preserva i bordi netti necessari per una scansione affidabile. + +### Passo 5: Creare un secondo generatore per lo stesso tipo di codice a barre (layout a righe) + +Se preferisci una pila verticale, lavori con le righe invece delle colonne. Il codice qui sotto riutilizza lo stesso valore ma crea una nuova istanza di `BarcodeGenerator` per evitare di mescolare le impostazioni di colonne e righe. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Passo 6: Impostare il numero di righe (layout verticale) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** dispone i moduli del codice a barre verticalmente. Un layout a tre righe riduce l’altezza di ogni singola pila, rendendo il codice a barre adatto a ricevute strette o schermi mobili. + +#### Caso limite +Se imposti `rows` a 1, la libreria genera un Databar a singola riga (equivalente a un Databar standard). Valori inferiori a 1 vengono ignorati e ripristinati al valore predefinito (1 riga). + +### Passo 7: Salvare l’immagine del codice a barre con il layout a righe + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Ancora una volta, **save barcode image** utilizza PNG per mantenere l’output nitido. + +## Esempio completo eseguibile + +Mettere insieme tutti i pezzi ti fornisce uno script autonomo che puoi inserire in qualsiasi progetto Python. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Output previsto** + +L’esecuzione dello script crea due file PNG: + +* `output/ExpandedCols4.png` – un codice a barre esteso su quattro colonne +* `output/ExpandedRows3.png` – un codice a barre compresso in tre righe + +Entrambe le immagini possono essere aperte con qualsiasi visualizzatore di immagini o importate direttamente in fatture PDF, modelli di etichette o pagine web. + +## Domande frequenti e risoluzione dei problemi + +| Domanda | Risposta | +|----------|--------| +| *E se il codice a barre appare sfocato?* | Aumenta la risoluzione dell’immagine impostando `barcode_generator.parameters.image_width` e `image_height` prima di chiamare `save`. | +| *Posso usare altri formati immagine?* | Sì. Sostituisci `BarCodeImageFormat.Png` con `Jpeg`, `Bmp` o `Gif` secondo necessità. | +| *Esiste un limite alla lunghezza dei dati?* | Databar Expanded Stacked supporta fino a 74 caratteri numerici. Superare il limite genera una `ArgumentException`. | +| *Come cambio il colore del primo piano?* | Usa `barcode_generator.parameters.barcode.color = Color.Blue` (importa `System.Drawing.Color`). | +| *Posso combinare colonne e righe?* | No. L’API tratta colonne e righe come modalità di layout mutualmente esclusive. Scegli una sola per istanza di codice a barre. | + +## Prossimi passi + +Ora che sai **configurare il layout del codice a barre Databar**, considera di approfondire questi argomenti correlati: + +* **Aggiungere didascalie di testo** – usa `barcode_generator.parameters.barcode.code_text` per visualizzare il valore codificato sotto l’immagine. +* **Incorporare il codice a barre in un PDF** – combina il PNG generato con `aspose.pdf` per creare documenti stampabili. +* **Dimensionamento dinamico** – calcola il numero ottimale di colonne o righe in base alle dimensioni dell’etichetta a runtime. +* **Elaborazione batch** – itera su un CSV di codici prodotto per generare automaticamente una libreria di immagini di codici a barre. + +Sperimenta con valori diversi di colonne e righe per vedere come influenzano l’affidabilità della scansione sui tuoi dispositivi target. Più test esegui, più comprenderai i compromessi tra dimensione del codice a barre, leggibilità e vincoli di spazio. + +--- + +*Buon coding! Se questo tutorial ti è stato utile, condividilo con i colleghi o lascia un commento sulle sfide di layout che hai incontrato.* + +## Cosa dovresti imparare dopo? + + +I tutorial seguenti coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare ulteriori funzionalità dell’API ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Create barcode image c# – Configure Codablock F Rows & Columns](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [One-Dimensional Databar Barcode Height Adjustment](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/italian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/italian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..b70151011 --- /dev/null +++ b/barcode/italian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: Crea un'immagine di codice a barre in C# usando BarCodeGenerator. Scopri + come generare DataBar, controllare le dimensioni dell'immagine del codice a barre + e creare più codici a barre in modo efficiente. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: it +lastmod: 2026-08-12 +og_description: Crea un'immagine di codice a barre in C# con BarCodeGenerator. Questo + tutorial mostra passo passo come generare codici DataBar, regolare le dimensioni + dell'immagine del codice a barre e produrre più codici a barre. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Crea immagine di codice a barre in C# – guida completa a BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Crea immagine di codice a barre in C# con BarCodeGenerator +url: /it/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea immagine barcode in C# con BarCodeGenerator + +Se hai bisogno di **creare un'immagine barcode** in un'applicazione .NET, questa guida ti mostra esattamente come farlo con la classe `BarCodeGenerator`. Che tu stia costruendo un sistema POS per il retail o uno strumento di tracciamento dell'inventario, imparerai a generare simboli DataBar, controllare le dimensioni dell'immagine barcode e produrre diversi barcode in un'unica esecuzione. + +Scoprirai anche come l'API **barcode generator c#** ti consente di regolare le dimensioni, cambiare i formati di output e gestire casi limite come stringhe di dati non valide. Alla fine del tutorial potrai **creare più barcode** con sicurezza senza scrivere codice ripetitivo. + +## Prerequisiti + +- .NET 6.0 o versioni successive installate +- Un ambiente di sviluppo (Visual Studio, Rider o VS Code) +- Il pacchetto NuGet Aspose.BarCode per .NET (o qualsiasi libreria compatibile che fornisca `BarCodeGenerator`) + +Puoi aggiungere il pacchetto con: + +```bash +dotnet add package Aspose.BarCode +``` + +## Cosa copre questo tutorial + +1. Configurare un'istanza **barcode generator c#** per la codifica DataBar Omni‑directional. +2. Regolare la **dimensione dell'immagine barcode** modificando X‑dimension e altezza delle barre. +3. Utilizzare un ciclo per **creare più barcode** con altezze diverse. +4. Salvare le immagini come file PNG e verificare il risultato. + +Tutti gli snippet di codice sono completi e pronti per il copia‑incolla in un nuovo progetto console. + +![Esempio di creazione immagine barcode](barcode-example.png){alt="Esempio di creazione immagine barcode"} + +## Passo 1: Inizializzare il generatore – nozioni di base per creare l'immagine barcode + +Il primo passo è istanziare `BarCodeGenerator` con la simbologia desiderata. Per un simbolo DataBar Omni‑directional si utilizza `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Perché è importante:** L'istanziazione del generatore definisce le regole di codifica e il payload dei dati. Se ometti il valore corretto di `EncodeTypes`, la libreria produrrà un barcode non supportato o genererà un'eccezione. + +## Passo 2: Configurare X‑dimension e altezza della barra – controllare le dimensioni dell'immagine barcode + +Le dimensioni visive di un barcode sono determinate da due parametri: + +| Parametro | Cosa controlla | Intervallo tipico | +|-----------|----------------|-------------------| +| `x_dimension.pixels` | Larghezza del modulo più piccolo (il “punto”) | 1 – 4 px | +| `bar_height.pixels` | Altezza delle barre verticali | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Consiglio professionale:** Una X‑dimension più piccola produce un'immagine ad alta risoluzione ma può risultare più difficile da leggere su stampanti di bassa qualità. Regola il valore in base all'apparecchiatura di scansione prevista. + +## Passo 3: Salvare il primo barcode – creare l'immagine barcode per altezza di 30 px + +Ora puoi generare l'immagine e scriverla su disco. Il metodo `Save` accetta un percorso file e un enum del formato immagine. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Risultato atteso:** Un file PNG chiamato `Databar30.png` appare in `C:\Barcodes`. Aprendo il file si visualizza un simbolo DataBar Omni‑directional con un pattern chiaro e ad alto contrasto. + +## Passo 4: Modificare l'altezza e generare immagini aggiuntive – creare più barcode + +Per **creare più barcode** con dimensioni diverse è sufficiente modificare la proprietà `BarHeight` e chiamare nuovamente `Save`. Questo evita di reinizializzare il generatore, risparmiando memoria e tempo CPU. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Perché funziona:** L'oggetto `BarCodeGenerator` conserva tutto lo stato di configurazione. Modificando una singola proprietà si aggiorna il motore di rendering per la successiva chiamata a `Save`, consentendo di **creare più barcode** in modo efficiente. + +## Passo 5: Avanzato – come generare DataBar con dati personalizzati + +L'esempio sopra utilizza un payload GS1 statico. In scenari reali spesso è necessario incorporare identificatori di prodotto variabili. La libreria accetta qualsiasi stringa che corrisponda alla specifica DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Punto chiave:** Impostare `generator.CodeText` aggiorna i dati codificati senza ricreare l'oggetto. Questo è lo schema consigliato **how to generate databar** quando si gestiscono grandi insiemi di dati. + +## Passo 6: Verificare e risolvere problemi – garantire la corretta dimensione dell'immagine barcode + +Dopo aver generato le immagini, potresti voler confermare programmaticamente che le dimensioni corrispondano alle tue aspettative. La classe `Image` di `System.Drawing` può leggere il file e riportare la sua dimensione. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Se l'altezza non riflette il valore impostato, verifica: + +- **X‑dimension**: Un valore molto piccolo può far arrotondare l'altezza da parte del renderer. +- **Image format**: Alcuni formati (ad esempio JPEG) applicano compressione che può modificare le dimensioni in pixel al salvataggio. PNG conserva le dimensioni esatte. + +## Passo 7: Best practice per le dimensioni dell'immagine barcode e le prestazioni + +| Raccomandazione | Motivo | +|----------------|--------| +| Mantieni `x_dimension.pixels` tra 2 – 3 px per la maggior parte degli scanner. | Equilibra leggibilità e dimensione del file. | +| Usa PNG per output lossless quando l'immagine verrà stampata. | Garantisce dimensioni esatte e bordi nitidi. | +| Riutilizza una singola istanza di `BarCodeGenerator` quando generi molti barcode. | Riduce l'overhead di allocazione degli oggetti. | +| Convalida la stringa di input rispetto allo standard GS1 prima di assegnarla a `CodeText`. | Previene eccezioni a runtime e scansioni non valide. | +| Memorizza le immagini generate in una cartella dedicata con una convenzione di denominazione chiara (ad esempio `Databar_{GTIN}.png`). | Semplifica l'elaborazione successiva e le tracce di audit. | + +## Esempio completo funzionante + +Di seguito è riportato il programma completo che incorpora tutti i passaggi dall'inizializzazione alla verifica. Copia il codice in un nuovo progetto console e eseguilo. + + + +## Cosa dovresti imparare dopo? + +I tutorial seguenti coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Genera immagine barcode – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Crea immagine barcode DotCode – righe e colonne (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Come creare la zona silenziosa del barcode per ITF-14 usando Aspose.BarCode per .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/italian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/italian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..738a6dcb7 --- /dev/null +++ b/barcode/italian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-12 +description: Crea un databar omnidirezionale con Python e impara come generare un'immagine + di codice a barre in Python usando Aspose.BarCode. Segui la guida passo passo per + una soluzione completa. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: it +lastmod: 2026-08-12 +og_description: Crea un databar omnidirezionale con Python e genera un'immagine di + codice a barre in pochi minuti. Questo tutorial mostra un esempio completo e eseguibile. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Crea una databar omnidirezionale – guida completa in Python +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Crea immagine di databar e codice a barre omnidirezionale in Python +url: /it/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea omni directional databar e immagine di barcode in Python + +Se hai bisogno di **create omni directional databar** in un progetto Python, questa guida ti mostra come farlo e anche come **create barcode image python** usando la libreria Aspose.BarCode. Otterrai uno script pronto all'esecuzione che produce due file PNG con diversi rapporti d'aspetto. + +Generare un DataBar che segue la specifica Omni‑directional è una necessità comune per applicazioni di vendita al dettaglio e logistica. Il tutorial copre l'installazione, la configurazione della X‑dimension, la regolazione del rapporto d'aspetto e il salvataggio delle immagini finali. Non sono richiesti servizi esterni; tutto viene eseguito localmente. + +## Cosa ti servirà + +* Python 3.8 o versioni successive installato sulla tua macchina. +* Accesso a un terminale o prompt dei comandi. +* Permessi di scrittura su una cartella dove verranno salvate le immagini del codice a barre. + +L'unica dipendenza di terze parti è **Aspose.BarCode for Python via .NET**, che supporta il tipo Omni‑directional DataBar fin da subito. + +## Passo 1: Installa Aspose.BarCode per Python + +Aspose.BarCode fornisce la classe `BarcodeGenerator` usata nel codice di esempio. Installa il pacchetto con `pip`: + +```bash +pip install aspose-barcode +``` + +Il pacchetto include i binding necessari per il runtime .NET, quindi non è necessario installare separatamente il .NET SDK. + +## Passo 2: Importa la libreria e crea il generatore + +La prima riga dello script crea un generatore per un Omni‑directional DataBar impilato. Il valore GTIN‑14 `(01)12345678901231` è usato come dato di esempio. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Perché questo passo è importante*: La costante `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` indica alla libreria di codificare il valore come Omni‑directional DataBar, che è il formato richiesto da molti scanner point‑of‑sale. + +## Passo 3: Imposta la X‑dimension (larghezza del modulo) + +La X‑dimension definisce la larghezza del modulo di barra più piccolo. Un valore di `2` pixel produce un codice a barre chiaro e leggibile senza dimensioni eccessive del file. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Perché questo passo è importante*: Regolare la X‑dimension ti permette di bilanciare leggibilità e dimensioni dell'immagine. Una X‑dimension troppo piccola può risultare poco leggibile su stampanti a bassa risoluzione. + +## Passo 4: Configura il rapporto d'aspetto e salva la prima immagine + +Il rapporto d'aspetto influenza l'altezza complessiva del DataBar rispetto alla sua larghezza. Un rapporto d'aspetto di `15` crea uno stile visivo compatto. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Suggerimento**: Usa `pathlib.Path` per costruire il percorso di output, che crea automaticamente le directory mancanti. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Passo 5: Cambia il rapporto d'aspetto per un secondo stile visivo e salva un'altra immagine + +Modificando il rapporto d'aspetto a `30` si ottiene un codice a barre più alto, che può essere richiesto da hardware scanner specifici. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Perché questo passo è importante*: Diversi rivenditori e dispositivi di scansione hanno vincoli di dimensioni differenti. Fornire entrambi i rapporti d'aspetto in un unico script ti consente di generare lo stile esatto di cui hai bisogno senza duplicare il codice. + +## Script completo – create omni directional databar and barcode image python + +Di seguito trovi l'esempio completo e eseguibile che incorpora tutti i passaggi precedenti. Salvalo come `generate_databar.py` ed eseguilo con `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Output previsto + +Eseguendo lo script vengono creati i seguenti file: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Entrambe le immagini mostrano un Omni‑directional DataBar valido che può essere scansionato dall'attrezzatura retail standard. + +![esempio di creazione di immagine di databar omni directional barcode in Python](example_databar.png "crea immagine di databar omni directional barcode python") + +*L'immagine sopra è un segnaposto che illustra i due file PNG salvati.* + +## Gestione dei problemi comuni + +| Problema | Motivo | Soluzione | +|----------|--------|-----------| +| `ImportError: No module named aspose` | Aspose.BarCode non installato o installato in un ambiente diverso. | Attiva l'ambiente virtuale corretto ed esegui `pip install aspose-barcode`. | +| `PermissionError` when saving | Lo script non ha i permessi di scrittura per la cartella di destinazione. | Scegli una directory di tua proprietà o esegui lo script con i privilegi appropriati. | +| Barcode does not scan | X‑dimension troppo bassa o rapporto d'aspetto incompatibile con lo scanner. | Aumenta `x_dimension.pixels` a 3 o 4 e prova diversi valori di `aspect_ratio` (es., 20, 25). | +| Missing .NET runtime | Aspose.BarCode dipende dal runtime .NET su Windows/Linux. | Installa l'ultimo runtime .NET dal sito di Microsoft; la documentazione del pacchetto fornisce indicazioni specifiche per piattaforma. | + +## Estendere l'esempio + +Puoi adattare lo script per generare altre varianti di DataBar (es., `DATABAR_STACKED`, `DATABAR_EXPANDED`). Sostituisci la costante `EncodeTypes` di conseguenza: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Se hai bisogno di incorporare il codice a barre in un PDF, Aspose.PDF per Python può importare direttamente il file PNG oppure puoi usare il metodo `save` con `BarCodeImageFormat.Pdf`. + +## Conclusione + +Questo tutorial ha mostrato come **create omni directional databar** e come **create barcode image python** usando Aspose.BarCode. Ora disponi di uno script completo e riproducibile che genera due file PNG con diversi rapporti d'aspetto, gestisce le problematiche comuni e può essere esteso ad altri formati di codice a barre. + +Successivamente, esplora la generazione di QR code, l'aggiunta del codice a barre a fatture PDF o l'automazione dell'elaborazione batch per grandi cataloghi di prodotti. Ognuno di questi argomenti si basa sullo stesso modello `BarcodeGenerator` mostrato qui. Buona programmazione! + +## Cosa dovresti imparare dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Genera immagine di codice a barre – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Crea immagine di codice a barre DotCode – righe & colonne (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Come creare un'immagine di codice a barre e renderizzarla in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/italian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/italian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..98748e63a --- /dev/null +++ b/barcode/italian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Come generare rapidamente un codice a barre usando Python. Impara a creare + un codice a barre dai dati ed esportare l'immagine del codice a barre con una singola + libreria. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: it +lastmod: 2026-08-12 +og_description: Come generare un codice a barre in Python con Aspose.BarCode. Segui + questa guida per creare un codice a barre dai dati ed esportare l'immagine del codice + a barre in formato PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Come generare un codice a barre in Python – guida veloce e affidabile +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Come generare un codice a barre in Python – guida completa passo passo +url: /it/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come generare un codice a barre in Python – guida completa passo‑passo + +Se hai bisogno di **come generare un codice a barre** in un'applicazione Python, questo tutorial ti mostra il codice esatto di cui hai bisogno. Imparerai a **creare un codice a barre dai dati**, a regolare il suo aspetto e a **esportare l'immagine del codice a barre** come file PNG—tutto in meno di dieci righe di codice. + +Generare un codice a barre può sembrare una preoccupazione separata rispetto al resto della tua logica di business, ma con una singola libreria puoi mantenere il processo in linea con il tuo codice esistente. Nelle sezioni seguenti vedrai un esempio completo e eseguibile, comprenderai perché ogni riga è importante e scoprirai variazioni comuni come la modifica della larghezza del modulo o la creazione di un codice a barre solo con contorno. + +## Come generare un codice a barre con la libreria Aspose.BarCode + +La libreria Aspose.BarCode per Python (via .NET) fornisce un'API semplice per molte simbologie, incluso il codice a barre Planet usato in questa guida. Prima di iniziare, assicurati di avere il pacchetto installato: + +```bash +pip install aspose-barcode +``` + +> **Consiglio:** Usa un ambiente virtuale per evitare conflitti di versione con altri progetti. + +### 1. Importa le classi necessarie + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Queste importazioni ti danno accesso alla classe generatore, all'enumerazione dei tipi di codice a barre e all'enumerazione del formato immagine usata quando salvi il risultato. + +### 2. Crea un codice a barre dai dati + +Il primo passo è **creare un codice a barre dai dati**. Il costruttore `BarcodeGenerator` accetta la simbologia e la stringa grezza che vuoi codificare. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +Il valore `EncodeTypes.Planet` seleziona il codice a barre Planet, mentre `"123456"` è il payload che apparirà nell'immagine finale. + +### 3. Regola la dimensione X (larghezza del modulo) + +La dimensione X controlla la larghezza di ogni modulo del codice a barre (la barra sottile). Impostandola a 4 pixel ottieni un'immagine chiara e leggibile senza rendere il file troppo grande. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Perché è importante:** Una dimensione X più grande migliora l'affidabilità della scansione su stampanti a bassa risoluzione, mentre un valore più piccolo riduce le dimensioni del file per l'uso web. + +### 4. Esporta l'immagine del codice a barre (stile pieno) + +Ora puoi **esportare l'immagine del codice a barre** usando il metodo `save`. L'esempio salva un file PNG, ma puoi scegliere JPEG, BMP o TIFF modificando l'enumerazione `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +Il file `PlanetFilled.png` contiene un codice a barre Planet completamente pieno, pronto per la stampa o per l'inserimento in un PDF. + +### 5. Crea un secondo generatore per un codice a barre solo contorno + +Se ti serve una versione a contorno (barre vuote), devi creare un nuovo generatore perché il flag `filled_bars` non può essere modificato dopo che l'immagine è stata salvata. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Applica la stessa impostazione della dimensione X + +Quando crei un secondo generatore, devi ripetere tutte le impostazioni visive che vuoi mantenere coerenti. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Disabilita le barre piene per un codice a barre a contorno + +Impostare `filled_bars` a `False` indica al renderer di disegnare solo i contorni di ogni modulo, producendo un'immagine più leggera che può essere utile per scopi di design. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Esporta l'immagine del codice a barre a contorno + +Infine, **esporta l'immagine del codice a barre** di nuovo, questa volta salvando la versione a contorno. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Ora hai due file PNG: uno con barre solide (`PlanetFilled.png`) e uno con solo i contorni (`PlanetEmpty.png`). + +## Esporta l'immagine del codice a barre in altri formati (opzionale) + +Il metodo `save` supporta diversi formati. Per esportare come JPEG con qualità al 90 %: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Se ti serve uno sfondo trasparente per il web, scegli PNG con canale alfa: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Variazioni comuni e casi limite + +| Scenario | Modifica necessaria | Snippet di codice | +|----------|---------------------|-------------------| +| **Simbologia diversa** (es. QR) | Usa un valore `EncodeTypes` diverso | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Colore di primo piano personalizzato** | Imposta `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Risoluzione più alta** | Aumenta DPI tramite `image_width` e `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Stringhe di dati lunghe** | Assicurati che la lunghezza dei dati rientri nelle specifiche della simbologia | Valida la lunghezza prima di creare il generatore | + +> **Attenzione:** Fornire dati che superano la lunghezza massima per la simbologia scelta genera un'eccezione a runtime. Convalida sempre la lunghezza della stringa o gestisci `ArgumentException`. + +## Esempio completo, eseguibile + +Di seguito trovi lo script completo che puoi copiare‑incollare in un file chiamato `generate_planet_barcode.py`. Modifica `YOUR_DIRECTORY` con una cartella che esiste sul tuo computer. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Eseguendo questo script otterrai due file PNG nella directory specificata. Verifica l'output aprendo le immagini con qualsiasi visualizzatore; entrambe dovrebbero mostrare un codice a barre Planet che codifica la stringa `123456`. + +## Conclusione + +Ora sai **come generare un codice a barre** in Python usando Aspose.BarCode, come **creare un codice a barre dai dati** e come **esportare l'immagine del codice a barre** sia in stile pieno che a contorno. Lo stesso schema si applica ad altre simbologie, formati immagine e personalizzazioni visive, offrendoti una base flessibile per qualsiasi funzionalità legata ai codici a barre nella tua applicazione. + +### Prossimi passi + +* Esplora altre simbologie come QR, Code‑128 o DataMatrix sostituendo `EncodeTypes.Planet` con il valore desiderato. +* Integra i file PNG generati nei report PDF usando librerie come `ReportLab` o `PyPDF2`. +* Sperimenta valori dinamici della dimensione X per adattare la dimensione del codice a barre in base alla risoluzione dello schermo o al DPI della stampante. + +Buon coding, e sentiti libero di adattare l'esempio alle esigenze del tuo progetto! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare ulteriori funzionalità dell'API e a esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Come generare un'immagine di codice a barre in Java con Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Come generare un codice a barre Java – Guida completa alla configurazione](/barcode/english/java/barcode-configuration/) +- [Come creare immagini di codice a barre code128 in Java con Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/japanese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/japanese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..8a02625ef --- /dev/null +++ b/barcode/japanese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-08-12 +description: 正確なピクセルサイズでバーコードを生成する方法を示すバーコードジェネレータの例です。モジュール幅やバーの高さの設定方法を学び、Planetバーコードを作成しましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: ja +lastmod: 2026-08-12 +og_description: バーコードジェネレータの例では、正確なピクセル寸法でバーコードを生成する方法を示しています。このガイドに従って、Planet および + RM4SCC コードのモジュール幅とバーの高さを制御してください。 +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: バーコードジェネレーターの例 – C#でピクセルサイズをカスタマイズ +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: バーコード生成例 – カスタムピクセルサイズのステップバイステップガイド +url: /ja/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# バーコードジェネレータ例 – カスタムピクセルサイズのステップバイステップガイド + +すべてのピクセルを制御できる **barcode generator example** が必要な場合、このガイドではその手順を正確に示します。モジュール幅の設定、固定バー高さの定義、そして Planet と RM4SCC のバーコードを予測可能なサイズで生成する方法を学びます。 + +ほとんどの開発者は、画面やプリンターごとに同じに見える「how to generate barcode」画像の作成に苦労しています。以下のコードスニペットは、Aspose.BarCode for .NET ライブラリのピクセルレベルのパラメータを公開することで、この問題を解決し、推測なしで一貫した出力を実現します。 + +## What you’ll learn + +* 必要な NuGet パッケージのインストール方法。 +* 高さを自動計算した Planet バーコードの生成方法。 +* 明示的に 100 ピクセルの高さを指定した Planet バーコードの生成方法。 +* 同じ明示的な高さで RM4SCC バーコードを生成する方法。 +* **barcode pixel size** がスキャン信頼性に与える影響。 +* Planet バーコード画像を生成する際の一般的な問題のトラブルシューティングのヒント。 + +.NET 6 以降、基本的な C# 開発環境、そして NuGet パッケージを取得できるインターネット接続があれば始められます。 + +--- + +## barcode generator example – set up the development environment + +コードを書く前に、Aspose.BarCode ライブラリがプロジェクトで利用可能であることを確認してください。 + +### Install the Aspose.BarCode package + +プロジェクトフォルダーでターミナルを開き、次のコマンドを実行します: + +```bash +dotnet add package Aspose.BarCode +``` + +このコマンドは **Aspose.BarCode** の最新安定版を `csproj` に追加します。復元が完了したら、`BarcodeGenerator` クラスの使用を開始できます。 + +> **Pro tip:** .NET 6 または .NET 7 をターゲットにすると、最新のパフォーマンス改善とデフォルトの UTF‑8 ハンドリングの恩恵を受けられます。 + +### Add the necessary `using` directives + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +これらの名前空間は、チュートリアル後半で使用する `BarcodeGenerator` クラスと `BarCodeImageFormat` 列挙体を公開します。 + +--- + +## How to generate barcode with custom pixel size + +以下の 3 つのステップで、完全な **barcode generator example** を示します。各ステップは前のものに基づいているため、コード全体をコンソールアプリにコピー&ペーストしてそのまま実行できます。 + +### Step 1 – generate a Planet barcode with automatically calculated height + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Why this works:** +`XDimension` プロパティは単一のバーコードモジュール(最小の黒または白要素)の幅を定義します。`BarHeight` を省略すると、ライブラリは Planet コードの標準アスペクト比を保つ高さを自動計算します。 + +**Expected output:** `PlanetAuto.png` という名前の PNG ファイルが生成され、クリーンな Planet バーコードが含まれます。その高さは 4 ピクセルモジュール幅に合わせて自動調整され、通常は 6 文字のペイロードで約 60 ピクセルになります。 + +### Step 2 – generate a Planet barcode with an explicit 100‑pixel height + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Why you might need this:** +スキャン機器が信頼できる検出のために最小バー高さを要求することがあります。`BarHeight.Pixels` を設定することで、エンコードデータの長さに関係なく、生成されるすべての画像がその要件を満たすことが保証されます。 + +**Expected output:** `PlanetHeight100.png` は前と同じデータを示しますが、バーの高さが正確に 100 ピクセルになり、視覚的なサイズを完全にコントロールできます。 + +### Step 3 – generate an RM4SCC barcode with the same explicit height + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Why this matters:** +`EncodeTypes.RM4SCC` は物流で使用されるスタック型リニアバーコードです。そのバー高さを Planet バーコードと揃えることで、同じラベル上に両方のシンボルが出現した場合のバッチ処理が簡素化されます。 + +**Expected output:** `RM4SCCHeight100.png` は完璧にサイズ調整された RM4SCC バーコードを表示し、Planet コードに設定した 100 ピクセルの高さと一致します。 + +> **Result verification:** 各 PNG を画像ビューアで開き、黒いバーが幅 4 ピクセル、指定した場合は高さ 100 ピクセルであることを確認してください。また、バーコードスキャナーアプリにファイルを渡して「123456」とデコードされるかテストできます。 + +--- + +## Understanding barcode pixel size and bar height + +### What is **barcode pixel size**? + +*Pixel size* は、単一モジュール(`XDimension`)を表す画面またはプリンターピクセルの実数を指します。ピクセルサイズが大きいほどバーコードは大きくなり、低解像度スキャナーには読み取りやすくなりますが、ラベルの使用面積も増えます。 + +### How does `BarHeight` affect readability? + +`BarHeight` プロパティはバーの垂直長さを制御します。Planet や RM4SCC などのほとんどの 1‑D バーコードの標準では、300 dpi で印刷した場合の最小高さは 10 mm とされ、これはおおよそ 118 ピクセルに相当します。この高さ未満に設定すると、特にモバイルカメラでの読み取りエラーが発生しやすくなります。 + +### When should you let the library calculate height automatically? + +画面表示のみを目的としたバーコードを生成する場合、ライブラリの自動計算はアスペクト比を保ち、手動調整の手間を減らします。ISO 仕様など厳格な印刷ラベルが必要な場合は、**バー高さを明示的に設定** すべきです。 + +--- + +## Common pitfalls and best practices when you generate Planet barcode + +| 落とし穴 | 発生原因 | 対策 | +|---------|----------|------| +| バーが細すぎるまたは太すぎる | 高解像度ディスプレイで `XDimension` がデフォルト (1 ピクセル) のまま | `XDimension.Pixels` を少なくとも 3‑4 に設定 | +| スキャナーがコードを読み取れない | `BarHeight` がスキャナーの焦点距離に対して小さすぎる | ほとんどのモバイルスキャナー向けに `BarHeight.Pixels` ≥ 100 を使用 | +| スケーリング後に画像がぼやける | JPEG で保存すると圧縮アーティファクトが発生 | ロスレス出力の PNG (`BarCodeImageFormat.Png`) で保存 | +| 予期しないバーコードタイプ | `EncodeTypes` 列挙体の値が間違っている | Planet シンボルには `EncodeTypes.Planet` を使用しているか再確認 | + +### Pro tip on performance + +数千件のバーコードをバッチ処理で生成する場合、`BarcodeGenerator` インスタンスを 1 つだけ再利用し、`CodeText` とサイズパラメータだけを変更して保存します。これにより内部レンダリングオブジェクトの再割り当てが回避され、実行時間が最大 30 % 短縮されることがあります。 + +--- + +## Full working example – put everything together + +新しいコンソールプロジェクトを作成します (`dotnet new console -n BarcodeDemo`)。次に `Program.cs` の内容を以下に置き換えてください: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +`dotnet run` でプログラムを実行します。実行後、プロジェクトフォルダーに 3 つの PNG ファイルが作成され、それぞれが異なる **barcode generator example** シナリオを示します。 + +--- + +## Next steps and related topics + +* **How to generate barcode in other formats** – `EncodeTypes.Code128`、`EncodeTypes.QR`、`EncodeTypes.DataMatrix` など 2‑D 用のフォーマットを調査してください。 +* **Embedding barcodes in PDFs** – Aspose.BarCode と Aspose.PDF を組み合わせて、請求書テンプレートに直接バーコードを配置できます。 +* **Dynamic barcode size based on user input** – ユーザー入力に基づいてサイズを計算する方法 + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで示したテクニックに基づく関連トピックをカバーしています。各リソースには、完全な動作コード例とステップバイステップの解説が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを探求するのに役立ちます。 + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/japanese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/japanese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..3dd6fc707 --- /dev/null +++ b/barcode/japanese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,286 @@ +--- +category: general +date: 2026-08-12 +description: PythonでDatabarバーコードのレイアウトを素早く設定します。列や行の設定方法、バーコードジェネレーターライブラリを使った画像の保存方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: ja +lastmod: 2026-08-12 +og_description: PythonでDatabarバーコードのレイアウトを設定し、列・行・画像出力を制御します。すぐに実行できるソリューションのガイドに従ってください。 +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: PythonでDatabarバーコードのレイアウトを設定する – 完全チュートリアル +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: PythonでDatabarバーコードのレイアウトを設定する – ステップバイステップガイド +url: /ja/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PythonでDatabarバーコードレイアウトを設定する – ステップバイステップガイド + +If you need to **configure Databar barcode layout in Python**, this guide walks you through the entire process. You’ll see how to set the number of columns or rows for a Databar Expanded Stacked barcode and how to save the resulting image with a single call to the barcode generator library. + +**PythonでDatabarバーコードレイアウトを設定**する必要がある場合、このガイドが全工程を案内します。Databar Expanded Stackedバーコードの列数または行数の設定方法と、バーコードジェネレーターライブラリを1回呼び出すだけで結果の画像を保存する方法が分かります。 + +Controlling the layout is essential when you embed barcodes on narrow packaging, receipts, or mobile screens. In the sections below we’ll cover the required imports, the two layout options (columns and rows), and the best practices for saving a clean PNG image. + +レイアウトの制御は、狭い包装材、レシート、モバイル画面にバーコードを埋め込む際に重要です。以下のセクションでは、必要なインポート、2つのレイアウトオプション(列と行)、そしてクリーンなPNG画像を保存するベストプラクティスを解説します。 + +## 必要なもの + +* Python 3.8 以上 +* `aspose.barcode`(または互換性のあるバーコード生成パッケージ)をインストール + ```bash + pip install aspose-barcode + ``` +* PNGファイルを保存するフォルダーへの書き込み権限 + +No additional external tools are required—the library handles rendering, scaling, and image encoding internally. + +追加の外部ツールは不要です。ライブラリが内部でレンダリング、スケーリング、画像エンコードを処理します。 + +## PythonでDatabarバーコードレイアウトを設定する方法 + +The core of the solution is the `BarcodeGenerator` class. It accepts an `EncodeTypes` enum that identifies the barcode symbology—in this case `EncodeTypes.DatabarExpandedStacked`. After creating the generator you can adjust the layout by setting the `columns` or `rows` properties on the `data_bar` parameter object. + +このソリューションの中心は `BarcodeGenerator` クラスです。バーコードシンボロジーを識別する `EncodeTypes` 列挙体を受け取り、ここでは `EncodeTypes.DatabarExpandedStacked` を使用します。ジェネレーターを作成した後、`data_bar` パラメータオブジェクトの `columns` または `rows` プロパティを設定してレイアウトを調整できます。 + +### 手順 1: 必要なクラスをインポート + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +These imports give you access to the generator, the enumeration for Databar types, and the PNG image format constant. + +これらのインポートにより、ジェネレーター、Databarタイプ用の列挙体、そして PNG 画像フォーマット定数にアクセスできます。 + +### 手順 2: Databar Expanded Stacked 用のバーコードジェネレーターを作成 + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Why this step?* +`EncodeTypes.DatabarExpandedStacked` は、ライブラリに **Databar Expanded Stacked** シンボロジーを生成させます。これにより、コンパクトなフットプリントを保ちつつ、長い数値文字列をサポートできます。第2引数はエンコードするデータで、Databar 仕様を満たす任意の文字列を指定できます。 + +### 手順 3: 列数を設定(水平レイアウト) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** はこの操作のキーフレーズです。列数を増やすと、バーコードが水平に広がり、幅の広いラベルに有用です。ライブラリは全体サイズを一定に保つためにモジュール幅を自動的に再計算します。 + +#### プロのコツ + +The maximum column count for Databar Expanded Stacked is 8. Setting a value higher than the limit will clamp it to the maximum, but it’s better to validate your input beforehand. + +Databar Expanded Stacked の最大列数は 8 です。上限を超える値を設定すると最大値にクランプされますが、事前に入力を検証する方が望ましいです。 + +### 手順 4: 列レイアウトでバーコード画像を保存 + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** は、レンダリングされたバーコードをディスクに書き込む操作です。PNG はロスレス形式で、信頼できるスキャンに必要なシャープなエッジを保持します。 + +### 手順 5: 同じバーコードタイプの2番目のジェネレーターを作成(行レイアウト) + +If you prefer a vertical stack, you work with rows instead of columns. The code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance to avoid mixing column and row settings. + +垂直スタックを好む場合は、列ではなく行を使用します。以下のコードは同じ値を再利用しますが、列と行の設定が混在しないように新しい `BarcodeGenerator` インスタンスを作成します。 + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### 手順 6: 行数を設定(垂直レイアウト) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** はバーコードモジュールを垂直に配置します。3 行のレイアウトは各スタックの高さを減らし、狭いレシートやモバイル画面に適したバーコードになります。 + +#### エッジケース + +If you set `rows` to 1, the library generates a single‑row Databar (equivalent to a standard Databar). Values below 1 are ignored and reset to the default (1 row). + +`rows` を 1 に設定すると、ライブラリはシングルロウ Databar(標準の Databar と同等)を生成します。1 未満の値は無視され、デフォルト(1 行)にリセットされます。 + +### 手順 7: 行レイアウトでバーコード画像を保存 + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Again, we **save barcode image** using PNG to keep the output crisp. + +再び、PNG を使用して **save barcode image** を実行し、出力を鮮明に保ちます。 + +## 完全に実行可能な例 + +Putting all the pieces together gives you a self‑contained script you can drop into any Python project. + +すべての要素を組み合わせると、任意の Python プロジェクトに組み込める自己完結型スクリプトが得られます。 + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**期待される出力** + +Running the script creates two PNG files: + +* `output/ExpandedCols4.png` – a barcode stretched across four columns +* `output/ExpandedRows3.png` – a barcode compressed into three rows + +Both images can be opened in any image viewer or imported directly into PDF invoices, label templates, or web pages. + +スクリプトを実行すると、2 つの PNG ファイルが作成されます: + +* `output/ExpandedCols4.png` – 4 列にわたって伸びたバーコード +* `output/ExpandedRows3.png` – 3 行に圧縮されたバーコード + +どちらの画像も任意の画像ビューアで開くことができ、PDF 請求書、ラベルテンプレート、ウェブページに直接インポートできます。 + +## よくある質問とトラブルシューティング + +| Question | Answer | +|----------|--------| +| *バーコードがぼやけて見える場合はどうすればいいですか?* | `save` を呼び出す前に `barcode_generator.parameters.image_width` と `image_height` を設定して画像解像度を上げます。 | +| *他の画像形式は使用できますか?* | はい。必要に応じて `BarCodeImageFormat.Png` を `Jpeg`、`Bmp`、または `Gif` に置き換えます。 | +| *データ長に制限はありますか?* | Databar Expanded Stacked は最大 74 桁の数字文字列をサポートします。上限を超えると `ArgumentException` がスローされます。 | +| *前景色を変更するには?* | `barcode_generator.parameters.barcode.color = Color.Blue` を使用します(`System.Drawing.Color` をインポート)。 | +| *列と行を組み合わせられますか?* | いいえ。API は列と行を相互排他的なレイアウトモードとして扱います。バーコードインスタンスごとにどちらか一方を選択してください。 | + +## 次のステップ + +Now that you can **configure Databar barcode layout**, consider exploring these related topics: + +これで **Databarバーコードレイアウトを設定** できるようになったので、以下の関連トピックを検討してください: + +* **テキストキャプションを追加** – `barcode_generator.parameters.barcode.code_text` を使用して、エンコードされた値を画像の下に表示します。 +* **バーコードを PDF に埋め込む** – 生成した PNG を `aspose.pdf` と組み合わせて印刷可能なドキュメントを作成します。 +* **動的サイズ設定** – ラベルの寸法に基づいて実行時に最適な列または行数を計算します。 +* **バッチ処理** – 製品コードの CSV をループして、バーコード画像のライブラリを自動生成します。 + +Experiment with different column and row values to see how they affect scan reliability on your target devices. The more you test, the better you’ll understand the trade‑offs between barcode size, readability, and space constraints. + +さまざまな列と行の値を試して、対象デバイスでのスキャン信頼性への影響を確認してください。テストすればするほど、バーコードサイズ、可読性、スペース制約のトレードオフをより深く理解できます。 + +--- + +*コーディングを楽しんでください!このチュートリアルが役立ったと思ったら、チームメイトと共有するか、直面したレイアウトの課題についてコメントを残してください。* + +## 次に学ぶべきこと? + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを取り上げています。各リソースには、ステップバイステップの解説付きの完全なコード例が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [DotCode バーコード画像の作成 – 行と列 (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [C# でバーコード画像を作成 – Codablock F の行と列を設定](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [一次元 Databar バーコードの高さ調整](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/japanese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/japanese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..574d7857a --- /dev/null +++ b/barcode/japanese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,230 @@ +--- +category: general +date: 2026-08-12 +description: C# で BarCodeGenerator を使用してバーコード画像を作成します。DataBar の生成方法、バーコード画像のサイズ調整、複数のバーコードを効率的に作成する方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: ja +lastmod: 2026-08-12 +og_description: BarCodeGenerator を使用して C# でバーコード画像を作成します。このチュートリアルでは、DataBar コードの生成方法、バーコード画像サイズの調整、複数のバーコードの作成方法をステップバイステップで示します。 +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: C#でバーコード画像を作成 – 完全なBarCodeGeneratorガイド +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: BarCodeGenerator を使用して C# でバーコード画像を作成する +url: /ja/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# と BarCodeGenerator を使用してバーコード画像を作成する + +.NET アプリケーションで **バーコード画像を作成** する必要がある場合、このガイドでは `BarCodeGenerator` クラスを使って正確に行う方法を示します。小売 POS システムや在庫管理ツールを構築しているかどうかに関わらず、DataBar シンボルの生成、バーコード画像サイズの制御、そして一度の実行で複数のバーコードを生成する方法を学べます。 + +また、**barcode generator c#** API を使用して寸法を調整したり、出力形式を切り替えたり、無効なデータ文字列などのエッジケースを処理できることもわかります。チュートリアルの最後までに、繰り返しコードを書くことなく自信を持って **複数のバーコードを作成** できるようになります。 + +## 前提条件 + +- .NET 6.0 以降がインストールされていること +- 開発環境 (Visual Studio、Rider、または VS Code) +- Aspose.BarCode for .NET NuGet パッケージ(または `BarCodeGenerator` を提供する互換ライブラリ) + +パッケージは次のコマンドで追加できます: + +```bash +dotnet add package Aspose.BarCode +``` + +## このチュートリアルでカバーする内容 + +1. DataBar Omni‑directional エンコーディング用の **barcode generator c#** インスタンスを設定する。 +2. X‑dimension とバー高さを変更して **barcode image size** を調整する。 +3. ループを使用して異なる高さの **multiple barcodes** を作成する。 +4. 画像を PNG ファイルとして保存し、出力を検証する。 + +すべてのコードスニペットは完全で、新しいコンソールプロジェクトにコピー&ペーストできる状態です。 + +![バーコード画像作成例](barcode-example.png){alt="バーコード画像作成例"} + +## ステップ 1: ジェネレータの初期化 – バーコード画像の基本作成 + +最初のステップは、目的のシンボリズムで `BarCodeGenerator` をインスタンス化することです。DataBar Omni‑directional シンボルの場合は `EncodeTypes.DatabarOmniDirectional` を使用します。 + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**重要性:** ジェネレータをインスタンス化することでエンコーディングルールとデータペイロードが定義されます。正しい `EncodeTypes` の値を省略すると、ライブラリはサポートされていないバーコードを生成するか、例外をスローします。 + +## ステップ 2: X‑dimension とバー高さの設定 – バーコード画像サイズの制御 + +バーコードの視覚的サイズは 2 つのパラメータで決まります。 + +| Parameter | 制御内容 | 標準範囲 | +|-----------|----------|----------| +| `x_dimension.pixels` | 最小モジュール(“ドット”)の幅 | 1 – 4 px | +| `bar_height.pixels` | 縦バーの高さ | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**プロのヒント:** 小さな X‑dimension は高解像度の画像を生成しますが、低品質のプリンターではスキャンが困難になる場合があります。対象のスキャン機器に合わせて値を調整してください。 + +## ステップ 3: 最初のバーコードを保存 – 30 px の高さでバーコード画像を作成 + +これで画像を生成し、ディスクに書き込むことができます。`Save` メソッドはファイルパスと画像フォーマットの列挙型を受け取ります。 + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**期待結果:** `C:\Barcodes` に `Databar30.png` という PNG ファイルが作成されます。ファイルを開くと、はっきりとした高コントラストのパターンを持つ DataBar Omni‑directional シンボルが表示されます。 + +## ステップ 4: 高さを変更して追加画像を生成 – 複数のバーコードを作成 + +異なる寸法で **複数のバーコード** を作成するには、`BarHeight` プロパティを変更し、再度 `Save` を呼び出すだけです。これによりジェネレータの再インスタンス化を回避でき、メモリと CPU 時間を節約できます。 + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**動作理由:** `BarCodeGenerator` オブジェクトはすべての設定状態を保持しています。単一のプロパティを変更するだけで次の `Save` 呼び出し時のレンダリングエンジンが更新され、効率的に **複数のバーコード** を作成できます。 + +## ステップ 5: 上級編 – カスタムデータで DataBar を生成する方法 + +上記の例は静的な GS1 ペイロードを使用しています。実際のシナリオでは可変の製品識別子を埋め込む必要があることが多いです。ライブラリは DataBar 仕様に合致する任意の文字列を受け入れます。 + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**重要ポイント:** `generator.CodeText` を設定すると、オブジェクトを再作成せずにエンコードされたデータが更新されます。大量のデータセットを扱う際に推奨される **how to generate databar** パターンです。 + +## ステップ 6: 検証とトラブルシューティング – 正しいバーコード画像サイズの確保 + +画像を生成した後、プログラム上で寸法が期待通りであることを確認したくなることがあります。`System.Drawing` の `Image` クラスを使用すると、ファイルを読み取りサイズを取得できます。 + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +設定した高さが反映されていない場合は、以下を確認してください: + +- **X‑dimension**: 非常に小さい値はレンダラが高さを丸める原因になることがあります。 +- **Image format**: JPEG などの一部フォーマットは保存時に圧縮を行い、ピクセル寸法が変わることがあります。PNG は正確な寸法を保持します。 + +## ステップ 7: バーコード画像サイズとパフォーマンスに関するベストプラクティス + +| 推奨事項 | 理由 | +|----------|------| +| ほとんどのスキャナで `x_dimension.pixels` を 2 – 3 px の範囲に保つ。 | 可読性とファイルサイズのバランスを取ります。 | +| 印刷する場合はロスレス出力の PNG を使用する。 | 正確な寸法と鮮明なエッジを保証します。 | +| 多数のバーコードを生成する際は単一の `BarCodeGenerator` インスタンスを再利用する。 | オブジェクト割り当てのオーバーヘッドを削減します。 | +| `CodeText` に割り当てる前に、入力文字列を GS1 標準に対して検証する。 | 実行時例外や無効なスキャンを防止します。 | +| 生成した画像は専用フォルダに明確な命名規則で保存する(例: `Databar_{GTIN}.png`)。 | 下流処理や監査トレイルを簡素化します。 | + +## 完全な動作例 + +以下は、初期化から検証までのすべてのステップを組み込んだ完全なプログラムです。コードを新しいコンソールプロジェクトにコピーして実行してください。 + + + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを取り上げています。各リソースには、完全な動作コード例とステップバイステップの解説が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [バーコード画像の生成 – GS1 クーポン UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode バーコード画像の作成 – 行と列 (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Aspose.BarCode for .NET を使用した ITF-14 のバーコードクワイエットゾーンの作成方法](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/japanese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/japanese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..7665f54d7 --- /dev/null +++ b/barcode/japanese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-08-12 +description: Pythonで全方向データバーを作成し、Aspose.BarCode を使用して Python のバーコード画像の作成方法を学びましょう。完全なソリューションのためのステップバイステップガイドをご確認ください。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: ja +lastmod: 2026-08-12 +og_description: Pythonで全方向データバーを作成し、数分でバーコード画像を生成します。このチュートリアルは、完全な実行可能な例を示しています。 +og_image_alt: example of create omni directional databar barcode image in Python +og_title: 全方向データバーの作成 – 完全Pythonガイド +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Pythonで全方向データバーとバーコード画像を作成する +url: /ja/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python でオムニ方向データバーとバーコード画像を作成する + +Python プロジェクトで **オムニ方向データバーを作成** したい場合、このガイドではその手順と **Python でバーコード画像を作成** する方法を Aspose.BarCode ライブラリを使って解説します。実行可能なスクリプトが提供され、異なるアスペクト比の PNG ファイルが 2 つ生成されます。 + +オムニ方向仕様に準拠した DataBar の生成は、小売や物流アプリケーションで一般的な要件です。本チュートリアルではインストール方法、X‑ディメンションの設定、アスペクト比の調整、最終画像の保存までをカバーします。外部サービスは不要で、すべてローカルで実行できます。 + +## 必要なもの + +開始する前に以下を確認してください。 + +* Python 3.8 以上がインストールされていること。 +* ターミナルまたはコマンドプロンプトが使用できること。 +* バーコード画像を保存するフォルダーへの書き込み権限があること。 + +唯一のサードパーティ依存は **Aspose.BarCode for Python via .NET** で、オムニ方向 DataBar タイプを標準でサポートしています。 + +## 手順 1: Aspose.BarCode for Python をインストール + +Aspose.BarCode はサンプルコードで使用する `BarcodeGenerator` クラスを提供します。`pip` でパッケージをインストールします。 + +```bash +pip install aspose-barcode +``` + +このパッケージには必要な .NET ランタイムバインディングが含まれているため、別途 .NET SDK をインストールする必要はありません。 + +## 手順 2: ライブラリをインポートしジェネレータを作成 + +スクリプトの最初の行で、スタックされたオムニ方向 DataBar 用のジェネレータを作成します。サンプルデータとして GTIN‑14 値 `(01)12345678901231` を使用しています。 + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*このステップが重要な理由*: `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` 定数は、ライブラリに値をオムニ方向 DataBar としてエンコードさせます。これは多くの POS スキャナで要求されるフォーマットです。 + +## 手順 3: X‑ディメンション(モジュール幅)を設定 + +X‑ディメンションは最小バー モジュールの幅を定義します。`2` ピクセルに設定すると、ファイルサイズが過大になることなく、読み取りやすいバーコードが生成されます。 + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*このステップが重要な理由*: X‑ディメンションを調整することで、可読性と画像サイズのバランスを取れます。小さすぎると低解像度プリンタでの印刷品質が低下します。 + +## 手順 4: アスペクト比を設定し最初の画像を保存 + +アスペクト比は DataBar の全体的な高さと幅の比率に影響します。`15` のアスペクト比はコンパクトなビジュアルスタイルを作り出します。 + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **プロのコツ**: `pathlib.Path` を使って出力パスを構築すると、欠落しているディレクトリが自動的に作成されます。 + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## 手順 5: アスペクト比を変更して別のビジュアルスタイルを作成し、別画像を保存 + +アスペクト比を `30` に変更すると、特定のスキャナハードウェアで必要とされる高さのあるバーコードが生成されます。 + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*このステップが重要な理由*: 小売業者やスキャナデバイスはそれぞれサイズ制約が異なります。1 つのスクリプトで両方のアスペクト比を生成できれば、コードを重複させずに必要なスタイルを作成できます。 + +## 完全なスクリプト – Python でオムニ方向データバーとバーコード画像を作成 + +以下はこれまでの手順をすべて組み込んだ実行可能なサンプルです。`generate_databar.py` として保存し、`python generate_databar.py` で実行してください。 + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### 期待される出力 + +スクリプトを実行すると次のファイルが作成されます。 + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +両方の画像は有効なオムニ方向 DataBar を示しており、標準的な小売機器でスキャン可能です。 + +![Python で作成したオムニ方向データバーとバーコード画像の例](example_databar.png "Python で作成したオムニ方向データバーとバーコード画像") + +*上の画像は、保存された 2 つの PNG ファイルを示すプレースホルダーです。* + +## よくある問題の対処法 + +| 問題 | 原因 | 対策 | +|------|------|------| +| `ImportError: No module named aspose` | Aspose.BarCode がインストールされていない、または別の環境にインストールされている | 正しい仮想環境をアクティブにし、`pip install aspose-barcode` を実行 | +| 保存時の `PermissionError` | スクリプトが対象フォルダーへの書き込み権限を持っていない | 自分が所有するディレクトリを選択するか、適切な権限でスクリプトを実行 | +| バーコードがスキャンできない | X‑ディメンションが小さすぎる、またはアスペクト比がスキャナに合わない | `x_dimension.pixels` を 3 または 4 に増やし、`aspect_ratio` を 20, 25 などで試す | +| .NET ランタイムが見つからない | Aspose.BarCode は Windows/Linux 上で .NET ランタイムに依存している | Microsoft のサイトから最新の .NET ランタイムをインストール。パッケージのドキュメントにプラットフォーム別の手順あり | + +## サンプルの拡張 + +スクリプトを他の DataBar バリアント(例: `DATABAR_STACKED`, `DATABAR_EXPANDED`)に対応させることも可能です。`EncodeTypes` 定数を適切に置き換えてください。 + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +PDF にバーコードを埋め込む必要がある場合は、Aspose.PDF for Python が PNG ファイルを直接インポートできるほか、`save` メソッドに `BarCodeImageFormat.Pdf` を指定して保存することもできます。 + +## 結論 + +本チュートリアルでは Aspose.BarCode を使用して **オムニ方向データバーを作成** し、**Python でバーコード画像を作成** する方法を示しました。これで、異なるアスペクト比の PNG ファイルを生成し、一般的な落とし穴に対処し、他のバーコード形式へ拡張できる完全なスクリプトが手に入ります。 + +次は QR コードの生成、PDF 請求書へのバーコード埋め込み、または大規模商品カタログ向けのバッチ処理自動化に挑戦してみてください。ここで学んだ `BarcodeGenerator` パターンを応用すれば、さまざまなシナリオに対応できます。コーディングを楽しんでください! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示した手法をベースにした関連トピックを扱っています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、API の追加機能習得や代替実装アプローチの探求に役立ちます。 + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to create barcode image and render it in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/japanese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/japanese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..d7de18c32 --- /dev/null +++ b/barcode/japanese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,252 @@ +--- +category: general +date: 2026-08-12 +description: Python を使ってバーコードを素早く生成する方法。データからバーコードを作成し、単一のライブラリでバーコード画像をエクスポートする方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: ja +lastmod: 2026-08-12 +og_description: Aspose.BarCode を使用して Python でバーコードを生成する方法。データからバーコードを作成し、バーコード画像を + PNG としてエクスポートするガイドです。 +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Pythonでバーコードを生成する方法 – 速くて信頼できるガイド +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Pythonでバーコードを生成する方法 – 完全ステップバイステップガイド +url: /ja/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pythonでバーコードを生成する方法 – 完全ステップバイステップガイド + +Pythonアプリケーションで **バーコードの生成方法** が必要な場合、このチュートリアルでは必要な正確なコードを示します。**データからバーコードを作成** し、外観を調整し、**バーコード画像をPNGファイルとしてエクスポート** する方法を学びます—すべて10行未満のコードで実現できます。 + +バーコードの生成はビジネスロジックの別個の関心事のように感じられるかもしれませんが、単一のライブラリを使用すれば既存のコードベースに組み込んで処理を行うことができます。以下のセクションでは、完全に実行可能な例を示し、各行が重要な理由を理解し、モジュール幅の変更やアウトラインのみのバーコード描画といった一般的なバリエーションを紹介します。 + +## Aspose.BarCode ライブラリでバーコードを生成する方法 + +Python 用 (via .NET) の Aspose.BarCode ライブラリは、この記事で使用する Planet バーコードを含む多くのシンボロジーに対してシンプルな API を提供します。開始する前に、パッケージがインストールされていることを確認してください: + +```bash +pip install aspose-barcode +``` + +> **プロのコツ:** 仮想環境を使用して、他のプロジェクトとのバージョン競合を回避しましょう。 + +### 1. 必要なクラスをインポートする + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +これらのインポートにより、ジェネレータクラス、バーコードタイプの列挙、および結果を保存する際に使用する画像フォーマット列挙にアクセスできます。 + +### 2. データからバーコードを作成する + +最初のステップは **データからバーコードを作成** することです。`BarcodeGenerator` コンストラクタはシンボロジーとエンコードしたい生文字列を受け取ります。 + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +`EncodeTypes.Planet` の値は Planet バーコードを選択し、`"123456"` は最終画像に表示されるペイロードです。 + +### 3. X‑dimension(モジュール幅)を調整する + +X‑dimension は各バーコードモジュール(細いバー)の幅を制御します。4 ピクセルに設定すると、ファイルサイズが大きくなりすぎず、クリアで読みやすい画像になります。 + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **重要な理由:** 大きな X‑dimension は低解像度プリンターでのスキャン信頼性を向上させ、逆に小さな値はウェブ使用時のファイルサイズを削減します。 + +### 4. バーコード画像をエクスポートする(塗りつぶしスタイル) + +これで `save` メソッドを使用して **バーコード画像をエクスポート** できます。例では PNG ファイルを保存していますが、`BarCodeImageFormat` 列挙を変更すれば JPEG、BMP、TIFF も選択可能です。 + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +ファイル `PlanetFilled.png` には完全に塗りつぶされた Planet バーコードが含まれており、印刷や PDF への埋め込みにすぐ使用できます。 + +### 5. アウトラインのみのバーコード用に2つ目のジェネレータを作成する + +アウトラインバージョン(バーが空)の必要がある場合、画像保存後に `filled_bars` フラグを切り替えることはできないため、新しいジェネレータを作成する必要があります。 + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. 同じ X‑dimension 設定を適用する + +2つ目のジェネレータを作成する際は、一貫性を保つために視覚設定を再度適用する必要があります。 + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. アウトラインバーコードの塗りつぶしバーを無効にする + +`filled_bars` を `False` に設定すると、レンダラは各モジュールのアウトラインのみを描画し、デザイン目的で役立つ軽い画像が生成されます。 + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. アウトラインバーコード画像をエクスポートする + +最後に、再度 **バーコード画像をエクスポート** し、今回はアウトラインバージョンを保存します。 + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +これで 2 つの PNG ファイルが作成されました:実線バーの `PlanetFilled.png` とアウトラインのみの `PlanetEmpty.png` です。 + +## 他の形式でバーコード画像をエクスポートする(オプション) + +`save` メソッドは複数の形式をサポートしています。90 % の品質で JPEG としてエクスポートするには: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +ウェブ用に透過背景が必要な場合は、アルファチャンネル付きの PNG を選択してください: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## 一般的なバリエーションとエッジケース + +| シナリオ | 必要な変更 | コードスニペット | +|----------|---------------|--------------| +| **異なるシンボロジー**(例:QR) | 別の `EncodeTypes` 値を使用する | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **カスタム前景色** | `fore_color` を設定する | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **高解像度** | `image_width` と `image_height` で DPI を上げる | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **大きなデータ文字列** | データ長がシンボロジー仕様に合うことを確認する | ジェネレータ作成前に長さを検証する | + +> **注意:** 選択したシンボロジーの最大長を超えるデータを提供すると、ランタイム例外が発生します。常に文字列長を検証するか、`ArgumentException` を捕捉してください。 + +## 完全な実行可能サンプル + +以下は `generate_planet_barcode.py` という名前のファイルにコピー&ペーストできる完全なスクリプトです。`YOUR_DIRECTORY` を、マシン上に存在するフォルダーに変更してください。 + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +このスクリプトを実行すると、指定ディレクトリに 2 つの PNG ファイルが生成されます。任意の画像ビューアで画像を開いて出力を確認してください。どちらも文字列 `123456` をエンコードした Planet バーコードが表示されます。 + +## 結論 + +これで、Aspose.BarCode を使用して Python で **バーコードを生成する方法**、**データからバーコードを作成する方法**、そして塗りつぶしスタイルとアウトラインスタイルの両方で **バーコード画像をエクスポートする方法** が分かりました。同じパターンは他のシンボロジー、画像形式、視覚カスタマイズにも適用でき、アプリケーション内のあらゆるバーコード関連機能の柔軟な基盤となります。 + +### 次のステップ + +* QR、Code‑128、DataMatrix などの他のシンボロジーを調査し、`EncodeTypes.Planet` を目的の値に置き換えてみてください。 +* `ReportLab` や `PyPDF2` などのライブラリを使用して、生成した PNG ファイルを PDF レポートに統合します。 +* 画面解像度やプリンター DPI に応じてバーコードサイズを調整できるよう、動的な X‑dimension 値を試してみてください。 + +コーディングを楽しんでください。また、例を自由にカスタマイズしてご自身のプロジェクト要件に合わせてください! + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを扱っています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、追加の API 機能を習得し、プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [JavaでAspose.BarCodeを使用してバーコード画像を生成する方法](/barcode/english/java/barcode-rendering-techniques/) +- [Javaでバーコードを生成する – 完全設定ガイド](/barcode/english/java/barcode-configuration/) +- [JavaでAspose.BarCodeを使用してcode128バーコード画像を作成する方法](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/korean/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/korean/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..442a1afa4 --- /dev/null +++ b/barcode/korean/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-08-12 +description: 정확한 픽셀 크기로 바코드를 생성하는 방법을 보여주는 바코드 생성기 예제입니다. 모듈 폭, 바 높이를 설정하고 Planet + 바코드를 만드는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: ko +lastmod: 2026-08-12 +og_description: 바코드 생성기 예제는 정확한 픽셀 치수로 바코드를 생성하는 방법을 보여줍니다. 이 가이드를 따라 Planet 및 RM4SCC + 코드의 모듈 너비와 바 높이를 제어하세요. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: 바코드 생성기 예제 – C#에서 픽셀 크기 맞춤 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: 바코드 생성기 예제 – 사용자 지정 픽셀 크기를 위한 단계별 가이드 +url: /ko/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 바코드 생성기 예제 – 사용자 지정 픽셀 크기를 위한 단계별 가이드 + +모든 픽셀을 제어할 수 있는 **barcode generator example**이 필요하다면, 이 가이드는 정확한 방법을 보여줍니다. 모듈 너비를 설정하고, 고정된 바 높이를 정의하며, Planet 및 RM4SCC 바코드를 예측 가능한 크기로 생성하는 방법을 배울 수 있습니다. + +대부분의 개발자는 모든 화면이나 프린터에서 동일하게 보이는 “how to generate barcode” 이미지 생성에 어려움을 겪습니다. 아래 코드 스니펫은 Aspose.BarCode for .NET 라이브러리의 픽셀 수준 매개변수를 노출하여 추측 없이 일관된 출력을 만들 수 있게 해줍니다. + +## 배울 내용 + +* 필수 NuGet 패키지를 설치하는 방법. +* 자동 계산된 높이로 Planet 바코드를 생성하는 방법. +* 명시적인 100픽셀 높이로 Planet 바코드를 생성하는 방법. +* 같은 명시적 높이를 사용하여 RM4SCC 바코드를 생성하는 방법. +* **barcode pixel size**가 스캔 신뢰성에 중요한 이유. +* Planet 바코드 이미지를 생성할 때 흔히 발생하는 문제를 해결하기 위한 팁. + +.NET 6 이상, 기본 C# 개발 환경, 그리고 NuGet 패키지를 가져올 인터넷 연결만 있으면 됩니다. + +--- + +## barcode generator example – 개발 환경 설정 + +코드를 작성하기 전에 Aspose.BarCode 라이브러리가 프로젝트에 포함되어 있는지 확인하세요. + +### Aspose.BarCode 패키지 설치 + +프로젝트 폴더에서 터미널을 열고 다음 명령을 실행합니다: + +```bash +dotnet add package Aspose.BarCode +``` + +이 명령은 최신 안정 버전의 **Aspose.BarCode**를 `csproj`에 추가합니다. 복원이 완료되면 `BarcodeGenerator` 클래스를 사용할 수 있습니다. + +> **Pro tip:** 최신 성능 향상 및 기본 UTF‑8 처리를 활용하려면 .NET 6 또는 .NET 7을 대상으로 설정하세요. + +### 필요한 `using` 지시문 추가 + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +이 네임스페이스들은 튜토리얼에서 나중에 사용할 `BarcodeGenerator` 클래스와 `BarCodeImageFormat` 열거형을 노출합니다. + +--- + +## 사용자 지정 픽셀 크기로 바코드 생성하기 + +다음 세 단계는 전체 **barcode generator example**을 보여줍니다. 각 단계는 이전 단계 위에 구축되므로 전체 블록을 콘솔 앱에 복사‑붙여넣기하고 그대로 실행할 수 있습니다. + +### Step 1 – 자동 계산된 높이로 Planet 바코드 생성 + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**왜 작동하나요:** +*`XDimension` 속성은 단일 바코드 모듈(가장 작은 검은색 또는 흰색 요소)의 너비를 정의합니다. `BarHeight`를 생략하면 라이브러리는 Planet 코드의 표준 종횡비를 유지하는 높이를 계산합니다.* + +**예상 출력:** `PlanetAuto.png`라는 PNG 파일에 깔끔한 Planet 바코드가 포함됩니다. 높이는 4픽셀 모듈 너비에 맞게 조정되며, 일반적으로 6자리 데이터에 대해 약 60 픽셀 정도입니다. + +### Step 2 – 명시적인 100픽셀 높이로 Planet 바코드 생성 + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**왜 필요할 수 있나요:** +스캔 장비가 신뢰할 수 있는 감지를 위해 최소 바 높이를 요구하는 경우가 있습니다. `BarHeight.Pixels`를 설정하면 인코딩된 데이터 길이에 관계없이 모든 생성 이미지가 해당 요구 사항을 충족함을 보장합니다. + +**예상 출력:** `PlanetHeight100.png`는 이전과 동일한 데이터를 표시하지만, 바가 정확히 100 픽셀 높이로 설정되어 시각적 크기를 완전히 제어할 수 있습니다. + +### Step 3 – 동일한 명시적 높이로 RM4SCC 바코드 생성 + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**왜 중요한가:** +`EncodeTypes.RM4SCC`는 물류에서 사용되는 스택형 선형 바코드입니다. Planet 바코드와 바 높이를 맞추면 두 심볼이 동일 라벨에 나타날 때 배치 처리 작업이 간소화됩니다. + +**예상 출력:** `RM4SCCHeight100.png`는 완벽한 크기의 RM4SCC 바코드를 표시하며, Planet 코드에 설정한 100‑픽셀 높이와 일치합니다. + +> **Result verification:** 각 PNG 파일을 이미지 뷰어에서 열어 검은 바가 정확히 4 픽셀 너비이며 지정한 경우 100 픽셀 높이인지 확인하세요. 또한 파일을 바코드 스캐너 앱에 넣어 “123456”으로 디코딩되는지 확인할 수 있습니다. + +--- + +## 바코드 픽셀 크기와 바 높이 이해하기 + +### **barcode pixel size**란 무엇인가? + +*Pixel size*는 단일 모듈(`XDimension`)을 나타내는 화면 또는 프린터 픽셀의 실제 수를 의미합니다. 픽셀 크기가 클수록 바코드가 커져 저해상도 스캐너에 더 쉬워질 수 있지만 라벨 공간을 더 많이 차지합니다. + +### `BarHeight`가 가독성에 미치는 영향 + +`BarHeight` 속성은 바의 수직 길이를 제어합니다. 대부분의 1‑D 바코드(Planet 및 RM4SCC 포함) 표준은 300 dpi로 인쇄할 경우 최소 10 mm 높이를 권장하며, 이는 대략 118 픽셀에 해당합니다. 이보다 낮은 높이로 설정하면 특히 모바일 카메라에서 읽기 오류가 발생할 수 있습니다. + +### 언제 라이브러리에 높이 자동 계산을 맡겨야 할까? + +스크린에만 표시할 바코드를 생성한다면 자동 계산이 종횡비를 일관되게 유지하고 수동 조정량을 줄여줍니다. 엄격한 ISO 규격을 만족해야 하는 인쇄 라벨의 경우 **바 높이를 명시적으로 설정**해야 합니다. + +--- + +## Planet 바코드 생성 시 흔히 발생하는 함정과 모범 사례 + +| 함정 | 왜 발생하는가 | 해결 방법 | +|------|--------------|----------| +| 바가 너무 얇거나 두껍게 보임 | 고해상도 디스플레이에서 `XDimension`이 기본값(1 픽셀)으로 남아 있음 | 시각적 선명도를 위해 `XDimension.Pixels`를 최소 3‑4로 설정 | +| 스캐너가 코드를 읽지 못함 | `BarHeight`가 스캐너 초점 거리보다 작음 | 대부분의 모바일 스캐너에 대해 `BarHeight.Pixels`를 100 이상 사용 | +| 스케일링 후 이미지가 흐릿함 | JPEG 저장 시 압축 아티팩트 발생 | 무손실 출력을 위해 PNG(`BarCodeImageFormat.Png`)로 저장 | +| 예상치 못한 바코드 유형 | `EncodeTypes` 열거형 값이 잘못 지정됨 | Planet 심볼에 `EncodeTypes.Planet`을 사용했는지 다시 확인 | + +### 성능에 대한 Pro tip + +배치 작업에서 수천 개의 바코드를 생성할 때는 단일 `BarcodeGenerator` 인스턴스를 재사용하고 저장 사이에 `CodeText`와 크기 매개변수만 변경하세요. 이렇게 하면 내부 렌더링 객체의 반복 할당을 방지하고 실행 시간을 최대 30 %까지 단축할 수 있습니다. + +--- + +## 전체 작업 예제 – 모든 것을 합치기 + +`dotnet new console -n BarcodeDemo` 명령으로 새 콘솔 프로젝트를 만들고 `Program.cs` 내용을 다음과 교체합니다: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +`dotnet run`으로 프로그램을 실행합니다. 실행 후 프로젝트 폴더에 세 개의 PNG 파일이 생성되며, 각각 다른 **barcode generator example** 시나리오를 보여줍니다. + +--- + +## 다음 단계 및 관련 주제 + +* **다른 형식으로 바코드 생성하기** – 2‑D 필요에 따라 `EncodeTypes.Code128`, `EncodeTypes.QR`, `EncodeTypes.DataMatrix`를 살펴보세요. +* **PDF에 바코드 삽입** – Aspose.BarCode와 Aspose.PDF를 결합하여 청구서 템플릿에 바코드를 직접 배치합니다. +* **사용자 입력에 따라 바코드 크기를 동적으로 계산** – 계산 + +## 다음에 배워야 할 내용은? + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료에는 단계별 설명이 포함된 완전한 코드 예제가 제공되어 추가 API 기능을 숙달하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/korean/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/korean/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..aa327fb86 --- /dev/null +++ b/barcode/korean/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: Python에서 Databar 바코드 레이아웃을 빠르게 구성하세요. 열과 행을 설정하고 바코드 생성기 라이브러리로 이미지를 + 저장하는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: ko +lastmod: 2026-08-12 +og_description: Python에서 Databar 바코드 레이아웃을 구성하여 열, 행 및 이미지 출력을 제어합니다. 바로 실행 가능한 솔루션을 + 위해 이 가이드를 따라보세요. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Python에서 Databar 바코드 레이아웃 구성 – 완전 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Python에서 Databar 바코드 레이아웃 구성 – 단계별 가이드 +url: /ko/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python에서 Databar 바코드 레이아웃 구성 – 단계별 가이드 + +Python에서 **Databar 바코드 레이아웃을 구성**해야 한다면, 이 가이드는 전체 과정을 단계별로 안내합니다. Databar Expanded Stacked 바코드의 열 또는 행 수를 설정하는 방법과 바코드 생성 라이브러리를 한 번 호출하여 결과 이미지를 저장하는 방법을 확인할 수 있습니다. + +좁은 포장, 영수증, 모바일 화면 등에 바코드를 삽입할 때 레이아웃 제어는 필수입니다. 아래 섹션에서는 필요한 import, 두 가지 레이아웃 옵션(열 및 행) 및 깨끗한 PNG 이미지를 저장하기 위한 모범 사례를 다룹니다. + +## 필요 사항 + +* Python 3.8 이상 +* `aspose.barcode` (또는 호환 가능한 바코드 생성 패키지) 설치 + ```bash + pip install aspose-barcode + ``` +* PNG 파일이 저장될 폴더에 대한 쓰기 권한 + +추가 외부 도구는 필요하지 않습니다—라이브러리가 렌더링, 스케일링 및 이미지 인코딩을 내부적으로 처리합니다. + +## Python에서 Databar 바코드 레이아웃 구성 방법 + +솔루션의 핵심은 `BarcodeGenerator` 클래스입니다. 이 클래스는 바코드 심볼을 식별하는 `EncodeTypes` 열거형을 받으며, 여기서는 `EncodeTypes.DatabarExpandedStacked`를 사용합니다. 생성기를 만든 후 `data_bar` 파라미터 객체의 `columns` 또는 `rows` 속성을 설정하여 레이아웃을 조정할 수 있습니다. + +### 단계 1: 필요한 클래스 가져오기 + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +이 import를 통해 생성기, Databar 유형 열거형 및 PNG 이미지 포맷 상수에 접근할 수 있습니다. + +### 단계 2: Databar Expanded Stacked용 바코드 생성기 만들기 + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Why this step?* +`EncodeTypes.DatabarExpandedStacked`는 라이브러리에게 **Databar Expanded Stacked** 심볼을 생성하도록 지시합니다. 이 심볼은 더 긴 숫자 문자열을 지원하면서도 컴팩트한 공간을 유지합니다. 두 번째 인자는 인코딩할 데이터이며, Databar 사양을 충족하는 문자열이면 무엇이든 사용할 수 있습니다. + +### 단계 3: 열 수 설정 (가로 레이아웃) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns**는 이 작업의 핵심 구문입니다. 열 수를 늘리면 바코드가 가로로 펼쳐져 넓은 라벨에 유용합니다. 라이브러리는 전체 크기를 일정하게 유지하도록 모듈 폭을 자동으로 재계산합니다. + +#### 팁 +Databar Expanded Stacked의 최대 열 수는 8입니다. 제한보다 높은 값을 설정하면 최대값으로 제한되지만, 사전에 입력값을 검증하는 것이 좋습니다. + +### 단계 4: 열 레이아웃으로 바코드 이미지 저장 + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image**는 렌더링된 바코드를 디스크에 기록하는 동작입니다. PNG는 무손실 포맷으로, 신뢰할 수 있는 스캔에 필요한 선명한 가장자리를 보존합니다. + +### 단계 5: 동일한 바코드 유형에 대한 두 번째 생성기 만들기 (행 레이아웃) + +세로 스택을 선호한다면 열 대신 행을 사용합니다. 아래 코드는 동일한 값을 재사용하지만, 열과 행 설정이 섞이지 않도록 새로운 `BarcodeGenerator` 인스턴스를 생성합니다. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### 단계 6: 행 수 설정 (세로 레이아웃) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows**는 바코드 모듈을 세로로 배열합니다. 3행 레이아웃은 각 스택의 높이를 줄여 좁은 영수증이나 모바일 화면에 적합한 바코드를 만듭니다. + +#### 예외 상황 +`rows`를 1로 설정하면 라이브러리는 단일 행 Databar(표준 Databar와 동일)를 생성합니다. 1보다 작은 값은 무시되고 기본값(1행)으로 재설정됩니다. + +### 단계 7: 행 레이아웃으로 바코드 이미지 저장 + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +다시 한 번 **save barcode image**를 사용해 PNG로 저장하면 출력이 선명하게 유지됩니다. + +## 전체 실행 가능한 예제 + +모든 요소를 결합하면 어떤 Python 프로젝트에도 바로 넣을 수 있는 독립 실행형 스크립트를 얻을 수 있습니다. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**예상 출력** + +스크립트를 실행하면 두 개의 PNG 파일이 생성됩니다: + +* `output/ExpandedCols4.png` – 네 열에 걸쳐 늘어난 바코드 +* `output/ExpandedRows3.png` – 세 행으로 압축된 바코드 + +두 이미지 모두 이미지 뷰어에서 열어볼 수 있으며 PDF 인보이스, 라벨 템플릿 또는 웹 페이지에 직접 삽입할 수 있습니다. + +## 일반적인 질문 및 문제 해결 + +| Question | Answer | +|----------|--------| +| *What if the barcode looks blurry?* | `barcode_generator.parameters.image_width`와 `image_height`를 `save` 호출 전에 설정하여 이미지 해상도를 높이세요. | +| *Can I use other image formats?* | 예. `BarCodeImageFormat.Png`를 필요에 따라 `Jpeg`, `Bmp`, `Gif` 등으로 교체하면 됩니다. | +| *Is there a limit on the data length?* | Databar Expanded Stacked은 최대 74개의 숫자 문자를 지원합니다. 제한을 초과하면 `ArgumentException`이 발생합니다. | +| *How do I change the foreground color?* | `barcode_generator.parameters.barcode.color = Color.Blue`를 사용하세요 (`System.Drawing.Color`를 import). | +| *Can I combine columns and rows?* | 아니요. API는 열과 행을 상호 배타적인 레이아웃 모드로 취급합니다. 바코드 인스턴스당 하나만 선택하세요. | + +## 다음 단계 + +이제 **Databar 바코드 레이아웃을 구성**할 수 있게 되었으니, 다음 관련 주제들을 살펴보세요: + +* **Add text captions** – `barcode_generator.parameters.barcode.code_text`를 사용해 인코딩된 값을 이미지 아래에 표시합니다. +* **Embed the barcode in a PDF** – 생성된 PNG를 `aspose.pdf`와 결합해 인쇄 가능한 문서를 만듭니다. +* **Dynamic sizing** – 실행 시 라벨 크기에 따라 최적의 열 또는 행 수를 계산합니다. +* **Batch processing** – CSV 파일에 있는 제품 코드를 순회하면서 바코드 이미지 라이브러리를 자동으로 생성합니다. + +다양한 열·행 값을 실험해 보면서 대상 디바이스에서 스캔 신뢰도에 어떤 영향을 주는지 확인하세요. 테스트를 많이 할수록 바코드 크기, 가독성 및 공간 제약 사이의 트레이드오프를 더 잘 이해하게 됩니다. + +--- + +*Happy coding! If you found this tutorial useful, share it with teammates or leave a comment about the layout challenges you faced.* + +## 다음에 배워야 할 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 주제를 다룹니다. 각 리소스에는 완전한 코드 예제와 단계별 설명이 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에 적용할 수 있는 다양한 구현 방법을 탐색할 수 있습니다. + +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Create barcode image c# – Configure Codablock F Rows & Columns](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [One-Dimensional Databar Barcode Height Adjustment](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/korean/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/korean/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..c41196b4e --- /dev/null +++ b/barcode/korean/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-08-12 +description: BarCodeGenerator를 사용하여 C#에서 바코드 이미지를 생성합니다. DataBar를 생성하는 방법, 바코드 이미지 + 크기를 제어하는 방법, 그리고 여러 바코드를 효율적으로 만드는 방법을 배웁니다. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: ko +lastmod: 2026-08-12 +og_description: BarCodeGenerator를 사용하여 C#에서 바코드 이미지를 생성합니다. 이 튜토리얼에서는 DataBar 코드를 + 생성하고, 바코드 이미지 크기를 조정하며, 여러 개의 바코드를 만드는 방법을 단계별로 보여줍니다. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: C#에서 바코드 이미지 만들기 – 완전한 BarCodeGenerator 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: BarCodeGenerator를 사용해 C#에서 바코드 이미지 만들기 +url: /ko/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#와 BarCodeGenerator를 사용하여 바코드 이미지 만들기 + +.NET 애플리케이션에서 **바코드 이미지 생성**이 필요하다면, 이 가이드는 `BarCodeGenerator` 클래스를 사용하여 정확히 수행하는 방법을 보여줍니다. 소매 POS 시스템이나 재고 추적 도구를 구축하든, DataBar 심볼을 생성하고, 바코드 이미지 크기를 제어하며, 한 번에 여러 바코드를 생성하는 방법을 배울 수 있습니다. + +또한 **barcode generator c#** API를 사용해 차원 조정, 출력 형식 전환, 잘못된 데이터 문자열과 같은 예외 상황을 처리하는 방법을 알게 됩니다. 튜토리얼이 끝날 때쯤에는 반복 코드를 작성하지 않고도 자신 있게 **여러 바코드 생성**을 할 수 있습니다. + +## 사전 요구 사항 + +- .NET 6.0 이상이 설치되어 있어야 합니다 +- 개발 환경 (Visual Studio, Rider, 또는 VS Code) +- Aspose.BarCode for .NET NuGet 패키지(또는 `BarCodeGenerator`를 제공하는 호환 라이브러리) + +You can add the package with: + +```bash +dotnet add package Aspose.BarCode +``` + +## 이 튜토리얼에서 다루는 내용 + +1. DataBar Omni‑directional 인코딩을 위한 **barcode generator c#** 인스턴스 설정. +2. X‑dimension 및 bar height를 변경하여 **barcode image size** 조정. +3. 루프를 사용해 서로 다른 높이의 **multiple barcodes** 생성. +4. 이미지를 PNG 파일로 저장하고 출력 결과를 검증. + +모든 코드 스니펫은 완전하며 새 콘솔 프로젝트에 복사‑붙여넣기 할 준비가 되어 있습니다. + +![바코드 이미지 생성 예시](barcode-example.png){alt="바코드 이미지 생성 예시"} + +## 1단계: 생성기 초기화 – 바코드 이미지 기본 설정 + +첫 번째 단계는 원하는 심볼을 사용하여 `BarCodeGenerator`를 인스턴스화하는 것입니다. DataBar Omni‑directional 심볼의 경우 `EncodeTypes.DatabarOmniDirectional`를 사용합니다. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**왜 중요한가:** 생성기를 인스턴스화하면 인코딩 규칙과 데이터 페이로드가 정의됩니다. 올바른 `EncodeTypes` 값을 생략하면 라이브러리가 지원되지 않는 바코드를 생성하거나 예외를 발생시킵니다. + +## 2단계: X‑dimension 및 bar height 구성 – 바코드 이미지 크기 제어 + +바코드의 시각적 크기는 두 가지 매개변수에 의해 결정됩니다: + +| 매개변수 | 제어하는 내용 | 일반 범위 | +|-----------|------------------|---------------| +| `x_dimension.pixels` | 가장 작은 모듈(‘점’)의 너비 | 1 – 4 px | +| `bar_height.pixels` | 수직 바의 높이 | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**팁:** X‑dimension이 작을수록 고해상도 이미지가 되지만 저품질 프린터에서는 스캔이 어려울 수 있습니다. 목표 스캔 장비에 따라 값을 조정하세요. + +## 3단계: 첫 번째 바코드 저장 – 30 px 높이의 바코드 이미지 생성 + +이제 이미지를 생성하고 디스크에 저장할 수 있습니다. `Save` 메서드는 파일 경로와 이미지 형식 열거형을 받습니다. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**예상 결과:** `C:\Barcodes`에 `Databar30.png`라는 PNG 파일이 생성됩니다. 파일을 열면 선명하고 고대비 패턴의 DataBar Omni‑directional 심볼이 표시됩니다. + +## 4단계: 높이 변경 및 추가 이미지 생성 – 여러 바코드 만들기 + +다른 차원의 **multiple barcodes**를 만들려면 `BarHeight` 속성을 수정하고 `Save`를 다시 호출하기만 하면 됩니다. 이렇게 하면 생성기를 다시 인스턴스화할 필요가 없어 메모리와 CPU 시간을 절약할 수 있습니다. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**왜 작동하는가:** `BarCodeGenerator` 객체는 모든 구성 상태를 보유합니다. 단일 속성을 변경하면 다음 `Save` 호출을 위한 렌더링 엔진이 업데이트되어 **multiple barcodes**를 효율적으로 생성할 수 있습니다. + +## 5단계: 고급 – 사용자 정의 데이터로 DataBar 생성 방법 + +위 예제는 정적 GS1 페이로드를 사용합니다. 실제 상황에서는 가변적인 제품 식별자를 삽입해야 할 경우가 많습니다. 라이브러리는 DataBar 사양에 맞는 문자열이면 어떤 것이든 허용합니다. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**핵심 포인트:** `generator.CodeText`를 설정하면 객체를 다시 생성하지 않고도 인코딩된 데이터가 업데이트됩니다. 대량 데이터 세트를 처리할 때 권장되는 **how to generate databar** 패턴입니다. + +## 6단계: 검증 및 문제 해결 – 올바른 바코드 이미지 크기 보장 + +이미지를 생성한 후, 차원이 기대와 일치하는지 프로그램matically 확인하고 싶을 수 있습니다. `System.Drawing`의 `Image` 클래스를 사용하면 파일을 읽고 크기를 보고할 수 있습니다. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +If the height does not reflect the value you set, check: + +- **X‑dimension**: 매우 작은 값은 렌더러가 높이를 반올림하게 만들 수 있습니다. +- **Image format**: 일부 형식(예: JPEG)은 저장 시 압축을 적용하여 픽셀 차원을 변경할 수 있습니다. PNG는 정확한 차원을 유지합니다. + +## 7단계: 바코드 이미지 크기 및 성능을 위한 모범 사례 + +| 권장 사항 | 이유 | +|----------------|--------| +| 대부분의 스캐너에 대해 `x_dimension.pixels`를 2 – 3 px 사이로 유지합니다. | 가독성과 파일 크기의 균형을 맞춥니다. | +| 이미지를 인쇄할 경우 무손실 출력을 위해 PNG를 사용합니다. | 정확한 차원과 선명한 가장자리를 보장합니다. | +| 다수의 바코드를 생성할 때 단일 `BarCodeGenerator` 인스턴스를 재사용합니다. | 객체 할당 오버헤드를 감소시킵니다. | +| `CodeText`에 할당하기 전에 입력 문자열을 GS1 표준에 맞게 검증합니다. | 런타임 예외와 잘못된 스캔을 방지합니다. | +| 생성된 이미지를 전용 폴더에 명확한 명명 규칙(예: `Databar_{GTIN}.png`)으로 저장합니다. | 후속 처리와 감사 추적을 단순화합니다. | + +## 전체 작동 예제 + +아래는 초기화부터 검증까지 모든 단계를 포함한 완전한 프로그램입니다. 코드를 새 콘솔 프로젝트에 복사하고 실행하세요. + + + +## 다음에 배워야 할 내용 + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료는 단계별 설명과 함께 완전한 작동 코드 예제를 제공하여 추가 API 기능을 마스터하고 자체 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [바코드 이미지 생성 – GS1 쿠폰 UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode 바코드 이미지 생성 – 행 및 열 (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Aspose.BarCode for .NET을 사용하여 ITF-14 바코드 Quiet Zone 생성 방법](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/korean/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/korean/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..beb956819 --- /dev/null +++ b/barcode/korean/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-08-12 +description: Python으로 전방향 데이터바를 생성하고 Aspose.BarCode를 사용하여 Python에서 바코드 이미지를 만드는 방법을 + 배워보세요. 완전한 솔루션을 위한 단계별 가이드를 따라하세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: ko +lastmod: 2026-08-12 +og_description: Python으로 전방위 데이터바를 생성하고 몇 분 안에 바코드 이미지를 만들 수 있습니다. 이 튜토리얼은 완전하고 실행 + 가능한 예제를 보여줍니다. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: 전방향 데이터바 만들기 – 전체 파이썬 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Python에서 전방위 데이터바 및 바코드 이미지 만들기 +url: /ko/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python에서 omni directional databar 및 barcode 이미지 만들기 + +If you need to **create omni directional databar** in a Python project, this guide shows you how to do it and also how to **create barcode image python** using the Aspose.BarCode library. You will get a ready‑to‑run script that produces two PNG files with different aspect ratios. + +Python 프로젝트에서 **omni directional databar**를 생성해야 한다면, 이 가이드는 그 방법과 Aspose.BarCode 라이브러리를 사용하여 **barcode image python**을 생성하는 방법을 보여줍니다. 실행 준비가 된 스크립트를 받아 두 개의 PNG 파일을 서로 다른 종횡비로 생성할 수 있습니다. + +Generating a DataBar that follows the Omni‑directional specification is a common requirement for retail and logistics applications. The tutorial covers installation, configuration of the X‑dimension, adjustment of the aspect ratio, and saving the final images. No external services are required; everything runs locally. + +Omni‑directional 사양을 따르는 DataBar를 생성하는 것은 소매 및 물류 애플리케이션에서 일반적인 요구 사항입니다. 이 튜토리얼에서는 설치, X‑dimension 설정, 종횡비 조정 및 최종 이미지 저장을 다룹니다. 외부 서비스가 필요 없으며 모든 작업이 로컬에서 실행됩니다. + +## 필요 사항 + +Before you start, make sure you have: + +* Python 3.8 or newer installed on your machine. +* Access to a terminal or command prompt. +* Write permission to a folder where the barcode images will be saved. + +The only third‑party dependency is **Aspose.BarCode for Python via .NET**, which supports the Omni‑directional DataBar type out of the box. + +## 단계 1: Aspose.BarCode for Python 설치 + +Aspose.BarCode provides the `BarcodeGenerator` class used in the example code. Install the package with `pip`: + +```bash +pip install aspose-barcode +``` + +The package includes the necessary .NET runtime bindings, so you do not need to install the .NET SDK separately. + +## 단계 2: Import the library and create the generator + +The first line of the script creates a generator for a stacked Omni‑directional DataBar. The GTIN‑14 value `(01)12345678901231` is used as sample data. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*이 단계가 중요한 이유*: The `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` constant tells the library to encode the value as an Omni‑directional DataBar, which is the format required by many point‑of‑sale scanners. + +## 단계 3: Set the X‑dimension (module width) + +The X‑dimension defines the width of the smallest bar module. A value of `2` pixels produces a clear, readable barcode without excessive file size. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*이 단계가 중요한 이유*: Adjusting the X‑dimension allows you to balance readability and image dimensions. An X‑dimension that is too small may render poorly on low‑resolution printers. + +## 단계 4: Configure the aspect ratio and save the first image + +The aspect ratio influences the overall height of the DataBar relative to its width. An aspect ratio of `15` creates a compact visual style. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **팁**: Use `pathlib.Path` to build the output path, which automatically creates missing directories. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## 단계 5: Change the aspect ratio for a second visual style and save another image + +Switching the aspect ratio to `30` produces a taller barcode that may be required by specific scanner hardware. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*이 단계가 중요한 이유*: Different retailers and scanning devices have distinct size constraints. Providing both aspect ratios in a single script lets you generate the exact style you need without duplicating code. + +## 전체 스크립트 – omni directional databar 및 barcode 이미지 python 생성 + +Below is the complete, runnable example that incorporates all previous steps. Save it as `generate_databar.py` and run it with `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### 예상 출력 + +Running the script creates the following files: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Both images display a valid Omni‑directional DataBar that can be scanned by standard retail equipment. + +![Python에서 omni directional databar barcode 이미지 생성 예시](example_databar.png "Python에서 omni directional databar barcode 이미지 생성") + +*위 이미지는 저장된 두 PNG 파일을 보여주는 자리 표시자입니다.* + +## 일반적인 문제 처리 + +| 문제 | 원인 | 해결 방법 | +|-------|--------|-----| +| `ImportError: No module named aspose` | Aspose.BarCode가 설치되지 않았거나 다른 환경에 설치되었습니다. | 올바른 가상 환경을 활성화하고 `pip install aspose-barcode`를 실행하십시오. | +| `PermissionError` when saving | 스크립트가 대상 폴더에 대한 쓰기 권한이 없습니다. | 자신이 소유한 디렉터리를 선택하거나 적절한 권한으로 스크립트를 실행하십시오. | +| Barcode does not scan | X‑dimension이 너무 낮거나 종횡비가 스캐너와 호환되지 않습니다. | `x_dimension.pixels`를 3 또는 4로 늘리고, 다양한 `aspect_ratio` 값(예: 20, 25)을 테스트하십시오. | +| Missing .NET runtime | Aspose.BarCode는 Windows/Linux에서 .NET 런타임에 의존합니다. | Microsoft 사이트에서 최신 .NET 런타임을 설치하십시오; 패키지 문서에 플랫폼별 가이드가 제공됩니다. | + +## 예제 확장하기 + +You can adapt the script to generate other DataBar variants (e.g., `DATABAR_STACKED`, `DATABAR_EXPANDED`). Replace the `EncodeTypes` constant accordingly: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +If you need to embed the barcode in a PDF, Aspose.PDF for Python can import the PNG file directly or you can use the `save` method with `BarCodeImageFormat.Pdf`. + +## 결론 + +This tutorial showed how to **create omni directional databar** and how to **create barcode image python** using Aspose.BarCode. You now have a complete, reproducible script that generates two PNG files with different aspect ratios, handles common pitfalls, and can be extended to other barcode formats. + +Next, explore generating QR codes, adding the barcode to PDF invoices, or automating batch processing for large product catalogs. Each of those topics builds on the same `BarcodeGenerator` pattern demonstrated here. Happy coding! + +## 다음에 배워야 할 내용은? + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [바코드 이미지 생성 – GS1 쿠폰 UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode 바코드 이미지 생성 – 행 및 열 (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Java에서 바코드 이미지 생성 및 렌더링 방법](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/korean/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/korean/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..fca8b8812 --- /dev/null +++ b/barcode/korean/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: Python을 사용하여 바코드를 빠르게 생성하는 방법. 데이터를 기반으로 바코드를 만들고 단일 라이브러리로 바코드 이미지를 + 내보내는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: ko +lastmod: 2026-08-12 +og_description: Aspose.BarCode를 사용하여 Python에서 바코드를 생성하는 방법. 이 가이드를 따라 데이터를 사용해 바코드를 + 만들고 바코드 이미지를 PNG로 내보내세요. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Python에서 바코드 생성 방법 – 빠르고 신뢰할 수 있는 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Python에서 바코드 생성 방법 – 완전한 단계별 가이드 +url: /ko/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python에서 바코드 생성 방법 – 완전 단계별 가이드 + +Python 애플리케이션에서 **바코드 생성 방법**이 필요하다면, 이 튜토리얼은 정확한 코드를 보여줍니다. **데이터에서 바코드 생성**, 외관 조정, 그리고 **바코드 이미지 내보내기**를 PNG 파일로 배우게 됩니다—코드 10줄 이하로. + +바코드 생성은 비즈니스 로직의 다른 부분과 별개처럼 느껴질 수 있지만, 단일 라이브러리를 사용하면 기존 코드 베이스와 일관되게 진행할 수 있습니다. 아래 섹션에서는 전체 실행 가능한 예제를 확인하고, 각 라인이 왜 중요한지 이해하며, 모듈 너비 변경이나 외곽선만 그리는 바코드와 같은 일반적인 변형을 살펴봅니다. + +## Aspose.BarCode 라이브러리를 사용한 바코드 생성 방법 + +Python용 Aspose.BarCode 라이브러리(.NET 기반)는 이 가이드에서 사용한 Planet 바코드를 포함한 다양한 심볼에 대한 직관적인 API를 제공합니다. 시작하기 전에 패키지가 설치되어 있는지 확인하세요: + +```bash +pip install aspose-barcode +``` + +> **프로 팁:** 다른 프로젝트와의 버전 충돌을 피하려면 가상 환경을 사용하세요. + +### 1. 필요한 클래스 가져오기 + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +이 임포트를 통해 생성기 클래스, 바코드 유형 열거형, 그리고 결과 저장 시 사용할 이미지 포맷 열거형에 접근할 수 있습니다. + +### 2. 데이터에서 바코드 생성 + +첫 번째 단계는 **데이터에서 바코드 생성**입니다. `BarcodeGenerator` 생성자는 심볼과 인코딩할 원시 문자열을 받습니다. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +`EncodeTypes.Planet` 값은 Planet 바코드를 선택하고, `"123456"`은 최종 이미지에 표시될 페이로드입니다. + +### 3. X‑dimension (모듈 너비) 조정 + +X‑dimension은 각 바코드 모듈(얇은 막대)의 너비를 제어합니다. 4 픽셀로 설정하면 파일 크기를 크게 늘리지 않으면서도 선명하고 읽기 쉬운 이미지를 얻을 수 있습니다. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **왜 중요한가:** 큰 X‑dimension은 저해상도 프린터에서 스캔 신뢰성을 높이고, 작은 값은 웹 사용 시 파일 크기를 줄여줍니다. + +### 4. 바코드 이미지 내보내기 (채워진 스타일) + +이제 `save` 메서드를 사용해 **바코드 이미지 내보내기**를 할 수 있습니다. 예제는 PNG 파일을 저장하지만, `BarCodeImageFormat` 열거형을 변경하면 JPEG, BMP, TIFF 등으로 저장할 수 있습니다. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +`PlanetFilled.png` 파일에는 완전히 채워진 Planet 바코드가 포함되어 있어 인쇄하거나 PDF에 삽입하기에 적합합니다. + +### 5. 외곽선만 있는 바코드를 위한 두 번째 생성기 만들기 + +외곽선 버전(빈 막대)이 필요하면 이미지 저장 후 `filled_bars` 플래그를 토글할 수 없기 때문에 새 생성기를 만들어야 합니다. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. 동일한 X‑dimension 설정 적용 + +두 번째 생성기를 만들 때는 일관성을 유지하고 싶은 모든 시각적 설정을 다시 적용해야 합니다. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. 외곽선 바코드에 대해 채워진 바 비활성화 + +`filled_bars`를 `False`로 설정하면 렌더러가 각 모듈의 외곽선만 그리게 되어, 디자인 용도로 유용한 가벼운 이미지를 만들 수 있습니다. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. 외곽선 바코드 이미지 내보내기 + +마지막으로 **바코드 이미지 내보내기**를 다시 수행해 이번에는 외곽선 버전을 저장합니다. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +이제 두 개의 PNG 파일이 있습니다: 실선이 채워진 파일(`PlanetFilled.png`)과 외곽선만 있는 파일(`PlanetEmpty.png`). + +## 다른 형식으로 바코드 이미지 내보내기 (옵션) + +`save` 메서드는 여러 형식을 지원합니다. 90 % 품질의 JPEG로 내보내려면 다음과 같이 합니다: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +웹용으로 투명 배경이 필요하면 알파 채널이 포함된 PNG를 선택하세요: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## 일반적인 변형 및 엣지 케이스 + +| 시나리오 | 필요한 변경 | 코드 스니펫 | +|----------|---------------|--------------| +| **다른 심볼** (예: QR) | 다른 `EncodeTypes` 값을 사용 | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **사용자 정의 전경 색상** | `fore_color` 설정 | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **고해상도** | `image_width` 및 `image_height` 로 DPI 증가 | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **큰 데이터 문자열** | 데이터 길이가 심볼 규격에 맞는지 확인 | Validate length before creating the generator | + +> **주의:** 선택한 심볼의 최대 길이를 초과하는 데이터를 제공하면 런타임 예외가 발생합니다. 항상 문자열 길이를 검증하거나 `ArgumentException`을 잡아 처리하세요. + +## 전체 실행 가능한 예제 + +아래는 `generate_planet_barcode.py`라는 파일에 복사‑붙여넣기 할 수 있는 완전한 스크립트입니다. `YOUR_DIRECTORY`를 실제 존재하는 폴더 경로로 바꾸세요. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +이 스크립트를 실행하면 지정된 디렉터리에 두 개의 PNG 파일이 생성됩니다. 이미지 뷰어로 열어 결과를 확인하세요; 두 파일 모두 문자열 `123456`을 인코딩한 Planet 바코드를 표시해야 합니다. + +## 결론 + +이제 Aspose.BarCode를 사용해 Python에서 **바코드 생성 방법**을 알고, **데이터에서 바코드 생성**과 **바코드 이미지 내보내기**를 채워진 스타일과 외곽선 스타일 모두에서 수행할 수 있습니다. 동일한 패턴을 다른 심볼, 이미지 포맷, 시각적 커스터마이징에도 적용할 수 있어 애플리케이션의 모든 바코드 관련 기능에 유연한 기반을 제공합니다. + +### 다음 단계 + +* `EncodeTypes.Planet`을 원하는 값으로 교체해 QR, Code‑128, DataMatrix 등 다른 심볼을 탐색하세요. +* `ReportLab`이나 `PyPDF2`와 같은 라이브러리를 사용해 생성된 PNG 파일을 PDF 보고서에 통합하세요. +* 화면 해상도나 프린터 DPI에 따라 바코드 크기를 조정하도록 동적 X‑dimension 값을 실험해 보세요. + +행복한 코딩 되시길 바라며, 예제를 여러분의 프로젝트 요구에 맞게 자유롭게 적용하세요! + +## 다음에 배워야 할 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 주제를 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 포함하고 있어 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하는 데 도움이 됩니다. + +- [Java에서 Aspose.BarCode로 바코드 이미지 생성하기](/barcode/english/java/barcode-rendering-techniques/) +- [Java에서 바코드 생성 – 완전 구성 가이드](/barcode/english/java/barcode-configuration/) +- [Java에서 Aspose.BarCode로 code128 바코드 이미지 만들기](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/polish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/polish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..9277b6c19 --- /dev/null +++ b/barcode/polish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-08-12 +description: Przykład generatora kodów kreskowych, który pokazuje, jak generować kod + kreskowy o precyzyjnym rozmiarze w pikselach. Dowiedz się, jak ustawić szerokość + modułu, wysokość kreski i tworzyć kody kreskowe Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: pl +lastmod: 2026-08-12 +og_description: Przykład generatora kodów kreskowych pokazuje, jak generować kod kreskowy + o dokładnych wymiarach w pikselach. Postępuj zgodnie z tym przewodnikiem, aby kontrolować + szerokość modułu i wysokość kreski dla kodów Planet i RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: przykład generatora kodów kreskowych – dostosuj rozmiar piksela w C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: przykład generatora kodów kreskowych – przewodnik krok po kroku dla niestandardowych + rozmiarów pikseli +url: /pl/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Przykład generatora kodów kreskowych – przewodnik krok po kroku dla niestandardowych rozmiarów pikseli + +Jeśli potrzebujesz **przykładu generatora kodów kreskowych**, który pozwala kontrolować każdy piksel, ten przewodnik pokazuje dokładnie, jak to zrobić. Nauczysz się ustawiać szerokość modułu, definiować stałą wysokość pasków oraz generować zarówno kody kreskowe Planet, jak i RM4SCC o przewidywalnych wymiarach. + +Większość programistów ma problem z obrazami „jak wygenerować kod kreskowy”, które wyglądają tak samo na każdym ekranie lub drukarce. Poniższe fragmenty kodu rozwiązują ten problem, udostępniając parametry na poziomie pikseli biblioteki Aspose.BarCode for .NET, dzięki czemu możesz uzyskać spójny wynik bez zgadywania. + +## Czego się nauczysz + +* Jak zainstalować wymaganą paczkę NuGet. +* Jak wygenerować kod kreskowy Planet z automatycznie obliczoną wysokością. +* Jak wygenerować kod kreskowy Planet z wyraźną wysokością 100 pikseli. +* Jak wygenerować kod kreskowy RM4SCC używając tej samej wyraźnej wysokości. +* Dlaczego **rozmiar piksela kodu kreskowego** ma znaczenie dla niezawodności skanowania. +* Wskazówki dotyczące rozwiązywania typowych problemów przy generowaniu obrazów kodów kreskowych Planet. + +Wystarczy .NET 6 lub nowszy, podstawowe środowisko programistyczne C# oraz połączenie internetowe, aby pobrać pakiet NuGet. + +--- + +## Przykład generatora kodów kreskowych – przygotowanie środowiska programistycznego + +Przed napisaniem jakiegokolwiek kodu upewnij się, że biblioteka Aspose.BarCode jest dostępna w Twoim projekcie. + +### Zainstaluj pakiet Aspose.BarCode + +Otwórz terminal w folderze projektu i uruchom: + +```bash +dotnet add package Aspose.BarCode +``` + +Polecenie dodaje najnowszą stabilną wersję **Aspose.BarCode** do Twojego pliku `csproj`. Po zakończeniu przywracania możesz rozpocząć używanie klasy `BarcodeGenerator`. + +> **Wskazówka:** Celuj w .NET 6 lub .NET 7, aby skorzystać z najnowszych ulepszeń wydajności i domyślnego obsługi UTF‑8. + +### Dodaj niezbędne dyrektywy `using` + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Te przestrzenie nazw udostępniają klasę `BarcodeGenerator` oraz wyliczenie `BarCodeImageFormat` używane później w samouczku. + +--- + +## Jak wygenerować kod kreskowy z niestandardowym rozmiarem piksela + +Poniższe trzy kroki ilustrują kompletny **przykład generatora kodów kreskowych**. Każdy krok opiera się na poprzednim, więc możesz skopiować‑wkleić cały blok do aplikacji konsolowej i uruchomić go bez zmian. + +### Krok 1 – wygeneruj kod kreskowy Planet z automatycznie obliczoną wysokością + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Dlaczego to działa:** +*Właściwość `XDimension` definiuje szerokość pojedynczego modułu kodu kreskowego (najmniejszego czarnego lub białego elementu). Gdy pomijasz `BarHeight`, biblioteka oblicza wysokość, która zachowuje standardowy współczynnik proporcji dla kodów Planet.* + +**Oczekiwany wynik:** Plik PNG o nazwie `PlanetAuto.png` zawierający czysty kod kreskowy Planet. Jego wysokość dostosowuje się do szerokości modułu 4 piksele, zazwyczaj około 60 pikseli dla ładunku sześciu znaków. + +### Krok 2 – wygeneruj kod kreskowy Planet z wyraźną wysokością 100 pikseli + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Dlaczego możesz tego potrzebować:** +Czasami sprzęt skanujący wymaga minimalnej wysokości paska dla niezawodnego wykrywania. Ustawiając `BarHeight.Pixels`, zapewniasz, że każdy wygenerowany obraz spełnia ten wymóg, niezależnie od długości kodowanych danych. + +**Oczekiwany wynik:** `PlanetHeight100.png` pokazuje te same dane co wcześniej, ale paski mają dokładnie 100 pikseli wysokości, dając pełną kontrolę nad rozmiarem wizualnym. + +### Krok 3 – wygeneruj kod kreskowy RM4SCC z tą samą wyraźną wysokością + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Dlaczego to ma znaczenie:** +`EncodeTypes.RM4SCC` to układany liniowy kod kreskowy używany w logistyce. Dopasowanie jego wysokości paska do kodu Planet upraszcza przetwarzanie wsadowe, gdy oba symbole pojawiają się na tej samej etykiecie. + +**Oczekiwany wynik:** `RM4SCCHeight100.png` wyświetla idealnie wymiarowany kod kreskowy RM4SCC, dopasowany do wysokości 100 pikseli ustawionej dla kodu Planet. + +> **Weryfikacja wyniku:** Otwórz każdy plik PNG w przeglądarce obrazów i potwierdź, że czarne paski mają dokładnie 4 piksele szerokości oraz, jeśli określono, 100 pikseli wysokości. Możesz także wprowadzić pliki do aplikacji skanującej kody kreskowe, aby upewnić się, że dekodują się jako „123456”. + +## Zrozumienie rozmiaru piksela kodu kreskowego i wysokości paska + +### Co to jest **rozmiar piksela kodu kreskowego**? + +*Rozmiar piksela* odnosi się do fizycznej liczby pikseli ekranu lub drukarki, które reprezentują pojedynczy moduł (`XDimension`). Większy rozmiar piksela daje większy kod kreskowy, co może być łatwiejsze dla skanerów o niskiej rozdzielczości, ale zajmuje więcej miejsca na etykiecie. + +### Jak `BarHeight` wpływa na czytelność? + +Właściwość `BarHeight` kontroluje pionową długość pasków. Normy dla większości kodów 1‑D (w tym Planet i RM4SCC) zalecają minimalną wysokość 10 mm przy druku w 300 dpi, co przekłada się na około 118 pikseli. Ustawienie wysokości poniżej tej wartości może powodować błędy odczytu, szczególnie w przypadku kamer mobilnych. + +### Kiedy pozwolić bibliotece automatycznie obliczyć wysokość? + +Jeśli generujesz kody kreskowe wyłącznie do wyświetlania na ekranie, automatyczne obliczanie utrzymuje stały współczynnik proporcji i zmniejsza potrzebę ręcznych korekt. Dla drukowanych etykiet, które muszą spełniać rygorystyczne normy ISO, powinieneś **wyraźnie ustawić wysokość paska**. + +## Typowe pułapki i najlepsze praktyki przy generowaniu kodu kreskowego Planet + +| Pułapka | Dlaczego się dzieje | Rozwiązanie | +|---------|---------------------|-------------| +| Paski wydają się zbyt cienkie lub grube | `XDimension` pozostawiony domyślnie (1 piksel) na wyświetlaczach o wysokiej rozdzielczości | Ustaw `XDimension.Pixels` na co najmniej 3‑4 dla lepszej czytelności | +| Skaner nie może odczytać kodu | `BarHeight` jest zbyt mały dla ogniskowej skanera | Użyj `BarHeight.Pixels` ≥ 100 dla większości skanerów mobilnych | +| Obraz jest rozmyty po skalowaniu | Zapisywanie jako JPEG wprowadza artefakty kompresji | Zapisz jako PNG (`BarCodeImageFormat.Png`) dla bezstratnego wyniku | +| Nieoczekiwany typ kodu kreskowego | Błędna wartość wyliczenia `EncodeTypes` | Sprawdź, czy używasz `EncodeTypes.Planet` dla symbologii Planet | + +### Wskazówka dotycząca wydajności + +Podczas generowania tysięcy kodów kreskowych w zadaniu wsadowym, ponownie używaj jednej instancji `BarcodeGenerator` i zmieniaj jedynie `CodeText` oraz parametry rozmiaru pomiędzy zapisami. Zapobiega to wielokrotnemu przydzielaniu wewnętrznych obiektów renderujących i może skrócić czas wykonania nawet o 30 %. + +## Pełny działający przykład – połącz wszystko razem + +Utwórz nowy projekt konsolowy (`dotnet new console -n BarcodeDemo`) i zamień zawartość pliku `Program.cs` na następujący: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Uruchom program poleceniem `dotnet run`. Po wykonaniu znajdziesz trzy pliki PNG w folderze projektu, każdy ilustrujący inny scenariusz **przykładu generatora kodów kreskowych**. + +## Kolejne kroki i powiązane tematy + +* **Jak generować kod kreskowy w innych formatach** – poznaj `EncodeTypes.Code128`, `EncodeTypes.QR` i `EncodeTypes.DataMatrix` dla potrzeb 2‑D. +* **Osadzanie kodów kreskowych w PDF** – połącz Aspose.BarCode z Aspose.PDF, aby umieszczać kody kreskowe bezpośrednio na szablonach faktur. +* **Dynamiczny rozmiar kodu kreskowego w zależności od danych wejściowych użytkownika** – oblicz + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każde źródło zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/polish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/polish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..f330ce892 --- /dev/null +++ b/barcode/polish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Szybko skonfiguruj układ kodu kreskowego Databar w Pythonie. Dowiedz + się, jak ustawiać kolumny, wiersze i zapisywać obrazy przy użyciu biblioteki generatora + kodów kreskowych. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: pl +lastmod: 2026-08-12 +og_description: Skonfiguruj układ kodu kreskowego Databar w Pythonie, aby kontrolować + kolumny, wiersze i wyjście obrazu. Skorzystaj z tego przewodnika, aby uzyskać gotowe + rozwiązanie. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Skonfiguruj układ kodu kreskowego Databar w Pythonie – kompletny poradnik +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Skonfiguruj układ kodu kreskowego Databar w Pythonie – przewodnik krok po kroku +url: /pl/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skonfiguruj układ kodu kreskowego Databar w Pythonie – przewodnik krok po kroku + +Jeśli potrzebujesz **skonfigurować układ kodu kreskowego Databar w Pythonie**, ten przewodnik przeprowadzi Cię przez cały proces. Zobaczysz, jak ustawić liczbę kolumn lub wierszy dla kodu kreskowego Databar Expanded Stacked oraz jak zapisać powstały obraz przy użyciu jednego wywołania biblioteki generatora kodów kreskowych. + +Kontrola układu jest niezbędna, gdy osadzasz kody kreskowe na wąskich opakowaniach, paragonach lub ekranach mobilnych. W poniższych sekcjach omówimy wymagane importy, dwie opcje układu (kolumny i wiersze) oraz najlepsze praktyki zapisywania czystego obrazu PNG. + +## Czego będziesz potrzebować + +* Python 3.8 lub nowszy +* `aspose.barcode` (lub dowolny kompatybilny pakiet generowania kodów kreskowych) zainstalowany + ```bash + pip install aspose-barcode + ``` +* Uprawnienia do zapisu w folderze, w którym będą przechowywane pliki PNG + +Nie są wymagane żadne dodatkowe narzędzia zewnętrzne — biblioteka obsługuje renderowanie, skalowanie i kodowanie obrazu wewnętrznie. + +## Jak skonfigurować układ kodu kreskowego Databar w Pythonie + +Rdzeniem rozwiązania jest klasa `BarcodeGenerator`. Przyjmuje ona wyliczenie `EncodeTypes`, które identyfikuje symbologię kodu kreskowego — w tym przypadku `EncodeTypes.DatabarExpandedStacked`. Po utworzeniu generatora możesz dostosować układ, ustawiając właściwości `columns` lub `rows` w obiekcie parametru `data_bar`. + +### Krok 1: Importuj wymagane klasy + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Te importy dają dostęp do generatora, wyliczenia typów Databar oraz stałej formatu obrazu PNG. + +### Krok 2: Utwórz generator kodu kreskowego dla Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Dlaczego ten krok?* +`EncodeTypes.DatabarExpandedStacked` mówi bibliotece, aby wygenerowała symbologię **Databar Expanded Stacked**, która obsługuje dłuższe ciągi numeryczne przy zachowaniu kompaktowego rozmiaru. Drugi argument to dane do zakodowania; może to być dowolny ciąg spełniający specyfikację Databar. + +### Krok 3: Ustaw liczbę kolumn (układ poziomy) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** jest kluczową frazą dla tej operacji. Gdy zwiększasz liczbę kolumn, kod kreskowy rozciąga się poziomo, co może być przydatne przy szerokich etykietach. Biblioteka automatycznie przelicza szerokość modułu, aby zachować spójny rozmiar całego kodu. + +#### Porada +Maksymalna liczba kolumn dla Databar Expanded Stacked wynosi 8. Ustawienie wartości wyższej niż limit spowoduje przycięcie jej do maksimum, ale lepiej jest zwalidować dane wejściowe wcześniej. + +### Krok 4: Zapisz obraz kodu kreskowego z układem kolumnowym + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** to akcja, która zapisuje renderowany kod kreskowy na dysku. PNG jest bezstratny, co zachowuje ostre krawędzie niezbędne do niezawodnego skanowania. + +### Krok 5: Utwórz drugi generator dla tego samego typu kodu kreskowego (układ wierszowy) + +Jeśli wolisz stos pionowy, pracujesz z wierszami zamiast kolumn. Poniższy kod ponownie wykorzystuje tę samą wartość, ale tworzy nową instancję `BarcodeGenerator`, aby uniknąć mieszania ustawień kolumn i wierszy. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Krok 6: Ustaw liczbę wierszy (układ pionowy) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** układa moduły kodu kreskowego pionowo. Układ trzech wierszy zmniejsza wysokość każdego pojedynczego stosu, co czyni kod odpowiednim dla wąskich paragonów lub ekranów mobilnych. + +#### Przypadek szczególny +Jeśli ustawisz `rows` na 1, biblioteka wygeneruje jednowierszowy Databar (równoważny standardowemu Databar). Wartości poniżej 1 są ignorowane i resetowane do domyślnej (1 wiersz). + +### Krok 7: Zapisz obraz kodu kreskowego z układem wierszowym + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Ponownie używamy **save barcode image**, zapisując w formacie PNG, aby zachować wyraźny wynik. + +## Pełny, uruchamialny przykład + +Połączenie wszystkich elementów daje samodzielny skrypt, który możesz wkleić do dowolnego projektu w Pythonie. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Oczekiwany wynik** + +Uruchomienie skryptu tworzy dwa pliki PNG: + +* `output/ExpandedCols4.png` – kod kreskowy rozciągnięty na cztery kolumny +* `output/ExpandedRows3.png` – kod kreskowy skompresowany do trzech wierszy + +Oba obrazy można otworzyć w dowolnym przeglądarce obrazów lub zaimportować bezpośrednio do faktur PDF, szablonów etykiet czy stron internetowych. + +## Częste pytania i rozwiązywanie problemów + +| Question | Answer | +|----------|--------| +| *What if the barcode looks blurry?* | Increase the image resolution by setting `barcode_generator.parameters.image_width` and `image_height` before calling `save`. | +| *Can I use other image formats?* | Yes. Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. | +| *Is there a limit on the data length?* | Databar Expanded Stacked supports up to 74 numeric characters. Exceeding the limit raises a `ArgumentException`. | +| *How do I change the foreground color?* | Use `barcode_generator.parameters.barcode.color = Color.Blue` (import `System.Drawing.Color`). | +| *Can I combine columns and rows?* | No. The API treats columns and rows as mutually exclusive layout modes. Choose one per barcode instance. | + +## Następne kroki + +Teraz, gdy możesz **skonfigurować układ kodu kreskowego Databar**, rozważ zgłębienie poniższych tematów: + +* **Add text captions** – use `barcode_generator.parameters.barcode.code_text` to display the encoded value beneath the image. +* **Embed the barcode in a PDF** – combine the generated PNG with `aspose.pdf` to create printable documents. +* **Dynamic sizing** – calculate optimal column or row counts based on label dimensions at runtime. +* **Batch processing** – loop over a CSV of product codes to generate a library of barcode images automatically. + +Eksperymentuj z różnymi wartościami kolumn i wierszy, aby zobaczyć, jak wpływają na niezawodność skanowania na docelowych urządzeniach. Im więcej testujesz, tym lepiej zrozumiesz kompromisy między rozmiarem kodu, czytelnością a ograniczeniami przestrzennymi. + +--- + +*Happy coding! If you found this tutorial useful, share it with teammates or leave a comment about the layout challenges you faced.* + +## Co warto nauczyć się dalej? + +Poniższe samouczki obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Create barcode image c# – Configure Codablock F Rows & Columns](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [One-Dimensional Databar Barcode Height Adjustment](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/polish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/polish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..4a3163fec --- /dev/null +++ b/barcode/polish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-08-12 +description: Utwórz obraz kodu kreskowego w C# przy użyciu BarCodeGenerator. Dowiedz + się, jak generować DataBar, kontrolować rozmiar obrazu kodu kreskowego oraz efektywnie + tworzyć wiele kodów kreskowych. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: pl +lastmod: 2026-08-12 +og_description: Utwórz obraz kodu kreskowego w C# za pomocą BarCodeGenerator. Ten + samouczek pokazuje krok po kroku, jak generować kody DataBar, dostosować rozmiar + obrazu kodu kreskowego oraz tworzyć wiele kodów kreskowych. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Tworzenie obrazu kodu kreskowego w C# – kompletny przewodnik BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Utwórz obraz kodu kreskowego w C# przy użyciu BarCodeGenerator +url: /pl/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tworzenie obrazu kodu kreskowego w C# przy użyciu BarCodeGenerator + +Jeśli potrzebujesz **utworzyć obraz kodu kreskowego** w aplikacji .NET, ten przewodnik pokaże Ci dokładnie, jak to zrobić przy użyciu klasy `BarCodeGenerator`. Niezależnie od tego, czy budujesz system POS w handlu detalicznym, czy narzędzie do śledzenia zapasów, nauczysz się generować symbole DataBar, kontrolować rozmiar obrazu kodu kreskowego oraz tworzyć wiele kodów w jednym przebiegu. + +Odkryjesz także, jak API **barcode generator c#** pozwala dostosować wymiary, zmienić format wyjściowy i obsłużyć przypadki brzegowe, takie jak nieprawidłowe ciągi danych. Po zakończeniu tutorialu będziesz pewnie **tworzyć wiele kodów kreskowych** bez pisania powtarzalnego kodu. + +## Wymagania wstępne + +Zanim rozpoczniesz, upewnij się, że masz: + +- .NET 6.0 lub nowszy zainstalowany +- Środowisko programistyczne (Visual Studio, Rider lub VS Code) +- Pakiet NuGet Aspose.BarCode for .NET (lub dowolną kompatybilną bibliotekę udostępniającą `BarCodeGenerator`) + +Pakiet możesz dodać za pomocą: + +```bash +dotnet add package Aspose.BarCode +``` + +## Co obejmuje ten tutorial + +1. Utworzenie instancji **barcode generator c#** dla kodowania DataBar Omni‑directional. +2. Dostosowanie **barcode image size** poprzez zmianę X‑dimension i wysokości pasków. +3. Użycie pętli do **create multiple barcodes** o różnych wysokościach. +4. Zapis obrazów jako pliki PNG i weryfikacja wyniku. + +Wszystkie fragmenty kodu są kompletne i gotowe do skopiowania do nowego projektu konsolowego. + +![Create barcode image example](barcode-example.png){alt="Create barcode image example"} + +## Krok 1: Inicjalizacja generatora – podstawy tworzenia obrazu kodu kreskowego + +Pierwszym krokiem jest utworzenie obiektu `BarCodeGenerator` z żądaną symbologią. Dla symbolu DataBar Omni‑directional używasz `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Dlaczego to ważne:** Inicjalizacja generatora definiuje zasady kodowania i ładunek danych. Jeśli pominiesz prawidłową wartość `EncodeTypes`, biblioteka wygeneruje nieobsługiwany kod kreskowy lub zgłosi wyjątek. + +## Krok 2: Konfiguracja X‑dimension i wysokości pasków – kontrola rozmiaru obrazu kodu kreskowego + +Wizualny rozmiar kodu kreskowego zależy od dwóch parametrów: + +| Parameter | What it controls | Typical range | +|-----------|------------------|---------------| +| `x_dimension.pixels` | Width of the smallest module (the “dot”) | 1 – 4 px | +| `bar_height.pixels` | Height of the vertical bars | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Pro tip:** Mniejsza X‑dimension daje obraz o wyższej rozdzielczości, ale może być trudniejsza do zeskanowania na drukarkach niskiej jakości. Dostosuj wartość w zależności od docelowego sprzętu skanującego. + +## Krok 3: Zapis pierwszego kodu kreskowego – tworzenie obrazu kodu kreskowego o wysokości 30 px + +Teraz możesz wygenerować obraz i zapisać go na dysku. Metoda `Save` przyjmuje ścieżkę pliku oraz enum formatu obrazu. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Oczekiwany rezultat:** Plik PNG o nazwie `Databar30.png` pojawia się w `C:\Barcodes`. Otwarcie pliku pokazuje symbol DataBar Omni‑directional o wyraźnym, wysokim kontraście. + +## Krok 4: Zmiana wysokości i generowanie dodatkowych obrazów – tworzenie wielu kodów kreskowych + +Aby **create multiple barcodes** o różnych wymiarach, wystarczy zmodyfikować właściwość `BarHeight` i ponownie wywołać `Save`. Dzięki temu nie musisz ponownie tworzyć generatora, co oszczędza pamięć i czas CPU. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Dlaczego to działa:** Obiekt `BarCodeGenerator` przechowuje cały stan konfiguracji. Zmiana jednej właściwości aktualizuje silnik renderujący przy następnym wywołaniu `Save`, umożliwiając **create multiple barcodes** w sposób efektywny. + +## Krok 5: Zaawansowane – jak generować DataBar z własnymi danymi + +Powyższy przykład używa statycznego ładunku GS1. W rzeczywistych scenariuszach często trzeba osadzić zmienne identyfikatory produktów. Biblioteka akceptuje dowolny ciąg spełniający specyfikację DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Kluczowy punkt:** Ustawienie `generator.CodeText` aktualizuje kodowane dane bez ponownego tworzenia obiektu. To zalecany wzorzec **how to generate databar** przy obsłudze dużych zbiorów danych. + +## Krok 6: Weryfikacja i rozwiązywanie problemów – zapewnienie prawidłowego rozmiaru obrazu kodu kreskowego + +Po wygenerowaniu obrazów możesz programowo potwierdzić, że wymiary odpowiadają oczekiwaniom. Klasa `Image` z `System.Drawing` może odczytać plik i zgłosić jego rozmiar. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Jeśli wysokość nie odzwierciedla ustawionej wartości, sprawdź: + +- **X‑dimension**: Bardzo mała wartość może spowodować zaokrąglenie wysokości przez renderer. +- **Image format**: Niektóre formaty (np. JPEG) stosują kompresję, która może zmienić liczbę pikseli przy zapisie. PNG zachowuje dokładne wymiary. + +## Krok 7: Najlepsze praktyki dotyczące rozmiaru obrazu kodu kreskowego i wydajności + +| Recommendation | Reason | +|----------------|--------| +| Keep `x_dimension.pixels` between 2 – 3 px for most scanners. | Balances readability and file size. | +| Use PNG for lossless output when the image will be printed. | Guarantees exact dimensions and sharp edges. | +| Reuse a single `BarCodeGenerator` instance when generating many barcodes. | Reduces object allocation overhead. | +| Validate the input string against the GS1 standard before assigning to `CodeText`. | Prevents runtime exceptions and invalid scans. | +| Store generated images in a dedicated folder with a clear naming convention (e.g., `Databar_{GTIN}.png`). | Simplifies downstream processing and audit trails. | + +## Pełny działający przykład + +Poniżej znajduje się kompletny program, który zawiera wszystkie kroki od inicjalizacji po weryfikację. Skopiuj kod do nowego projektu konsolowego i uruchom go. + + + +## Co powinieneś nauczyć się dalej? + +Poniższe tutoriale obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne przykłady kodu oraz wyjaśnienia krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/polish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/polish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..282ab98b9 --- /dev/null +++ b/barcode/polish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-08-12 +description: Utwórz wielokierunkowy DataBar w Pythonie i dowiedz się, jak tworzyć + obrazy kodów kreskowych w Pythonie przy użyciu Aspose.BarCode. Postępuj zgodnie + z przewodnikiem krok po kroku, aby uzyskać pełne rozwiązanie. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: pl +lastmod: 2026-08-12 +og_description: Utwórz omnidirectional databar w Pythonie i w kilka minut wygeneruj + obraz kodu kreskowego w Pythonie. Ten samouczek przedstawia kompletny, działający + przykład. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Stwórz wszechkierunkowy pasek danych – pełny przewodnik Pythona +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Utwórz wszechkierunkowy obraz databar i kodu kreskowego w Pythonie +url: /pl/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utwórz omni directional databar i obraz kodu kreskowego w Pythonie + +Jeśli potrzebujesz **create omni directional databar** w projekcie Python, ten przewodnik pokaże Ci, jak to zrobić oraz jak **create barcode image python** przy użyciu biblioteki Aspose.BarCode. Otrzymasz gotowy‑do‑uruchomienia skrypt, który generuje dwa pliki PNG o różnych proporcjach. + +Generowanie DataBar zgodnego ze specyfikacją Omni‑directional jest powszechnym wymogiem w aplikacjach detalicznych i logistycznych. Poradnik obejmuje instalację, konfigurację wymiaru X, dostosowanie proporcji oraz zapisywanie końcowych obrazów. Nie są wymagane żadne zewnętrzne usługi; wszystko działa lokalnie. + +## Czego będziesz potrzebować + +* Python 3.8 lub nowszy zainstalowany na Twoim komputerze. +* Dostęp do terminala lub wiersza poleceń. +* Uprawnienia do zapisu w folderze, w którym będą zapisywane obrazy kodów kreskowych. + +Jedyną zależnością zewnętrzną jest **Aspose.BarCode for Python via .NET**, który obsługuje typ Omni‑directional DataBar od razu po zainstalowaniu. + +## Krok 1: Zainstaluj Aspose.BarCode dla Pythona + +Aspose.BarCode udostępnia klasę `BarcodeGenerator` używaną w przykładowym kodzie. Zainstaluj pakiet przy pomocy `pip`: + +```bash +pip install aspose-barcode +``` + +Pakiet zawiera niezbędne powiązania środowiska .NET, więc nie musisz instalować .NET SDK osobno. + +## Krok 2: Zaimportuj bibliotekę i utwórz generator + +Pierwsza linia skryptu tworzy generator dla stosowanego Omni‑directional DataBar. Wartość GTIN‑14 `(01)12345678901231` jest używana jako przykładowe dane. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Dlaczego ten krok ma znaczenie*: Stała `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` informuje bibliotekę, aby zakodowała wartość jako Omni‑directional DataBar, co jest formatem wymaganym przez wiele skanerów punktu sprzedaży. + +## Krok 3: Ustaw wymiar X (szerokość modułu) + +Wymiar X określa szerokość najmniejszego modułu kreski. Wartość `2` piksele generuje wyraźny, czytelny kod kreskowy bez nadmiernego rozmiaru pliku. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Dlaczego ten krok ma znaczenie*: Dostosowanie wymiaru X pozwala zrównoważyć czytelność i wymiary obrazu. Zbyt mały wymiar X może źle wyglądać na drukarkach o niskiej rozdzielczości. + +## Krok 4: Skonfiguruj proporcje i zapisz pierwszy obraz + +Proporcje wpływają na ogólną wysokość DataBar w stosunku do jego szerokości. Proporcja `15` tworzy kompaktowy styl wizualny. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Wskazówka**: Użyj `pathlib.Path` do budowania ścieżki wyjściowej, co automatycznie tworzy brakujące katalogi. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Krok 5: Zmień proporcje dla drugiego stylu wizualnego i zapisz kolejny obraz + +Zmiana proporcji na `30` powoduje wyższy kod kreskowy, który może być wymagany przez określony sprzęt skanujący. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Dlaczego ten krok ma znaczenie*: Różni detaliści i urządzenia skanujące mają odrębne ograniczenia rozmiarowe. Udostępnienie obu proporcji w jednym skrypcie pozwala wygenerować dokładny styl, którego potrzebujesz, bez duplikowania kodu. + +## Pełny skrypt – create omni directional databar i barcode image python + +Poniżej znajduje się kompletny, uruchamialny przykład, który zawiera wszystkie poprzednie kroki. Zapisz go jako `generate_databar.py` i uruchom przy pomocy `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Oczekiwany wynik + +Uruchomienie skryptu tworzy następujące pliki: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Oba obrazy przedstawiają prawidłowy Omni‑directional DataBar, który może być zeskanowany przez standardowy sprzęt detaliczny. + +![example of create omni directional databar barcode image in Python](example_databar.png "create omni directional databar barcode image python") + +*Powyższy obraz jest symbolem, który ilustruje dwa zapisane pliki PNG.* + +## Rozwiązywanie typowych problemów + +| Problem | Przyczyna | Rozwiązanie | +|-------|--------|-----| +| `ImportError: No module named aspose` | Aspose.BarCode nie jest zainstalowany lub został zainstalowany w innym środowisku. | Aktywuj właściwe środowisko wirtualne i uruchom `pip install aspose-barcode`. | +| `PermissionError` przy zapisywaniu | Skrypt nie ma uprawnień do zapisu w docelowym folderze. | Wybierz katalog, do którego masz dostęp, lub uruchom skrypt z odpowiednimi uprawnieniami. | +| Kod kreskowy nie jest odczytywany | Zbyt mały wymiar X lub niekompatybilne proporcje z skanerem. | Zwiększ `x_dimension.pixels` do 3 lub 4 i przetestuj różne wartości `aspect_ratio` (np. 20, 25). | +| Brak środowiska .NET | Aspose.BarCode zależy od środowiska .NET na Windows/Linux. | Zainstaluj najnowsze środowisko .NET ze strony Microsoft; dokumentacja pakietu zawiera wskazówki specyficzne dla platformy. | + +## Rozszerzanie przykładu + +Możesz dostosować skrypt do generowania innych wariantów DataBar (np. `DATABAR_STACKED`, `DATABAR_EXPANDED`). Zastąp odpowiednio stałą `EncodeTypes`: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Jeśli potrzebujesz osadzić kod kreskowy w PDF, Aspose.PDF for Python może bezpośrednio zaimportować plik PNG lub możesz użyć metody `save` z `BarCodeImageFormat.Pdf`. + +## Zakończenie + +Ten poradnik pokazał, jak **create omni directional databar** oraz jak **create barcode image python** przy użyciu Aspose.BarCode. Masz teraz kompletny, powtarzalny skrypt, który generuje dwa pliki PNG o różnych proporcjach, radzi sobie z typowymi problemami i może być rozszerzony o inne formaty kodów kreskowych. + +Następnie, eksploruj generowanie kodów QR, dodawanie kodu kreskowego do faktur PDF lub automatyzację przetwarzania wsadowego dużych katalogów produktów. Każdy z tych tematów opiera się na tym samym wzorcu `BarcodeGenerator` przedstawionym tutaj. Powodzenia w kodowaniu! + +## Co powinieneś nauczyć się dalej? + +Poniższe poradniki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każde źródło zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Generuj obraz kodu kreskowego – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Utwórz obraz kodu DotCode – wiersze i kolumny (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Jak utworzyć obraz kodu kreskowego i renderować go w Javie](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/polish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/polish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..a54275d0a --- /dev/null +++ b/barcode/polish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Jak szybko generować kod kreskowy przy użyciu Pythona. Dowiedz się, jak + tworzyć kod kreskowy z danych i eksportować obraz kodu kreskowego za pomocą jednej + biblioteki. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: pl +lastmod: 2026-08-12 +og_description: Jak generować kod kreskowy w Pythonie przy użyciu Aspose.BarCode. + Postępuj zgodnie z tym przewodnikiem, aby utworzyć kod kreskowy z danych i wyeksportować + obraz kodu kreskowego jako PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Jak generować kod kreskowy w Pythonie – szybki, niezawodny przewodnik +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Jak generować kod kreskowy w Pythonie – kompletny przewodnik krok po kroku +url: /pl/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak generować kod kreskowy w Pythonie – kompletny przewodnik krok po kroku + +Jeśli potrzebujesz **jak generować kod kreskowy** w aplikacji Python, ten tutorial pokaże Ci dokładny kod, którego potrzebujesz. Nauczysz się **tworzyć kod kreskowy z danych**, dostosowywać jego wygląd oraz **eksportować obraz kodu kreskowego** jako plik PNG — wszystko w mniej niż dziesięciu linijkach kodu. + +Generowanie kodu kreskowego może wydawać się odrębną kwestią od reszty logiki biznesowej, ale dzięki jednej bibliotece możesz utrzymać proces w linii z istniejącą bazą kodu. W kolejnych sekcjach zobaczysz pełny, działający przykład, zrozumiesz, dlaczego każda linijka ma znaczenie, oraz odkryjesz typowe wariacje, takie jak zmiana szerokości modułu czy rysowanie kodu kreskowego tylko z konturami. + +## Jak generować kod kreskowy przy użyciu biblioteki Aspose.BarCode + +Biblioteka Aspose.BarCode dla Pythona (przez .NET) oferuje prosty interfejs API dla wielu symbologii, w tym kodu Planet używanego w tym przewodniku. Przed rozpoczęciem upewnij się, że masz zainstalowany pakiet: + +```bash +pip install aspose-barcode +``` + +> **Wskazówka:** Używaj wirtualnego środowiska, aby uniknąć konfliktów wersji z innymi projektami. + +### 1. Importuj wymagane klasy + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Te importy dają dostęp do klasy generatora, wyliczenia typów kodów kreskowych oraz wyliczenia formatu obrazu używanego przy zapisywaniu wyniku. + +### 2. Utwórz kod kreskowy z danych + +Pierwszym krokiem jest **utworzenie kodu kreskowego z danych**. Konstruktor `BarcodeGenerator` przyjmuje symbologię oraz surowy ciąg znaków, który chcesz zakodować. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +Wartość `EncodeTypes.Planet` wybiera kod Planet, natomiast `"123456"` jest ładunkiem, który pojawi się w ostatecznym obrazie. + +### 3. Dostosuj wymiar X (szerokość modułu) + +Wymiar X kontroluje szerokość każdego modułu kodu kreskowego (cienkiej kreski). Ustawienie go na 4 piksele daje wyraźny, czytelny obraz bez nadmiernego zwiększania rozmiaru pliku. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Dlaczego to ważne:** Większy wymiar X poprawia niezawodność skanowania na drukarkach o niskiej rozdzielczości, natomiast mniejsza wartość zmniejsza rozmiar pliku przy użyciu w sieci. + +### 4. Eksportuj obraz kodu kreskowego (styl wypełniony) + +Teraz możesz **eksportować obraz kodu kreskowego** używając metody `save`. Przykład zapisuje plik PNG, ale możesz wybrać JPEG, BMP lub TIFF, zmieniając wyliczenie `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +Plik `PlanetFilled.png` zawiera w pełni wypełniony kod Planet, gotowy do druku lub osadzenia w PDF. + +### 5. Utwórz drugi generator dla kodu kreskowego tylko z konturami + +Jeśli potrzebujesz wersji z konturami (puste kreski), musisz utworzyć nowy generator, ponieważ flagi `filled_bars` nie można przełączać po zapisaniu obrazu. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Zastosuj to samo ustawienie wymiaru X + +Gdy tworzysz drugi generator, musisz powtórzyć wszystkie ustawienia wizualne, które chcesz zachować spójne. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Wyłącz wypełnione kreski dla kodu kreskowego z konturami + +Ustawienie `filled_bars` na `False` informuje renderer, aby rysował tylko kontury każdego modułu, tworząc lżejszy obraz, który może być przydatny w celach projektowych. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Eksportuj obraz kodu kreskowego z konturami + +Na koniec **eksportuj obraz kodu kreskowego** ponownie, tym razem zapisując wersję z konturami. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Masz teraz dwa pliki PNG: jeden z pełnymi kreskami (`PlanetFilled.png`) i jeden tylko z konturami (`PlanetEmpty.png`). + +## Eksportuj obraz kodu kreskowego w innych formatach (opcjonalnie) + +Metoda `save` obsługuje kilka formatów. Aby wyeksportować jako JPEG z jakością 90 %: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Jeśli potrzebujesz przezroczystego tła do użytku w sieci, wybierz PNG z kanałem alfa: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Typowe wariacje i przypadki brzegowe + +| Scenariusz | Wymagana zmiana | Fragment kodu | +|------------|----------------|---------------| +| **Inna symbologia** (np. QR) | Użyj innej wartości `EncodeTypes` | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Niestandardowy kolor pierwszego planu** | Ustaw `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Wyższa rozdzielczość** | Zwiększ DPI poprzez `image_width` i `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Długie ciągi danych** | Upewnij się, że długość danych pasuje do specyfikacji symbologii | Sprawdź długość przed utworzeniem generatora | + +> **Uwaga:** Dostarczenie danych, które przekraczają maksymalną długość dla wybranej symbologii, powoduje wyjątek w czasie wykonywania. Zawsze weryfikuj długość ciągu lub obsługuj `ArgumentException`. + +## Pełny, działający przykład + +Poniżej znajduje się kompletny skrypt, który możesz skopiować i wkleić do pliku o nazwie `generate_planet_barcode.py`. Dostosuj `YOUR_DIRECTORY` do folderu istniejącego na Twoim komputerze. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Uruchomienie tego skryptu tworzy dwa pliki PNG w określonym katalogu. Zweryfikuj wynik, otwierając obrazy w dowolnej przeglądarce obrazów; oba powinny wyświetlać kod Planet kodujący ciąg `123456`. + +## Podsumowanie + +Teraz wiesz, **jak generować kod kreskowy** w Pythonie przy użyciu Aspose.BarCode, jak **tworzyć kod kreskowy z danych** oraz jak **eksportować obraz kodu kreskowego** zarówno w stylu wypełnionym, jak i z konturami. Ten sam wzorzec działa dla innych symbologii, formatów obrazu i dostosowań wizualnych, dając Ci elastyczną bazę dla każdej funkcji związanej z kodami kreskowymi w Twojej aplikacji. + +### Kolejne kroki + +* Zbadaj inne symbologie, takie jak QR, Code‑128 lub DataMatrix, zamieniając `EncodeTypes.Planet` na pożądaną wartość. +* Zintegruj wygenerowane pliki PNG z raportami PDF przy użyciu bibliotek takich jak `ReportLab` lub `PyPDF2`. +* Eksperymentuj z dynamicznymi wartościami wymiaru X, aby dostosować rozmiar kodu kreskowego do rozdzielczości ekranu lub DPI drukarki. + +Miłego kodowania i śmiało dostosowuj przykład do własnych wymagań projektowych! + +## Co powinieneś się nauczyć dalej? + +Poniższe tutoriale obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/portuguese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/portuguese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..98909a576 --- /dev/null +++ b/barcode/portuguese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,297 @@ +--- +category: general +date: 2026-08-12 +description: Exemplo de gerador de código de barras que mostra como gerar código de + barras com tamanho de pixel preciso. Aprenda a definir a largura do módulo, a altura + da barra e criar códigos de barras Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: pt +lastmod: 2026-08-12 +og_description: O exemplo de gerador de código de barras demonstra como gerar códigos + de barras com dimensões exatas em pixels. Siga este guia para controlar a largura + do módulo e a altura da barra para os códigos Planet e RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: exemplo de gerador de código de barras – personalize o tamanho dos pixels + em C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: exemplo de gerador de código de barras – guia passo a passo para tamanhos de + pixel personalizados +url: /pt/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# exemplo de gerador de código de barras – guia passo a passo para tamanhos de pixel personalizados + +Se você precisa de um **barcode generator example** que permita controlar cada pixel, este guia mostra exatamente como fazer isso. Você aprenderá a definir a largura do módulo, especificar uma altura fixa das barras e gerar códigos de barras Planet e RM4SCC com dimensões previsíveis. + +A maioria dos desenvolvedores tem dificuldade em gerar imagens de “como gerar barcode” que pareçam iguais em todas as telas ou impressoras. Os trechos de código abaixo resolvem esse problema ao expor os parâmetros em nível de pixel da biblioteca Aspose.BarCode for .NET, permitindo produzir resultados consistentes sem adivinhações. + +## O que você aprenderá + +* Como instalar o pacote NuGet necessário. +* Como gerar um código de barras Planet com altura calculada automaticamente. +* Como gerar um código de barras Planet com altura explícita de 100 pixels. +* Como gerar um código de barras RM4SCC usando a mesma altura explícita. +* Por que o **barcode pixel size** importa para a confiabilidade da leitura. +* Dicas para solucionar problemas comuns ao gerar imagens de código de barras Planet. + +Você só precisa do .NET 6 ou superior, um ambiente básico de desenvolvimento C# e uma conexão à internet para baixar o pacote NuGet. + +--- + +## exemplo de gerador de código de barras – configure o ambiente de desenvolvimento + +Antes de escrever qualquer código, certifique‑se de que a biblioteca Aspose.BarCode está disponível para o seu projeto. + +### Instale o pacote Aspose.BarCode + +Abra um terminal na pasta do seu projeto e execute: + +```bash +dotnet add package Aspose.BarCode +``` + +O comando adiciona a versão estável mais recente do **Aspose.BarCode** ao seu `csproj`. Após a restauração terminar, você pode começar a usar a classe `BarcodeGenerator`. + +> **Pro tip:** Alvo .NET 6 ou .NET 7 para aproveitar as melhorias de desempenho mais recentes e o tratamento padrão UTF‑8. + +### Adicione as diretivas `using` necessárias + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Esses namespaces expõem a classe `BarcodeGenerator` e o enum `BarCodeImageFormat` usados mais adiante no tutorial. + +--- + +## Como gerar código de barras com tamanho de pixel personalizado + +Os três passos a seguir ilustram o **barcode generator example** completo. Cada passo se baseia no anterior, de modo que você pode copiar‑colar todo o bloco em um aplicativo console e executá‑lo sem alterações. + +### Etapa 1 – gerar um código de barras Planet com altura calculada automaticamente + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Por que isso funciona:** +*A propriedade `XDimension` define a largura de um único módulo do código de barras (o menor elemento preto ou branco). Quando você omite `BarHeight`, a biblioteca calcula uma altura que mantém a proporção padrão para códigos Planet.* + +**Saída esperada:** Um arquivo PNG chamado `PlanetAuto.png` contendo um código Planet limpo. Sua altura se adapta à largura de módulo de 4 pixels, tipicamente cerca de 60 pixels para uma carga útil de seis caracteres. + +### Etapa 2 – gerar um código de barras Planet com altura explícita de 100 pixels + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Por que você pode precisar disso:** +Às vezes o equipamento de leitura espera uma altura mínima das barras para detecção confiável. Definindo `BarHeight.Pixels`, você garante que cada imagem gerada atenda a esse requisito, independentemente do comprimento dos dados codificados. + +**Saída esperada:** `PlanetHeight100.png` mostra os mesmos dados de antes, mas as barras têm exatamente 100 pixels de altura, dando controle total sobre o tamanho visual. + +### Etapa 3 – gerar um código de barras RM4SCC com a mesma altura explícita + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Por que isso importa:** +`EncodeTypes.RM4SCC` é um código de barras linear empilhado usado em logística. Alinhar sua altura de barra com a do código Planet simplifica o processamento em lote quando ambas as simbologias aparecem na mesma etiqueta. + +**Saída esperada:** `RM4SCCHeight100.png` exibe um código RM4SCC perfeitamente dimensionado, correspondendo à altura de 100 pixels que você definiu para o código Planet. + +> **Verificação de resultado:** Abra cada PNG em um visualizador de imagens e confirme que as barras pretas têm exatamente 4 pixels de largura e, onde especificado, 100 pixels de altura. Você também pode enviar os arquivos para um aplicativo de leitura de código de barras para garantir que eles decodifiquem “123456”. + +--- + +## Entendendo o tamanho de pixel do código de barras e a altura das barras + +### O que é **barcode pixel size**? + +*Pixel size* refere‑se ao número físico de pixels de tela ou impressora que representam um único módulo (`XDimension`). Um tamanho de pixel maior gera um código de barras maior, o que pode ser mais fácil para scanners de baixa resolução, mas consome mais espaço na etiqueta. + +### Como `BarHeight` afeta a legibilidade? + +A propriedade `BarHeight` controla o comprimento vertical das barras. Normas para a maioria dos códigos 1‑D (incluindo Planet e RM4SCC) recomendam uma altura mínima de 10 mm quando impressos a 300 dpi, o que equivale a aproximadamente 118 pixels. Definir uma altura abaixo disso pode causar erros de leitura, especialmente em câmeras de dispositivos móveis. + +### Quando deixar a biblioteca calcular a altura automaticamente? + +Se você está gerando códigos de barras apenas para exibição em tela, o cálculo automático mantém a proporção consistente e reduz a necessidade de ajustes manuais. Para etiquetas impressas que precisam atender a especificações ISO rigorosas, você deve **definir explicitamente a altura da barra**. + +--- + +## Armadilhas comuns e boas práticas ao gerar código de barras Planet + +| Armadilha | Por que acontece | Solução | +|-----------|------------------|---------| +| As barras aparecem muito finas ou grossas | `XDimension` deixado no padrão (1 pixel) em telas de alta resolução | Defina `XDimension.Pixels` para pelo menos 3‑4 para clareza visual | +| O scanner não consegue ler o código | `BarHeight` está muito pequeno para o comprimento focal do scanner | Use `BarHeight.Pixels` ≥ 100 para a maioria dos scanners móveis | +| A imagem fica borrada após redimensionamento | Salvar como JPEG introduz artefatos de compressão | Salve como PNG (`BarCodeImageFormat.Png`) para saída sem perdas | +| Tipo de código de barras inesperado | Valor errado do enum `EncodeTypes` | Verifique se está usando `EncodeTypes.Planet` para a simbologia Planet | + +### Dica profissional sobre desempenho + +Ao gerar milhares de códigos de barras em um trabalho em lote, reutilize uma única instância de `BarcodeGenerator` e altere apenas `CodeText` e os parâmetros de tamanho entre as gravações. Isso evita alocações repetidas de objetos internos de renderização e pode reduzir o tempo de execução em até 30 %. + +--- + +## Exemplo completo funcionando – junte tudo + +Crie um novo projeto console (`dotnet new console -n BarcodeDemo`) e substitua o conteúdo de `Program.cs` pelo seguinte: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Execute o programa com `dotnet run`. Após a execução, você encontrará três arquivos PNG na pasta do projeto, cada um ilustrando um cenário diferente do **barcode generator example**. + +--- + +## Próximos passos e tópicos relacionados + +* **Como gerar código de barras em outros formatos** – explore `EncodeTypes.Code128`, `EncodeTypes.QR` e `EncodeTypes.DataMatrix` para necessidades 2‑D. +* **Incorporando códigos de barras em PDFs** – combine Aspose.BarCode com Aspose.PDF para colocar códigos de barras diretamente em modelos de fatura. +* **Tamanho dinâmico de código de barras baseado na entrada do usuário** – calculate + +## O que você deve aprender a seguir? + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas de implementação em seus próprios projetos. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/portuguese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/portuguese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..57a949af2 --- /dev/null +++ b/barcode/portuguese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-08-12 +description: Configure rapidamente o layout de código de barras Databar em Python. + Aprenda a definir colunas, linhas e salvar imagens com a biblioteca geradora de + códigos de barras. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: pt +lastmod: 2026-08-12 +og_description: Configure o layout do código de barras Databar em Python para controlar + colunas, linhas e a saída de imagem. Siga este guia para uma solução pronta‑para‑usar. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Configure o layout do código de barras Databar em Python – tutorial completo +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Configure o layout de código de barras Databar em Python – guia passo a passo +url: /pt/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Configure o layout de código de barras Databar em Python – guia passo a passo + +Se você precisa **configurar o layout de código de barras Databar em Python**, este guia o conduzirá por todo o processo. Você verá como definir o número de colunas ou linhas para um código de barras Databar Expanded Stacked e como salvar a imagem resultante com uma única chamada à biblioteca geradora de códigos de barras. + +Controlar o layout é essencial ao incorporar códigos de barras em embalagens estreitas, recibos ou telas móveis. Nas seções abaixo, abordaremos as importações necessárias, as duas opções de layout (colunas e linhas) e as melhores práticas para salvar uma imagem PNG limpa. + +## O que você precisará + +* Python 3.8 ou superior +* `aspose.barcode` (ou qualquer pacote compatível de geração de códigos de barras) instalado + ```bash + pip install aspose-barcode + ``` +* Permissão de escrita em uma pasta onde os arquivos PNG serão armazenados + +Nenhuma ferramenta externa adicional é necessária — a biblioteca lida com renderização, dimensionamento e codificação de imagem internamente. + +## Como configurar o layout de código de barras Databar em Python + +O núcleo da solução é a classe `BarcodeGenerator`. Ela aceita um enum `EncodeTypes` que identifica a simbologia do código de barras — neste caso `EncodeTypes.DatabarExpandedStacked`. Após criar o gerador, você pode ajustar o layout definindo as propriedades `columns` ou `rows` no objeto de parâmetro `data_bar`. + +### Etapa 1: Importar as classes necessárias + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Essas importações dão acesso ao gerador, ao enum para tipos Databar e à constante de formato de imagem PNG. + +### Etapa 2: Criar um gerador de código de barras para Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Por que esta etapa?* +`EncodeTypes.DatabarExpandedStacked` indica à biblioteca que ela deve produzir a simbologia **Databar Expanded Stacked**, que suporta sequências numéricas mais longas mantendo uma pegada compacta. O segundo argumento é o dado a ser codificado; pode ser qualquer string que atenda à especificação Databar. + +### Etapa 3: Definir o número de colunas (layout horizontal) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** é a frase‑chave para esta operação. Quando você aumenta a contagem de colunas, o código de barras se expande horizontalmente, o que pode ser útil para rótulos largos. A biblioteca recalcula automaticamente a largura do módulo para manter o tamanho geral consistente. + +#### Dica profissional +A contagem máxima de colunas para Databar Expanded Stacked é 8. Definir um valor acima do limite o limitará ao máximo, mas é melhor validar sua entrada antecipadamente. + +### Etapa 4: Salvar a imagem do código de barras com o layout de colunas + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** é a ação que grava o código de barras renderizado no disco. PNG é sem perdas, o que preserva as bordas nítidas necessárias para uma leitura confiável. + +### Etapa 5: Criar um segundo gerador para o mesmo tipo de código de barras (layout de linhas) + +Se você prefere uma pilha vertical, trabalha com linhas em vez de colunas. O código abaixo reutiliza o mesmo valor, mas cria uma nova instância de `BarcodeGenerator` para evitar misturar configurações de colunas e linhas. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Etapa 6: Definir o número de linhas (layout vertical) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** organiza os módulos do código de barras verticalmente. Um layout de três linhas reduz a altura de cada pilha individual, tornando o código de barras adequado para recibos estreitos ou telas móveis. + +#### Caso de borda +Se você definir `rows` como 1, a biblioteca gera um Databar de linha única (equivalente a um Databar padrão). Valores abaixo de 1 são ignorados e redefinidos para o padrão (1 linha). + +### Etapa 7: Salvar a imagem do código de barras com o layout de linhas + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Novamente, usamos **save barcode image** com PNG para manter a saída nítida. + +## Exemplo completo executável + +Juntando todas as peças, você obtém um script autônomo que pode ser inserido em qualquer projeto Python. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Saída esperada** + +Executar o script cria dois arquivos PNG: + +* `output/ExpandedCols4.png` – um código de barras estendido em quatro colunas +* `output/ExpandedRows3.png` – um código de barras comprimido em três linhas + +Ambas as imagens podem ser abertas em qualquer visualizador de imagens ou importadas diretamente em faturas PDF, modelos de etiquetas ou páginas da web. + +## Perguntas comuns e solução de problemas + +| Pergunta | Resposta | +|----------|----------| +| *E se o código de barras parecer borrado?* | Aumente a resolução da imagem definindo `barcode_generator.parameters.image_width` e `image_height` antes de chamar `save`. | +| *Posso usar outros formatos de imagem?* | Sim. Substitua `BarCodeImageFormat.Png` por `Jpeg`, `Bmp` ou `Gif` conforme necessário. | +| *Existe um limite para o comprimento dos dados?* | Databar Expanded Stacked suporta até 74 caracteres numéricos. Exceder o limite gera uma `ArgumentException`. | +| *Como altero a cor de primeiro plano?* | Use `barcode_generator.parameters.barcode.color = Color.Blue` (importe `System.Drawing.Color`). | +| *Posso combinar colunas e linhas?* | Não. A API trata colunas e linhas como modos de layout mutuamente exclusivos. Escolha um por instância de código de barras. | + +## Próximos passos + +Agora que você pode **configurar o layout de código de barras Databar**, considere explorar estes tópicos relacionados: + +* **Adicionar legendas de texto** – use `barcode_generator.parameters.barcode.code_text` para exibir o valor codificado abaixo da imagem. +* **Incorporar o código de barras em um PDF** – combine o PNG gerado com `aspose.pdf` para criar documentos imprimíveis. +* **Dimensionamento dinâmico** – calcule a contagem ótima de colunas ou linhas com base nas dimensões da etiqueta em tempo de execução. +* **Processamento em lote** – percorra um CSV de códigos de produto para gerar automaticamente uma biblioteca de imagens de códigos de barras. + +Experimente diferentes valores de colunas e linhas para ver como eles afetam a confiabilidade da leitura em seus dispositivos-alvo. Quanto mais você testar, melhor compreenderá as compensações entre tamanho do código de barras, legibilidade e restrições de espaço. + +--- + +*Feliz codificação! Se você achou este tutorial útil, compartilhe com colegas ou deixe um comentário sobre os desafios de layout que enfrentou.* + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá-lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Criar imagem de código de barras DotCode – linhas e colunas (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Criar imagem de código de barras c# – Configurar linhas e colunas do Codablock F](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [Ajuste de altura do código de barras Databar unidimensional](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/portuguese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/portuguese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..7daec1a89 --- /dev/null +++ b/barcode/portuguese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: Crie imagem de código de barras em C# usando BarCodeGenerator. Aprenda + a gerar DataBar, controlar o tamanho da imagem do código de barras e criar múltiplos + códigos de barras de forma eficiente. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: pt +lastmod: 2026-08-12 +og_description: Crie imagem de código de barras em C# com BarCodeGenerator. Este tutorial + mostra passo a passo como gerar códigos DataBar, ajustar o tamanho da imagem do + código de barras e produzir múltiplos códigos de barras. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Criar imagem de código de barras em C# – guia completo do BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Criar imagem de código de barras em C# com BarCodeGenerator +url: /pt/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar imagem de código de barras em C# com BarCodeGenerator + +Se você precisa **criar imagem de código de barras** em uma aplicação .NET, este guia mostra exatamente como fazer isso com a classe `BarCodeGenerator`. Seja construindo um sistema POS de varejo ou uma ferramenta de rastreamento de inventário, você aprenderá a gerar símbolos DataBar, controlar o tamanho da imagem do código de barras e produzir vários códigos de barras em uma única execução. + +Você também descobrirá como a API **barcode generator c#** permite ajustar dimensões, mudar formatos de saída e lidar com casos extremos, como strings de dados inválidas. Ao final do tutorial, você poderá **criar múltiplos códigos de barras** com confiança, sem escrever código repetitivo. + +## Pré-requisitos + +- .NET 6.0 ou posterior instalado +- Um ambiente de desenvolvimento (Visual Studio, Rider ou VS Code) +- O pacote NuGet Aspose.BarCode for .NET (ou qualquer biblioteca compatível que forneça `BarCodeGenerator`) + +Você pode adicionar o pacote com: + +```bash +dotnet add package Aspose.BarCode +``` + +## O que este tutorial cobre + +1. Configurar uma instância **barcode generator c#** para codificação DataBar Omni‑directional. +2. Ajustar o **tamanho da imagem do código de barras** alterando a X‑dimension e a altura das barras. +3. Usar um loop para **criar múltiplos códigos de barras** com alturas diferentes. +4. Salvar as imagens como arquivos PNG e verificar a saída. + +Todos os trechos de código estão completos e prontos para copiar‑colar em um novo projeto de console. + +![Create barcode image example](barcode-example.png){alt="Exemplo de criação de imagem de código de barras"} + +## Etapa 1: Inicializar o gerador – fundamentos da criação de imagem de código de barras + +O primeiro passo é instanciar `BarCodeGenerator` com a simbologia desejada. Para um símbolo DataBar Omni‑directional, você usa `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Por que isso importa:** Instanciar o gerador define as regras de codificação e a carga de dados. Se você omitir o valor correto de `EncodeTypes`, a biblioteca produzirá um código de barras não suportado ou lançará uma exceção. + +## Etapa 2: Configurar X‑dimension e altura da barra – controlar o tamanho da imagem do código de barras + +O tamanho visual de um código de barras é determinado por dois parâmetros: + +| Parâmetro | O que controla | Faixa típica | +|-----------|----------------|--------------| +| `x_dimension.pixels` | Largura do menor módulo (o “ponto”) | 1 – 4 px | +| `bar_height.pixels` | Altura das barras verticais | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Dica profissional:** Uma X‑dimension menor gera uma imagem de maior resolução, mas pode ser mais difícil de escanear em impressoras de baixa qualidade. Ajuste o valor com base no equipamento de leitura alvo. + +## Etapa 3: Salvar o primeiro código de barras – criar imagem de código de barras com altura de 30 px + +Agora você pode gerar a imagem e gravá‑la no disco. O método `Save` aceita um caminho de arquivo e um enum de formato de imagem. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Resultado esperado:** Um arquivo PNG chamado `Databar30.png` aparece em `C:\Barcodes`. Ao abrir o arquivo, você verá um símbolo DataBar Omni‑directional com um padrão claro e de alto contraste. + +## Etapa 4: Alterar a altura e gerar imagens adicionais – criar múltiplos códigos de barras + +Para **criar múltiplos códigos de barras** com dimensões diferentes, basta modificar a propriedade `BarHeight` e chamar `Save` novamente. Isso evita reinstanciar o gerador, economizando memória e tempo de CPU. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Por que isso funciona:** O objeto `BarCodeGenerator` mantém todo o estado de configuração. Alterar uma única propriedade atualiza o motor de renderização para a próxima chamada de `Save`, permitindo que você **crie múltiplos códigos de barras** de forma eficiente. + +## Etapa 5: Avançado – como gerar DataBar com dados personalizados + +O exemplo acima usa uma carga estática GS1. Em cenários reais, você frequentemente precisa incorporar identificadores de produto variáveis. A biblioteca aceita qualquer string que corresponda à especificação DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Ponto chave:** Definir `generator.CodeText` atualiza os dados codificados sem recriar o objeto. Este é o padrão recomendado de **como gerar databar** ao lidar com grandes conjuntos de dados. + +## Etapa 6: Verificar e solucionar problemas – garantindo o tamanho correto da imagem do código de barras + +Depois de gerar as imagens, você pode querer confirmar programaticamente que as dimensões correspondem às suas expectativas. A classe `Image` de `System.Drawing` pode ler o arquivo e relatar seu tamanho. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Se a altura não refletir o valor que você definiu, verifique: + +- **X‑dimension**: Um valor muito pequeno pode fazer o renderizador arredondar a altura. +- **Formato da imagem**: Alguns formatos (por exemplo, JPEG) aplicam compressão que pode alterar as dimensões em pixels ao salvar. PNG preserva as dimensões exatas. + +## Etapa 7: Melhores práticas para tamanho de imagem de código de barras e desempenho + +| Recomendação | Razão | +|--------------|-------| +| Mantenha `x_dimension.pixels` entre 2 – 3 px para a maioria dos scanners. | Equilibra legibilidade e tamanho do arquivo. | +| Use PNG para saída sem perdas quando a imagem será impressa. | Garante dimensões exatas e bordas nítidas. | +| Reutilize uma única instância de `BarCodeGenerator` ao gerar muitos códigos de barras. | Reduz a sobrecarga de alocação de objetos. | +| Valide a string de entrada contra o padrão GS1 antes de atribuir a `CodeText`. | Previna exceções em tempo de execução e leituras inválidas. | +| Armazene as imagens geradas em uma pasta dedicada com uma convenção de nomenclatura clara (por exemplo, `Databar_{GTIN}.png`). | Simplifica o processamento posterior e trilhas de auditoria. | + +## Exemplo completo em funcionamento + +Abaixo está o programa completo que incorpora todas as etapas, da inicialização à verificação. Copie o código para um novo projeto de console e execute-o. + + + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [Gerar imagem de código de barras – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Criar imagem de código de barras DotCode – linhas & colunas (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Como criar zona silenciosa de código de barras para ITF-14 usando Aspose.BarCode para .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/portuguese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/portuguese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..d42fffe16 --- /dev/null +++ b/barcode/portuguese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-12 +description: Crie um databar omnidirecional com Python e aprenda como criar imagem + de código de barras em Python usando Aspose.BarCode. Siga o guia passo a passo para + uma solução completa. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: pt +lastmod: 2026-08-12 +og_description: Crie um databar omnidirecional com Python e gere uma imagem de código + de barras em minutos. Este tutorial mostra um exemplo completo e executável. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Crie uma barra de dados omnidirecional – guia completo de Python +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Criar imagem de databar e código de barras omnidirecional em Python +url: /pt/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar databar omnidirecional e imagem de código de barras em Python + +Se você precisa **criar databar omnidirecional** em um projeto Python, este guia mostra como fazer isso e também como **criar imagem de código de barras python** usando a biblioteca Aspose.BarCode. Você receberá um script pronto‑para‑executar que produz dois arquivos PNG com diferentes proporções. + +Gerar um DataBar que segue a especificação omnidirecional é um requisito comum para aplicações de varejo e logística. O tutorial cobre instalação, configuração da dimensão X, ajuste da proporção e salvamento das imagens finais. Nenhum serviço externo é necessário; tudo roda localmente. + +## O que você precisará + +Antes de começar, certifique‑se de que você tem: + +* Python 3.8 ou mais recente instalado na sua máquina. +* Acesso a um terminal ou prompt de comando. +* Permissão de escrita em uma pasta onde as imagens de código de barras serão salvas. + +A única dependência de terceiros é **Aspose.BarCode for Python via .NET**, que suporta o tipo DataBar omnidirecional nativamente. + +## Etapa 1: Instalar Aspose.BarCode para Python + +Aspose.BarCode fornece a classe `BarcodeGenerator` usada no código de exemplo. Instale o pacote com `pip`: + +```bash +pip install aspose-barcode +``` + +O pacote inclui as ligações necessárias ao runtime .NET, portanto você não precisa instalar o .NET SDK separadamente. + +## Etapa 2: Importar a biblioteca e criar o gerador + +A primeira linha do script cria um gerador para um DataBar omnidirecional empilhado. O valor GTIN‑14 `(01)12345678901231` é usado como dado de exemplo. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Por que esta etapa importa*: A constante `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` indica à biblioteca que o valor deve ser codificado como um DataBar omnidirecional, formato exigido por muitos scanners de ponto de venda. + +## Etapa 3: Definir a dimensão X (largura do módulo) + +A dimensão X define a largura do menor módulo de barra. Um valor de `2` pixels produz um código de barras claro e legível sem tamanho de arquivo excessivo. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Por que esta etapa importa*: Ajustar a dimensão X permite equilibrar legibilidade e dimensões da imagem. Uma dimensão X muito pequena pode gerar má qualidade em impressoras de baixa resolução. + +## Etapa 4: Configurar a proporção e salvar a primeira imagem + +A proporção influencia a altura total do DataBar em relação à sua largura. Uma proporção de `15` cria um estilo visual compacto. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Dica profissional**: Use `pathlib.Path` para construir o caminho de saída, o que cria diretórios ausentes automaticamente. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Etapa 5: Alterar a proporção para um segundo estilo visual e salvar outra imagem + +Mudar a proporção para `30` produz um código de barras mais alto, que pode ser exigido por hardware de scanner específico. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Por que esta etapa importa*: Diferentes varejistas e dispositivos de leitura têm restrições de tamanho distintas. Fornecer ambas as proporções em um único script permite gerar o estilo exato que você precisa sem duplicar código. + +## Script completo – criar databar omnidirecional e imagem de código de barras python + +Abaixo está o exemplo completo e executável que incorpora todas as etapas anteriores. Salve como `generate_databar.py` e execute com `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Saída esperada + +Executar o script cria os seguintes arquivos: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Ambas as imagens exibem um DataBar omnidirecional válido que pode ser lido por equipamentos de varejo padrão. + +![exemplo de criação de databar omnidirecional e imagem de código de barras em Python](example_databar.png "criar databar omnidirecional e imagem de código de barras python") + +*A imagem acima é um placeholder que ilustra os dois arquivos PNG salvos.* + +## Tratamento de problemas comuns + +| Problema | Motivo | Solução | +|----------|--------|---------| +| `ImportError: No module named aspose` | Aspose.BarCode não instalado ou instalado em outro ambiente. | Ative o ambiente virtual correto e execute `pip install aspose-barcode`. | +| `PermissionError` ao salvar | O script não tem permissão de escrita na pasta de destino. | Escolha um diretório que você possua ou execute o script com privilégios adequados. | +| Código de barras não lê | Dimensão X muito baixa ou proporção incompatível com o scanner. | Aumente `x_dimension.pixels` para 3 ou 4 e teste diferentes valores de `aspect_ratio` (ex.: 20, 25). | +| Runtime .NET ausente | Aspose.BarCode depende do runtime .NET no Windows/Linux. | Instale o runtime .NET mais recente a partir do site da Microsoft; a documentação do pacote fornece orientações específicas por plataforma. | + +## Estendendo o exemplo + +Você pode adaptar o script para gerar outras variantes de DataBar (ex.: `DATABAR_STACKED`, `DATABAR_EXPANDED`). Substitua a constante `EncodeTypes` conforme necessário: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Se precisar incorporar o código de barras em um PDF, Aspose.PDF para Python pode importar o arquivo PNG diretamente ou você pode usar o método `save` com `BarCodeImageFormat.Pdf`. + +## Conclusão + +Este tutorial mostrou como **criar databar omnidirecional** e como **criar imagem de código de barras python** usando Aspose.BarCode. Agora você tem um script completo e reproduzível que gera dois arquivos PNG com diferentes proporções, lida com armadilhas comuns e pode ser estendido para outros formatos de código de barras. + +Em seguida, explore a geração de QR codes, a adição do código de barras a faturas PDF ou a automação de processamento em lote para grandes catálogos de produtos. Cada um desses tópicos se baseia no mesmo padrão `BarcodeGenerator` demonstrado aqui. Boa codificação! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas de implementação em seus próprios projetos. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to create barcode image and render it in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/portuguese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/portuguese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..4b16c541d --- /dev/null +++ b/barcode/portuguese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Como gerar códigos de barras rapidamente usando Python. Aprenda a criar + códigos de barras a partir de dados e exportar a imagem do código de barras com + uma única biblioteca. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: pt +lastmod: 2026-08-12 +og_description: Como gerar código de barras em Python com Aspose.BarCode. Siga este + guia para criar código de barras a partir de dados e exportar a imagem do código + de barras como PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Como gerar código de barras em Python – guia rápido e confiável +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Como gerar código de barras em Python – guia completo passo a passo +url: /pt/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como gerar código de barras em Python – guia completo passo a passo + +Se você precisa **gerar código de barras** em uma aplicação Python, este tutorial mostra o código exato que você precisa. Você aprenderá a **criar código de barras a partir de dados**, ajustar sua aparência e **exportar a imagem do código de barras** como um arquivo PNG — tudo em menos de dez linhas de código. + +Gerar um código de barras pode parecer uma preocupação separada da lógica de negócio, mas com uma única biblioteca você pode manter o processo integrado ao seu código existente. Nas seções a seguir você verá um exemplo completo e executável, entenderá por que cada linha é importante e descobrirá variações comuns, como mudar a largura do módulo ou desenhar um código de barras apenas com contorno. + +## Como gerar código de barras com a biblioteca Aspose.BarCode + +A biblioteca Aspose.BarCode para Python (via .NET) fornece uma API direta para muitas simbologias, incluindo o código de barras Planet usado neste guia. Antes de começar, certifique‑se de que o pacote está instalado: + +```bash +pip install aspose-barcode +``` + +> **Dica profissional:** Use um ambiente virtual para evitar conflitos de versão com outros projetos. + +### 1. Importar as classes necessárias + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Essas importações dão acesso à classe geradora, à enumeração dos tipos de código de barras e à enumeração de formatos de imagem usada ao salvar o resultado. + +### 2. Criar código de barras a partir de dados + +O primeiro passo é **criar código de barras a partir de dados**. O construtor `BarcodeGenerator` recebe a simbologia e a string bruta que você deseja codificar. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +O valor `EncodeTypes.Planet` seleciona o código de barras Planet, enquanto `"123456"` é a carga útil que aparecerá na imagem final. + +### 3. Ajustar a dimensão X (largura do módulo) + +A dimensão X controla a largura de cada módulo do código de barras (a barra fina). Definir 4 pixels fornece uma imagem clara e legível sem tornar o arquivo muito grande. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Por que isso importa:** Uma dimensão X maior melhora a confiabilidade da leitura em impressoras de baixa resolução, enquanto um valor menor reduz o tamanho do arquivo para uso na web. + +### 4. Exportar imagem do código de barras (estilo preenchido) + +Agora você pode **exportar a imagem do código de barras** usando o método `save`. O exemplo salva um arquivo PNG, mas você pode escolher JPEG, BMP ou TIFF alterando a enumeração `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +O arquivo `PlanetFilled.png` contém um código de barras Planet totalmente preenchido, pronto para impressão ou incorporação em um PDF. + +### 5. Criar um segundo gerador para um código de barras apenas com contorno + +Se precisar de uma versão de contorno (barras vazias), deve criar um novo gerador porque a flag `filled_bars` não pode ser alterada após a imagem ser salva. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Aplicar a mesma configuração de dimensão X + +Ao criar um segundo gerador, você deve repetir todas as configurações visuais que deseja manter consistentes. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Desativar barras preenchidas para um código de barras de contorno + +Definir `filled_bars` como `False` indica ao renderizador que desenhe apenas os contornos de cada módulo, produzindo uma imagem mais leve que pode ser útil para fins de design. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Exportar a imagem do código de barras de contorno + +Finalmente, **exporte a imagem do código de barras** novamente, desta vez armazenando a versão de contorno. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Agora você tem dois arquivos PNG: um com barras sólidas (`PlanetFilled.png`) e outro apenas com contornos (`PlanetEmpty.png`). + +## Exportar imagem do código de barras em outros formatos (opcional) + +O método `save` suporta vários formatos. Para exportar como JPEG com 90 % de qualidade: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Se precisar de fundo transparente para uso na web, escolha PNG com canal alfa: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Variações comuns e casos de borda + +| Cenário | Alteração necessária | Trecho de código | +|----------|----------------------|------------------| +| **Simbologia diferente** (ex.: QR) | Use um valor diferente de `EncodeTypes` | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Cor de primeiro plano personalizada** | Defina `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Resolução mais alta** | Aumente DPI via `image_width` e `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Strings de dados grandes** | Garanta que o comprimento dos dados se ajuste à especificação da simbologia | Valide o comprimento antes de criar o gerador | + +> **Atenção:** Fornecer dados que excedam o comprimento máximo para a simbologia escolhida gera uma exceção em tempo de execução. Sempre valide o tamanho da string ou capture `ArgumentException`. + +## Exemplo completo e executável + +Abaixo está o script completo que você pode copiar‑colar em um arquivo chamado `generate_planet_barcode.py`. Ajuste `YOUR_DIRECTORY` para uma pasta que exista na sua máquina. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Executar este script produz dois arquivos PNG no diretório especificado. Verifique a saída abrindo as imagens em qualquer visualizador; ambas devem exibir um código de barras Planet codificando a string `123456`. + +## Conclusão + +Agora você sabe **como gerar código de barras** em Python usando Aspose.BarCode, como **criar código de barras a partir de dados** e como **exportar a imagem do código de barras** tanto em estilo preenchido quanto em contorno. O mesmo padrão se aplica a outras simbologias, formatos de imagem e personalizações visuais, oferecendo uma base flexível para qualquer recurso relacionado a códigos de barras em sua aplicação. + +### Próximos passos + +* Explore outras simbologias como QR, Code‑128 ou DataMatrix substituindo `EncodeTypes.Planet` pelo valor desejado. +* Integre os arquivos PNG gerados em relatórios PDF usando bibliotecas como `ReportLab` ou `PyPDF2`. +* Experimente valores dinâmicos de dimensão X para adaptar o tamanho do código de barras com base na resolução da tela ou DPI da impressora. + +Feliz codificação, e sinta‑se à vontade para adaptar o exemplo às necessidades do seu próprio projeto! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas de implementação em seus próprios projetos. + +- [Como gerar imagem de código de barras em Java com Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Como gerar código de barras Java – Guia completo de configuração](/barcode/english/java/barcode-configuration/) +- [Como criar imagens de código de barras code128 em Java com Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/russian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/russian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..cb338d7a6 --- /dev/null +++ b/barcode/russian/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,286 @@ +--- +category: general +date: 2026-08-12 +description: пример генератора штрихкодов, показывающий, как генерировать штрихкод + с точным размером пикселя. Узнайте, как задать ширину модуля, высоту полосы и создавать + штрихкоды Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: ru +lastmod: 2026-08-12 +og_description: Пример генератора штрихкодов демонстрирует, как создавать штрихкоды + с точными пиксельными размерами. Следуйте этому руководству, чтобы управлять шириной + модуля и высотой полосы для кодов Planet и RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: пример генератора штрихкода – настройка размера пикселя в C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: пример генератора штрихкода — пошаговое руководство по пользовательским размерам + пикселей +url: /ru/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Пример генератора штрихкода – пошаговое руководство по пользовательским размерам пикселей + +Если вам нужен **barcode generator example**, позволяющий контролировать каждый пиксель, это руководство покажет, как это сделать. Вы научитесь задавать ширину модуля, определять фиксированную высоту полосы и генерировать штрихкоды Planet и RM4SCC с предсказуемыми размерами. + +Большинство разработчиков сталкиваются с проблемой «как сгенерировать штрихкод», когда изображения выглядят по‑разному на разных экранах или принтерах. Приведённые ниже фрагменты кода решают эту проблему, раскрывая параметры уровня пикселей библиотеки Aspose.BarCode for .NET, чтобы вы могли получать согласованный результат без догадок. + +## Что вы узнаете + +* Как установить требуемый пакет NuGet. +* Как сгенерировать штрихкод Planet с автоматически вычисляемой высотой. +* Как сгенерировать штрихкод Planet с явно заданной высотой 100 пикселей. +* Как сгенерировать штрихкод RM4SCC, используя ту же явно заданную высоту. +* Почему **barcode pixel size** важен для надёжности сканирования. +* Советы по устранению распространённых проблем при генерации изображений штрихкода Planet. + +Вам понадобится только .NET 6 или новее, базовая среда разработки C# и подключение к интернету для загрузки пакета NuGet. + +--- + +## barcode generator example – настройка среды разработки + +Прежде чем писать код, убедитесь, что библиотека Aspose.BarCode доступна вашему проекту. + +### Установите пакет Aspose.BarCode + +Откройте терминал в папке проекта и выполните: + +```bash +dotnet add package Aspose.BarCode +``` + +Команда добавит последнюю стабильную версию **Aspose.BarCode** в ваш `csproj`. После завершения восстановления вы сможете начать использовать класс `BarcodeGenerator`. + +> **Pro tip:** Нацельтесь на .NET 6 или .NET 7, чтобы воспользоваться последними улучшениями производительности и обработкой UTF‑8 по умолчанию. + +### Добавьте необходимые директивы `using` + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Эти пространства имён предоставляют класс `BarcodeGenerator` и перечисление `BarCodeImageFormat`, используемые далее в руководстве. + +## Как сгенерировать штрихкод с пользовательским размером пикселей + +Ниже представлены три шага, иллюстрирующие полный **barcode generator example**. Каждый шаг опирается на предыдущий, поэтому вы можете скопировать‑вставить весь блок в консольное приложение и запустить его без изменений. + +### Шаг 1 – сгенерировать штрихкод Planet с автоматически вычисляемой высотой + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Почему это работает:** +*Свойство `XDimension` определяет ширину одного модуля штрихкода (самого маленького чёрного или белого элемента). Когда вы опускаете `BarHeight`, библиотека рассчитывает высоту, сохраняющую стандартное соотношение сторон для кодов Planet.* + +**Ожидаемый результат:** PNG‑файл `PlanetAuto.png` с чистым штрихкодом Planet. Его высота адаптируется к ширине модуля 4 пикселя, обычно около 60 пикселей для шестизначного полезного сообщения. + +### Шаг 2 – сгенерировать штрихкод Planet с явно заданной высотой 100 пикселей + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Зачем это может понадобиться:** +Иногда оборудование сканирования требует минимальную высоту полосы для надёжного обнаружения. Установив `BarHeight.Pixels`, вы гарантируете, что каждое сгенерированное изображение удовлетворяет этому требованию, независимо от длины кодируемых данных. + +**Ожидаемый результат:** `PlanetHeight100.png` показывает те же данные, что и раньше, но полосы имеют ровно 100 пикселей в высоту, давая вам полный контроль над визуальным размером. + +### Шаг 3 – сгенерировать штрихкод RM4SCC с той же явно заданной высотой + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Почему это важно:** +`EncodeTypes.RM4SCC` – это штабелированный линейный штрихкод, используемый в логистике. Выравнивание его высоты с высотой штрихкода Planet упрощает пакетную обработку, когда обе символьные системы появляются на одной этикетке. + +**Ожидаемый результат:** `RM4SCCHeight100.png` отображает идеально размерный штрихкод RM4SCC, соответствующий высоте 100 пикселей, установленной для кода Planet. + +> **Проверка результата:** Откройте каждый PNG в просмотрщике изображений и убедитесь, что чёрные полосы ровно 4 пикселя в ширину и, где указано, 100 пикселей в высоту. Вы также можете загрузить файлы в приложение‑сканер, чтобы убедиться, что они декодируются в «123456». + +## Понимание размера пикселя штрихкода и высоты полосы + +### Что такое **barcode pixel size**? + +*Размер пикселя* — это физическое количество пикселей экрана или принтера, представляющих один модуль (`XDimension`). Больший размер пикселя даёт более крупный штрихкод, который может быть легче считывать сканерам низкого разрешения, но занимает больше места на этикетке. + +### Как `BarHeight` влияет на читаемость? + +Свойство `BarHeight` управляет вертикальной длиной полос. Стандарты большинства 1‑D штрихкодов (включая Planet и RM4SCC) рекомендуют минимальную высоту 10 мм при печати с 300 dpi, что примерно соответствует 118 пикселям. Установка высоты ниже этой может вызвать ошибки чтения, особенно на мобильных камерах. + +### Когда следует позволить библиотеке автоматически рассчитывать высоту? + +Если вы генерируете штрихкоды только для отображения на экране, автоматический расчёт сохраняет соотношение сторон и уменьшает необходимость ручной настройки. Для печатных этикеток, которым необходимо соответствовать строгим требованиям ISO, следует **явно задавать высоту полосы**. + +## Распространённые подводные камни и лучшие практики при генерации штрихкода Planet + +| Проблема | Почему происходит | Решение | +|----------|-------------------|---------| +| Полосы выглядят слишком тонкими или толстыми | `XDimension` оставлен по умолчанию (1 пиксель) на дисплеях с высоким разрешением | Установите `XDimension.Pixels` минимум 3‑4 для визуальной чёткости | +| Сканер не может прочитать код | `BarHeight` слишком мал для фокусного расстояния сканера | Используйте `BarHeight.Pixels` ≥ 100 для большинства мобильных сканеров | +| Изображение размыто после масштабирования | Сохранение в JPEG добавляет артефакты сжатия | Сохраняйте как PNG (`BarCodeImageFormat.Png`) для без потерь | +| Неожиданный тип штрихкода | Неправильное значение перечисления `EncodeTypes` | Проверьте, что используете `EncodeTypes.Planet` для символьной системы Planet | + +### Pro tip по производительности + +При генерации тысяч штрихкодов в пакетной задаче переиспользуйте один экземпляр `BarcodeGenerator` и меняйте только `CodeText` и параметры размера между сохранениями. Это избавляет от повторного выделения внутренних объектов рендеринга и может сократить время выполнения до 30 %. + +## Полный рабочий пример – собрать всё вместе + +Создайте новый консольный проект (`dotnet new console -n BarcodeDemo`) и замените содержимое `Program.cs` следующим кодом: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Запустите программу командой `dotnet run`. После выполнения вы найдёте три PNG‑файла в папке проекта, каждый из которых иллюстрирует отдельный сценарий **barcode generator example**. + +## Следующие шаги и связанные темы + +* **Как генерировать штрихкоды в других форматах** – изучите `EncodeTypes.Code128`, `EncodeTypes.QR` и `EncodeTypes.DataMatrix` для 2‑D потребностей. +* **Встраивание штрихкодов в PDF** – комбинируйте Aspose.BarCode с Aspose.PDF, чтобы размещать штрихкоды непосредственно в шаблонах счетов. +* **Динамический размер штрихкода на основе ввода пользователя** – вычисляйте + +## Что следует изучить дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Как генерировать штрихкод Java: создать точное изображение штрихкода](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [Как генерировать штрихкод в Java: создать и задать размер для полного изображения штрихкода](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [Как создать штрихкод Code128 в Java и задать высоту полос](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/russian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/russian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..f100ca3fd --- /dev/null +++ b/barcode/russian/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-08-12 +description: Быстро настройте макет штрихкода Databar в Python. Узнайте, как задать + столбцы, строки и сохранять изображения с помощью библиотеки генератора штрихкодов. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: ru +lastmod: 2026-08-12 +og_description: Настройте макет штрих‑кода Databar в Python, чтобы управлять столбцами, + строками и выводом изображения. Следуйте этому руководству для готового решения. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Настройка макета штрихкода Databar в Python — полный учебник +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Настройка макета штрих‑кода Databar в Python — пошаговое руководство +url: /ru/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Настройка макета штрих‑кода Databar в Python – пошаговое руководство + +Если вам нужно **настроить макет штрих‑кода Databar в Python**, это руководство проведёт вас через весь процесс. Вы увидите, как задать количество столбцов или строк для штрих‑кода Databar Expanded Stacked и как сохранить полученное изображение одним вызовом библиотеки генерации штрих‑кодов. + +Контроль макета важен, когда вы размещаете штрих‑коды на узкой упаковке, чеках или экранах мобильных устройств. В разделах ниже мы рассмотрим необходимые импорты, два варианта макета (столбцы и строки) и лучшие практики сохранения чистого PNG‑изображения. + +## Что понадобится + +Прежде чем начать, убедитесь, что у вас есть: + +* Python 3.8 или новее +* `aspose.barcode` (или любой совместимый пакет генерации штрих‑кодов) установлен + ```bash + pip install aspose-barcode + ``` +* Права записи в папку, где будут храниться PNG‑файлы + +Дополнительные внешние инструменты не требуются — библиотека самостоятельно обрабатывает рендеринг, масштабирование и кодирование изображения. + +## Как настроить макет штрих‑кода Databar в Python + +Ядром решения является класс `BarcodeGenerator`. Он принимает перечисление `EncodeTypes`, которое определяет символьность штрих‑кода — в данном случае `EncodeTypes.DatabarExpandedStacked`. После создания генератора вы можете изменить макет, задав свойства `columns` или `rows` у параметра `data_bar`. + +### Шаг 1: Импортировать необходимые классы + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Эти импорты дают доступ к генератору, перечислению типов Databar и константе формата изображения PNG. + +### Шаг 2: Создать генератор штрих‑кода для Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Зачем это нужно?* +`EncodeTypes.DatabarExpandedStacked` указывает библиотеке генерировать символьность **Databar Expanded Stacked**, которая поддерживает более длинные числовые строки при компактном размере. Второй аргумент — данные для кодирования; это может быть любая строка, соответствующая спецификации Databar. + +### Шаг 3: Задать количество столбцов (горизонтальный макет) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** — ключевая фраза для этой операции. При увеличении количества столбцов штрих‑код растягивается по горизонтали, что может быть полезно для широких этикеток. Библиотека автоматически пересчитывает ширину модуля, чтобы общий размер оставался неизменным. + +#### Совет профессионала +Максимальное количество столбцов для Databar Expanded Stacked равно 8. Установка значения выше предела приведёт к его ограничению максимумом, но лучше проверять ввод заранее. + +### Шаг 4: Сохранить изображение штрих‑кода с макетом по столбцам + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** — действие, записывающее отрисованный штрих‑код на диск. PNG — без потерь, что сохраняет резкие края, необходимые для надёжного сканирования. + +### Шаг 5: Создать второй генератор для того же типа штрих‑кода (макет по строкам) + +Если вам нужен вертикальный стек, используйте строки вместо столбцов. Ниже представленный код повторно использует то же значение, но создаёт новый экземпляр `BarcodeGenerator`, чтобы не смешивать настройки столбцов и строк. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Шаг 6: Задать количество строк (вертикальный макет) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** располагает модули штрих‑кода вертикально. Макет из трёх строк уменьшает высоту каждого отдельного стека, делая штрих‑код пригодным для узких чеков или мобильных экранов. + +#### Пограничный случай +Если установить `rows` в 1, библиотека генерирует одно‑строчный Databar (эквивалент стандартного Databar). Значения ниже 1 игнорируются и сбрасываются к значению по умолчанию (1 строка). + +### Шаг 7: Сохранить изображение штрих‑кода с макетом по строкам + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Снова **save barcode image** с использованием PNG, чтобы сохранить чёткость вывода. + +## Полный исполняемый пример + +Собрав все части вместе, вы получаете автономный скрипт, который можно добавить в любой проект на Python. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Ожидаемый результат** + +Запуск скрипта создаёт два PNG‑файла: + +* `output/ExpandedCols4.png` – штрих‑код, растянутый на четыре столбца +* `output/ExpandedRows3.png` – штрих‑код, сжатый в три строки + +Оба изображения можно открыть в любом просмотрщике или импортировать напрямую в PDF‑счета, шаблоны этикеток или веб‑страницы. + +## Часто задаваемые вопросы и устранение неполадок + +| Question | Answer | +|----------|--------| +| *Что делать, если штрих‑код выглядит размытым?* | Увеличьте разрешение изображения, задав `barcode_generator.parameters.image_width` и `image_height` перед вызовом `save`. | +| *Можно ли использовать другие форматы изображений?* | Да. При необходимости замените `BarCodeImageFormat.Png` на `Jpeg`, `Bmp` или `Gif`. | +| *Есть ли ограничение на длину данных?* | Databar Expanded Stacked поддерживает до 74 числовых символов. При превышении лимита генерируется `ArgumentException`. | +| *Как изменить цвет переднего плана?* | Используйте `barcode_generator.parameters.barcode.color = Color.Blue` (импортируйте `System.Drawing.Color`). | +| *Можно ли комбинировать столбцы и строки?* | Нет. API рассматривает столбцы и строки как взаимно исключающие режимы макета. Выбирайте один из них для каждого экземпляра штрих‑кода. | + +## Следующие шаги + +Теперь, когда вы умеете **настраивать макет штрих‑кода Databar**, рассмотрите изучение связанных тем: + +* **Добавить текстовые подписи** – используйте `barcode_generator.parameters.barcode.code_text` для отображения закодированного значения под изображением. +* **Встроить штрих‑код в PDF** – объедините сгенерированный PNG с `aspose.pdf` для создания печатных документов. +* **Динамический размер** – вычисляйте оптимальное количество столбцов или строк исходя из размеров этикетки во время выполнения. +* **Пакетная обработка** – пройдитесь по CSV с кодами продуктов, чтобы автоматически создать библиотеку изображений штрих‑кодов. + +Экспериментируйте с различными значениями столбцов и строк, чтобы увидеть, как они влияют на надёжность сканирования на ваших устройствах. Чем больше вы тестируете, тем лучше понимаете компромиссы между размером штрих‑кода, читаемостью и ограничениями пространства. + +--- + +*Счастливого кодинга! Если это руководство оказалось полезным, поделитесь им с коллегами или оставьте комментарий о проблемах с макетом, с которыми вы столкнулись.* + + +## Что изучать дальше? + + +В следующих руководствах рассматриваются тесно связанные темы, которые развивают техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Create barcode image c# – Configure Codablock F Rows & Columns](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [One-Dimensional Databar Barcode Height Adjustment](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/russian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/russian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..044292286 --- /dev/null +++ b/barcode/russian/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-08-12 +description: Создайте изображение штрихкода в C# с помощью BarCodeGenerator. Узнайте, + как генерировать DataBar, управлять размером изображения штрихкода и эффективно + создавать несколько штрихкодов. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: ru +lastmod: 2026-08-12 +og_description: Создайте изображение штрих‑кода в C# с помощью BarCodeGenerator. Этот + учебник пошагово показывает, как генерировать коды DataBar, регулировать размер + изображения штрих‑кода и создавать несколько штрих‑кодов. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Создание изображения штрихкода в C# – полное руководство по BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Создать изображение штрихкода в C# с помощью BarCodeGenerator +url: /ru/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание изображения штрих‑кода в C# с помощью BarCodeGenerator + +Если вам нужно **создать изображение штрих‑кода** в приложении .NET, это руководство покажет, как сделать это с помощью класса `BarCodeGenerator`. Независимо от того, разрабатываете ли вы POS‑систему для розничной торговли или инструмент учёта запасов, вы научитесь генерировать символы DataBar, управлять размером изображения штрих‑кода и создавать несколько штрих‑кодов за один запуск. + +Вы также узнаете, как API **barcode generator c#** позволяет настраивать размеры, переключать форматы вывода и обрабатывать граничные случаи, такие как недопустимые строки данных. К концу урока вы сможете уверенно **создавать несколько штрих‑кодов** без написания повторяющегося кода. + +## Требования + +Прежде чем начать, убедитесь, что у вас есть: + +- .NET 6.0 или новее +- Среда разработки (Visual Studio, Rider или VS Code) +- NuGet‑пакет Aspose.BarCode for .NET (или любая совместимая библиотека, предоставляющая `BarCodeGenerator`) + +Пакет можно добавить с помощью: + +```bash +dotnet add package Aspose.BarCode +``` + +## Что покрывает это руководство + +1. Создание экземпляра **barcode generator c#** для кодирования DataBar Omni‑directional. +2. Регулировка **barcode image size** путём изменения X‑dimension и высоты штрихов. +3. Использование цикла для **создания нескольких штрих‑кодов** с разными высотами. +4. Сохранение изображений в формате PNG и проверка результата. + +Все фрагменты кода полностью готовы к копированию в новый консольный проект. + +![Create barcode image example](barcode-example.png){alt="Create barcode image example"} + +## Шаг 1: Инициализация генератора — основы создания изображения штрих‑кода + +Первый шаг — создать экземпляр `BarCodeGenerator` с нужной символьной системой. Для символа DataBar Omni‑directional используйте `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Почему это важно:** При создании генератора задаются правила кодирования и полезная нагрузка данных. Если указать неверное значение `EncodeTypes`, библиотека сгенерирует неподдерживаемый штрих‑код или выбросит исключение. + +## Шаг 2: Настройка X‑dimension и высоты штриха — контроль размера изображения штрих‑кода + +Визуальный размер штрих‑кода определяется двумя параметрами: + +| Параметр | Что контролирует | Типичный диапазон | +|------------------------|-----------------------------------------------|-------------------| +| `x_dimension.pixels` | Ширина самого маленького модуля («точки») | 1 – 4 px | +| `bar_height.pixels` | Высота вертикальных штрихов | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Совет:** Меньшее значение X‑dimension даёт изображение более высокого разрешения, но может быть труднее считать на принтерах низкого качества. Подбирайте значение в зависимости от оборудования сканирования. + +## Шаг 3: Сохранение первого штрих‑кода — создание изображения штрих‑кода высотой 30 px + +Теперь можно сгенерировать изображение и записать его на диск. Метод `Save` принимает путь к файлу и перечисление формата изображения. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Ожидаемый результат:** В папке `C:\Barcodes` появляется PNG‑файл `Databar30.png`. При открытии файла отображается символ DataBar Omni‑directional с чётким, контрастным узором. + +## Шаг 4: Изменение высоты и генерация дополнительных изображений — создание нескольких штрих‑кодов + +Чтобы **создать несколько штрих‑кодов** с разными размерами, достаточно изменить свойство `BarHeight` и снова вызвать `Save`. Это избавляет от повторного создания генератора, экономя память и процессорное время. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Почему это работает:** Объект `BarCodeGenerator` хранит всё состояние конфигурации. Изменение одного свойства обновляет движок рендеринга для следующего вызова `Save`, позволяя **создавать несколько штрих‑кодов** эффективно. + +## Шаг 5: Продвинутое использование — генерация DataBar с пользовательскими данными + +В примере выше используется статический GS1‑payload. В реальных сценариях часто требуется внедрять переменные идентификаторы продукта. Библиотека принимает любую строку, соответствующую спецификации DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Ключевой момент:** Установка `generator.CodeText` обновляет закодированные данные без пересоздания объекта. Это рекомендуемый шаблон **how to generate databar** при работе с большими наборами данных. + +## Шаг 6: Проверка и отладка — обеспечение правильного размера изображения штрих‑кода + +После генерации изображений вы можете программно убедиться, что их размеры соответствуют ожиданиям. Класс `Image` из `System.Drawing` может прочитать файл и сообщить его размеры. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Если высота не соответствует заданному значению, проверьте: + +- **X‑dimension**: Очень маленькое значение может привести к округлению высоты рендерером. +- **Формат изображения**: Некоторые форматы (например, JPEG) применяют сжатие, которое может изменить пиксельные размеры при сохранении. PNG сохраняет точные размеры. + +## Шаг 7: Лучшие практики для размера изображения штрих‑кода и производительности + +| Рекомендация | Причина | +|---------------------------------------------------------------|---------| +| Держите `x_dimension.pixels` в диапазоне 2 – 3 px для большинства сканеров. | Баланс читаемости и размера файла. | +| Используйте PNG для безпотерьного вывода, когда изображение будет печататься. | Гарантирует точные размеры и чёткие края. | +| Переиспользуйте один экземпляр `BarCodeGenerator` при генерации множества штрих‑кодов. | Снижает накладные расходы на создание объектов. | +| Валидируйте входную строку согласно стандарту GS1 перед присвоением `CodeText`. | Предотвращает исключения во время выполнения и некорректные сканы. | +| Храните сгенерированные изображения в отдельной папке с понятным именованием (например, `Databar_{GTIN}.png`). | Упрощает последующую обработку и аудит. | + +## Полный рабочий пример + +Ниже представлена полная программа, включающая все шаги от инициализации до проверки. Скопируйте код в новый консольный проект и запустите его. + + + +## Что следует изучить дальше? + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы в собственных проектах. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/russian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/russian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..8f0860067 --- /dev/null +++ b/barcode/russian/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-08-12 +description: Создайте омни‑направленный Databar с помощью Python и узнайте, как создать + изображение штрих‑кода в Python, используя Aspose.BarCode. Следуйте пошаговому руководству + для получения полного решения. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: ru +lastmod: 2026-08-12 +og_description: Создайте омнинаправленный Databar с помощью Python и за несколько + минут сгенерируйте изображение штрихкода. Этот учебник демонстрирует полный, готовый + к запуску пример. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Создайте омни‑направленный датабар – полное руководство по Python +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Создайте всенаправленный DataBar и изображение штрихкода в Python +url: /ru/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание omni directional databar и изображения штрихкода в Python + +Если вам нужно **создать omni directional databar** в проекте на Python, это руководство покажет, как это сделать, а также как **создать изображение штрихкода в Python** с использованием библиотеки Aspose.BarCode. Вы получите готовый к запуску скрипт, который генерирует два PNG‑файла с разными соотношениями сторон. + +Генерация DataBar, соответствующего спецификации Omni‑directional, является распространённым требованием для розничных и логистических приложений. В руководстве рассматриваются установка, настройка X‑размера, корректировка соотношения сторон и сохранение окончательных изображений. Внешние сервисы не требуются; всё работает локально. + +## Что вам понадобится + +* Python 3.8 или новее, установленный на вашем компьютере. +* Доступ к терминалу или командной строке. +* Права записи в папку, где будут сохраняться изображения штрихкода. + +Единственная сторонняя зависимость — **Aspose.BarCode for Python via .NET**, который из коробки поддерживает тип Omni‑directional DataBar. + +## Шаг 1: Установите Aspose.BarCode для Python + +Aspose.BarCode предоставляет класс `BarcodeGenerator`, используемый в примере кода. Установите пакет с помощью `pip`: + +```bash +pip install aspose-barcode +``` + +Пакет включает необходимые привязки к .NET‑runtime, поэтому отдельная установка .NET SDK не требуется. + +## Шаг 2: Импортируйте библиотеку и создайте генератор + +Первая строка скрипта создаёт генератор для stacked Omni‑directional DataBar. В качестве примерных данных используется значение GTIN‑14 `(01)12345678901231`. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Почему этот шаг важен*: Константа `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` указывает библиотеке кодировать значение как Omni‑directional DataBar, формат, требуемый многими сканерами точек продаж. + +## Шаг 3: Установите X‑dimension (ширина модуля) + +X‑dimension определяет ширину самого маленького бар‑модуля. Значение `2` пикселя даёт чёткий, читаемый штрихкод без избыточного размера файла. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Почему этот шаг важен*: Регулировка X‑dimension позволяет сбалансировать читаемость и размеры изображения. Слишком маленькая X‑dimension может плохо отображаться на принтерах с низким разрешением. + +## Шаг 4: Настройте соотношение сторон и сохраните первое изображение + +Соотношение сторон влияет на общую высоту DataBar относительно его ширины. Соотношение `15` создаёт компактный визуальный стиль. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Pro tip**: Используйте `pathlib.Path` для построения пути вывода — он автоматически создаёт недостающие каталоги. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Шаг 5: Измените соотношение сторон для второго визуального стиля и сохраните другое изображение + +Переключение соотношения сторон на `30` даёт более высокий штрихкод, который может потребоваться определённому сканирующему оборудованию. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Почему этот шаг важен*: Разные розничные сети и сканеры имеют свои ограничения по размеру. Предоставление обоих соотношений в одном скрипте позволяет генерировать нужный стиль без дублирования кода. + +## Полный скрипт – создание omni directional databar и изображения штрихкода в Python + +Ниже приведён полностью готовый к запуску пример, включающий все предыдущие шаги. Сохраните его как `generate_databar.py` и запустите командой `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Ожидаемый результат + +Запуск скрипта создаёт следующие файлы: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Оба изображения отображают корректный Omni‑directional DataBar, который может быть считан стандартным розничным оборудованием. + +![пример создания omni directional databar и изображения штрихкода в Python](example_databar.png "создание omni directional databar и изображения штрихкода python") + +*Изображение выше является заглушкой, иллюстрирующей два сохранённых PNG‑файла.* + +## Решение распространённых проблем + +| Проблема | Причина | Решение | +|----------|---------|---------| +| `ImportError: No module named aspose` | Aspose.BarCode не установлен или установлен в другой среде. | Активируйте правильное виртуальное окружение и выполните `pip install aspose-barcode`. | +| `PermissionError` при сохранении | Скрипт не имеет прав записи в целевую папку. | Выберите каталог, к которому у вас есть доступ, или запустите скрипт с соответствующими привилегиями. | +| Штрихкод не считывается | X‑dimension слишком мала или соотношение сторон несовместимо со сканером. | Увеличьте `x_dimension.pixels` до 3 или 4 и протестируйте разные значения `aspect_ratio` (например, 20, 25). | +| Отсутствует .NET runtime | Aspose.BarCode зависит от .NET runtime на Windows/Linux. | Установите последнюю версию .NET runtime с сайта Microsoft; в документации пакета есть рекомендации для разных платформ. | + +## Расширение примера + +Вы можете адаптировать скрипт для генерации других вариантов DataBar (например, `DATABAR_STACKED`, `DATABAR_EXPANDED`). Замените соответствующую константу `EncodeTypes`. + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Если необходимо встроить штрихкод в PDF, Aspose.PDF for Python может напрямую импортировать PNG‑файл, либо можно воспользоваться методом `save` с параметром `BarCodeImageFormat.Pdf`. + +## Заключение + +В этом руководстве показано, как **создать omni directional databar** и как **создать изображение штрихкода в Python** с помощью Aspose.BarCode. Теперь у вас есть полностью воспроизводимый скрипт, генерирующий два PNG‑файла с разными соотношениями сторон, учитывающий типичные подводные камни и готовый к расширению под другие форматы штрихкодов. + +Далее изучайте генерацию QR‑кодов, добавление штрихкода в PDF‑счета или автоматизацию пакетной обработки больших каталогов товаров. Все эти темы опираются на тот же шаблон `BarcodeGenerator`, продемонстрированный здесь. Приятного кодинга! + +## Что следует изучить дальше? + +Следующие руководства охватывают смежные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс содержит полностью работающие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Генерация изображения штрихкода – GS1 Coupon UPC‑A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Создание изображения штрихкода DotCode – строки и столбцы (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Как создать изображение штрихкода и отобразить его в Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/russian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/russian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..bd85d07c1 --- /dev/null +++ b/barcode/russian/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-08-12 +description: Как быстро генерировать штрих‑код с помощью Python. Узнайте, как создать + штрих‑код из данных и экспортировать изображение штрих‑кода с помощью одной библиотеки. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: ru +lastmod: 2026-08-12 +og_description: Как генерировать штрих‑код в Python с помощью Aspose.BarCode. Следуйте + этому руководству, чтобы создать штрих‑код из данных и экспортировать изображение + штрих‑кода в формате PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Как генерировать штрих‑код в Python — быстрый, надёжный гид +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Как сгенерировать штрих‑код в Python — полное пошаговое руководство +url: /ru/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как генерировать штрих‑код в Python – полное пошаговое руководство + +Если вам нужно **how to generate barcode** в приложении на Python, этот учебник покажет точный код, который вам нужен. Вы научитесь **create barcode from data**, настраивать его внешний вид и **export barcode image** в виде PNG‑файла — всё это менее чем в десяти строках кода. + +Создание штрих‑кода может казаться отдельной задачей от остальной бизнес‑логики, но с помощью одной библиотеки вы можете интегрировать процесс в ваш существующий код. В последующих разделах вы увидите полностью рабочий пример, поймёте, почему важна каждая строка, и узнаете о распространённых вариациях, таких как изменение ширины модуля или отрисовка штрих‑кода только с контурами. + +## Как генерировать штрих‑код с библиотекой Aspose.BarCode + +Библиотека Aspose.BarCode для Python (через .NET) предоставляет простой API для множества символогий, включая штрих‑код Planet, используемый в этом руководстве. Прежде чем начать, убедитесь, что пакет установлен: + +```bash +pip install aspose-barcode +``` + +> **Pro tip:** Используйте виртуальное окружение, чтобы избежать конфликтов версий с другими проектами. + +### 1. Импортировать необходимые классы + +Эти импорты дают вам доступ к классу генератора, перечислению типов штрих‑кодов и перечислению форматов изображений, используемых при сохранении результата. + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +### 2. Создать штрих‑код из данных + +Первый шаг — **create barcode from data**. Конструктор `BarcodeGenerator` принимает символогию и исходную строку, которую нужно закодировать. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +Значение `EncodeTypes.Planet` выбирает штрих‑код Planet, а `"123456"` — это полезные данные, которые появятся в конечном изображении. + +### 3. Настроить X‑dimension (ширина модуля) + +X‑dimension управляет шириной каждого модуля штрих‑кода (тонкой полосы). Установка значения в 4 пикселя даёт чёткое, читаемое изображение без излишнего увеличения размера файла. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Why this matters:** Большая X‑dimension повышает надёжность сканирования на принтерах с низким разрешением, а меньшее значение уменьшает размер файла для веб‑использования. + +### 4. Экспортировать изображение штрих‑кода (заполненный стиль) + +Теперь вы можете **export barcode image** с помощью метода `save`. В примере сохраняется PNG‑файл, но вы можете выбрать JPEG, BMP или TIFF, изменив перечисление `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +Файл `PlanetFilled.png` содержит полностью заполненный штрих‑код Planet, готовый к печати или встраиванию в PDF. + +### 5. Создать второй генератор для штрих‑кода только с контурами + +Если вам нужна версия с контурами (пустые полосы), необходимо создать новый генератор, поскольку флаг `filled_bars` нельзя изменить после сохранения изображения. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Применить тот же параметр X‑dimension + +При создании второго генератора необходимо повторить все визуальные настройки, которые вы хотите сохранить одинаковыми. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Отключить заполненные полосы для контурного штрих‑кода + +Установка `filled_bars` в `False` указывает рендереру рисовать только контуры каждого модуля, создавая более лёгкое изображение, полезное для дизайнерских целей. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Экспортировать контурное изображение штрих‑кода + +Наконец, **export barcode image** ещё раз, на этот раз сохраняя контурную версию. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Теперь у вас есть два PNG‑файла: один с сплошными полосами (`PlanetFilled.png`) и один только с контурами (`PlanetEmpty.png`). + +## Экспортировать изображение штрих‑кода в других форматах (необязательно) + +Метод `save` поддерживает несколько форматов. Чтобы экспортировать в JPEG с качеством 90 %: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Если нужен прозрачный фон для веб‑использования, выберите PNG с альфа‑каналом: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Распространённые вариации и граничные случаи + +| Сценарий | Необходимое изменение | Фрагмент кода | +|----------|-----------------------|---------------| +| **Разная симвология** (например, QR) | Использовать другое значение `EncodeTypes` | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Custom foreground color** | Установить `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Более высокое разрешение** | Увеличить DPI через `image_width` и `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Большие строки данных** | Убедиться, что длина данных соответствует спецификации символогии | Validate length before creating the generator | + +> **Watch out for:** Предоставление данных, превышающих максимальную длину для выбранной символогии, вызывает исключение во время выполнения. Всегда проверяйте длину строки или перехватывайте `ArgumentException`. + +## Полный, исполняемый пример + +Ниже приведён полный скрипт, который вы можете скопировать и вставить в файл с именем `generate_planet_barcode.py`. Измените `YOUR_DIRECTORY`, указав путь к существующей на вашем компьютере папке. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Запуск этого скрипта создаст два PNG‑файла в указанной директории. Проверьте результат, открыв изображения в любом просмотрщике; оба должны отображать штрих‑код Planet, кодирующий строку `123456`. + +## Заключение + +Теперь вы знаете **how to generate barcode** в Python с использованием Aspose.BarCode, как **create barcode from data**, и как **export barcode image** как в заполненном, так и в контурном стиле. Та же схема применима к другим символогиям, форматам изображений и визуальным настройкам, предоставляя гибкую основу для любой функции, связанной со штрих‑кодами, в вашем приложении. + +### Следующие шаги + +* Изучить другие символогии, такие как QR, Code‑128 или DataMatrix, заменив `EncodeTypes.Planet` на нужное значение. +* Интегрировать сгенерированные PNG‑файлы в PDF‑отчёты с помощью библиотек, таких как `ReportLab` или `PyPDF2`. +* Экспериментировать с динамическими значениями X‑dimension, чтобы адаптировать размер штрих‑кода в зависимости от разрешения экрана или DPI принтера. + +Удачной разработки, и не стесняйтесь адаптировать пример под требования вашего проекта! + +## Что вам стоит изучить дальше? + +Следующие учебники охватывают тесно связанные темы, опирающиеся на техники, продемонстрированные в этом руководстве. Каждый ресурс содержит полностью рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/spanish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/spanish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..0a5e3395e --- /dev/null +++ b/barcode/spanish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,297 @@ +--- +category: general +date: 2026-08-12 +description: Ejemplo de generador de códigos de barras que muestra cómo generar códigos + de barras con un tamaño de píxel preciso. Aprende a establecer el ancho del módulo, + la altura de la barra y crear códigos de barras Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: es +lastmod: 2026-08-12 +og_description: El ejemplo del generador de códigos de barras muestra cómo generar + un código de barras con dimensiones de píxeles exactas. Sigue esta guía para controlar + el ancho del módulo y la altura de la barra para los códigos Planet y RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: Ejemplo de generador de códigos de barras – personalizar tamaño de píxel + en C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Ejemplo de generador de códigos de barras – guía paso a paso para tamaños de + píxel personalizados +url: /es/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# barcode generator example – guía paso a paso para tamaños de píxel personalizados + +Si necesitas un **barcode generator example** que te permita controlar cada píxel, esta guía muestra exactamente cómo hacerlo. Aprenderás a establecer el ancho del módulo, definir una altura de barra fija y generar códigos de barras Planet y RM4SCC con dimensiones predecibles. + +La mayoría de los desarrolladores tienen problemas con imágenes de “cómo generar barcode” que se vean iguales en cada pantalla o impresora. Los fragmentos de código a continuación resuelven ese problema al exponer los parámetros a nivel de píxel de la biblioteca Aspose.BarCode for .NET, de modo que puedas producir una salida consistente sin conjeturas. + +## Lo que aprenderás + +* Cómo instalar el paquete NuGet requerido. +* Cómo generar un código de barras Planet con altura calculada automáticamente. +* Cómo generar un código de barras Planet con una altura explícita de 100 píxeles. +* Cómo generar un código de barras RM4SCC usando la misma altura explícita. +* Por qué **barcode pixel size** es importante para la fiabilidad del escaneo. +* Consejos para solucionar problemas comunes al generar imágenes de códigos de barras Planet. + +Solo necesitas .NET 6 o posterior, un entorno básico de desarrollo C# y una conexión a internet para obtener el paquete NuGet. + +--- + +## barcode generator example – configurar el entorno de desarrollo + +Antes de escribir cualquier código, asegúrate de que la biblioteca Aspose.BarCode esté disponible para tu proyecto. + +### Instalar el paquete Aspose.BarCode + +Abre una terminal en la carpeta de tu proyecto y ejecuta: + +```bash +dotnet add package Aspose.BarCode +``` + +El comando agrega la última versión estable de **Aspose.BarCode** a tu `csproj`. Después de que la restauración finalice, puedes comenzar a usar la clase `BarcodeGenerator`. + +> **Consejo profesional:** Apunta a .NET 6 o .NET 7 para beneficiarte de las últimas mejoras de rendimiento y del manejo predeterminado de UTF‑8. + +### Agregar las directivas `using` necesarias + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Estos espacios de nombres exponen la clase `BarcodeGenerator` y el enum `BarCodeImageFormat` que se utilizan más adelante en el tutorial. + +--- + +## Cómo generar un código de barras con tamaño de píxel personalizado + +Los siguientes tres pasos ilustran el **barcode generator example** completo. Cada paso se basa en el anterior, de modo que puedes copiar‑pegar todo el bloque en una aplicación de consola y ejecutarlo sin cambios. + +### Paso 1 – generar un código de barras Planet con altura calculada automáticamente + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Por qué funciona:** +*La propiedad `XDimension` define el ancho de un solo módulo del código de barras (el elemento negro o blanco más pequeño). Cuando omites `BarHeight`, la biblioteca calcula una altura que mantiene la relación de aspecto estándar para los códigos Planet.* + +**Salida esperada:** Un archivo PNG llamado `PlanetAuto.png` que contiene un código de barras Planet limpio. Su altura se adapta al ancho de módulo de 4 píxeles, típicamente alrededor de 60 píxeles para una carga útil de seis caracteres. + +### Paso 2 – generar un código de barras Planet con una altura explícita de 100 píxeles + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Por qué podrías necesitar esto:** +A veces el equipo de escaneo espera una altura mínima de barra para una detección fiable. Al establecer `BarHeight.Pixels`, garantizas que cada imagen generada cumpla con ese requisito, sin importar la longitud de los datos codificados. + +**Salida esperada:** `PlanetHeight100.png` muestra los mismos datos que antes, pero las barras tienen exactamente 100 píxeles de altura, dándote control total sobre el tamaño visual. + +### Paso 3 – generar un código de barras RM4SCC con la misma altura explícita + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Por qué es importante:** +`EncodeTypes.RM4SCC` es un código de barras lineal apilado usado en logística. Alinear su altura de barra con el código Planet simplifica el procesamiento por lotes cuando ambas simbologías aparecen en la misma etiqueta. + +**Salida esperada:** `RM4SCCHeight100.png` muestra un código de barras RM4SCC perfectamente dimensionado, coincidiendo con la altura de 100 píxeles que estableciste para el código Planet. + +> **Verificación del resultado:** Abre cada PNG en un visor de imágenes y confirma que las barras negras tienen exactamente 4 píxeles de ancho y, donde lo especificaste, 100 píxeles de alto. También puedes pasar los archivos a una aplicación de escáner de códigos de barras para asegurarte de que decodifiquen “123456”. + +--- + +## Comprender el tamaño de píxel del código de barras y la altura de la barra + +### ¿Qué es **barcode pixel size**? + +*Pixel size* se refiere al número físico de píxeles de pantalla o impresora que representan un solo módulo (`XDimension`). Un tamaño de píxel mayor produce un código de barras más grande, lo que puede ser más fácil para escáneres de baja resolución pero consume más espacio en la etiqueta. + +### ¿Cómo afecta `BarHeight` a la legibilidad? + +La propiedad `BarHeight` controla la longitud vertical de las barras. Las normas para la mayoría de los códigos de barras 1‑D (incluidos Planet y RM4SCC) recomiendan una altura mínima de 10 mm cuando se imprimen a 300 dpi, lo que equivale a aproximadamente 118 píxeles. Establecer una altura inferior puede provocar errores de lectura, especialmente en cámaras móviles. + +### ¿Cuándo deberías dejar que la biblioteca calcule la altura automáticamente? + +Si estás generando códigos de barras solo para visualización en pantalla, el cálculo automático mantiene la relación de aspecto consistente y reduce la cantidad de ajustes manuales necesarios. Para etiquetas impresas que deben cumplir especificaciones ISO estrictas, deberías **establecer explícitamente la altura de la barra**. + +--- + +## Errores comunes y buenas prácticas al generar códigos de barras Planet + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| Barra aparece demasiado delgada o gruesa | `XDimension` left at default (1 pixel) on high‑resolution displays | Establecer `XDimension.Pixels` a al menos 3‑4 para claridad visual | +| El escáner no puede leer el código | `BarHeight` es demasiado pequeño para la distancia focal del escáner | Usar `BarHeight.Pixels` ≥ 100 para la mayoría de escáneres móviles | +| La imagen está borrosa después de escalar | Saving as JPEG introduces compression artifacts | Guardar como PNG (`BarCodeImageFormat.Png`) para salida sin pérdidas | +| Tipo de código de barras inesperado | Wrong `EncodeTypes` enum value | Verificar que estés usando `EncodeTypes.Planet` para la simbología Planet | + +### Consejo profesional sobre rendimiento + +Al generar miles de códigos de barras en un trabajo por lotes, reutiliza una única instancia de `BarcodeGenerator` y solo cambia los parámetros `CodeText` y de tamaño entre guardados. Esto evita la asignación repetida de objetos internos de renderizado y puede reducir el tiempo de ejecución hasta en un 30 %. + +--- + +## Ejemplo completo funcionando – juntar todo + +Crea un nuevo proyecto de consola (`dotnet new console -n BarcodeDemo`) y reemplaza el contenido de `Program.cs` con lo siguiente: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Ejecuta el programa con `dotnet run`. Después de la ejecución encontrarás tres archivos PNG en la carpeta del proyecto, cada uno ilustrando un escenario diferente del **barcode generator example**. + +--- + +## Próximos pasos y temas relacionados + +* **Cómo generar códigos de barras en otros formatos** – explora `EncodeTypes.Code128`, `EncodeTypes.QR` y `EncodeTypes.DataMatrix` para necesidades 2‑D. +* **Incorporar códigos de barras en PDFs** – combina Aspose.BarCode con Aspose.PDF para colocar códigos de barras directamente en plantillas de facturas. +* **Tamaño dinámico de código de barras basado en la entrada del usuario** – calcular + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo generar código de barras java: Crear una imagen de código exacta](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [Cómo generar código de barras en Java Crear y establecer tamaño para la imagen completa](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [Cómo crear código de barras code128 en Java y establecer altura de barra](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/spanish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/spanish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..d59f3e72b --- /dev/null +++ b/barcode/spanish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Configura rápidamente el diseño de códigos de barras Databar en Python. + Aprende a establecer columnas, filas y guardar imágenes con la biblioteca generadora + de códigos de barras. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: es +lastmod: 2026-08-12 +og_description: Configura el diseño del código de barras Databar en Python para controlar + columnas, filas y la salida de imagen. Sigue esta guía para obtener una solución + lista para ejecutar. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Configura el diseño del código de barras Databar en Python – tutorial completo +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Configura el diseño del código de barras Databar en Python – guía paso a paso +url: /es/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Configurar el diseño del código de barras Databar en Python – guía paso a paso + +Si necesitas **configurar el diseño del código de barras Databar en Python**, esta guía te lleva a través de todo el proceso. Verás cómo establecer el número de columnas o filas para un código de barras Databar Expanded Stacked y cómo guardar la imagen resultante con una única llamada a la biblioteca generadora de códigos de barras. + +Controlar el diseño es esencial cuando incrustas códigos de barras en empaques estrechos, recibos o pantallas móviles. En las secciones siguientes cubriremos las importaciones requeridas, las dos opciones de diseño (columnas y filas) y las mejores prácticas para guardar una imagen PNG limpia. + +## Lo que necesitarás + +* Python 3.8 o superior +* `aspose.barcode` (o cualquier paquete compatible de generación de códigos de barras) instalado + ```bash + pip install aspose-barcode + ``` +* Permiso de escritura en una carpeta donde se almacenarán los archivos PNG + +No se requieren herramientas externas adicionales: la biblioteca maneja el renderizado, el escalado y la codificación de la imagen internamente. + +## Cómo configurar el diseño del código de barras Databar en Python + +El núcleo de la solución es la clase `BarcodeGenerator`. Acepta un enum `EncodeTypes` que identifica la simbología del código de barras—en este caso `EncodeTypes.DatabarExpandedStacked`. Después de crear el generador puedes ajustar el diseño estableciendo las propiedades `columns` o `rows` en el objeto de parámetro `data_bar`. + +### Paso 1: Importar las clases requeridas + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Estas importaciones te dan acceso al generador, a la enumeración para los tipos Databar y a la constante de formato de imagen PNG. + +### Paso 2: Crear un generador de códigos de barras para Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*¿Por qué este paso?* +`EncodeTypes.DatabarExpandedStacked` indica a la biblioteca que produzca la simbología **Databar Expanded Stacked**, que admite cadenas numéricas más largas manteniendo una huella compacta. El segundo argumento es el dato a codificar; puede ser cualquier cadena que cumpla con la especificación Databar. + +### Paso 3: Establecer el número de columnas (diseño horizontal) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** es la frase clave para esta operación. Cuando aumentas el recuento de columnas, el código de barras se extiende horizontalmente, lo que puede ser útil para etiquetas anchas. La biblioteca recalcula automáticamente el ancho del módulo para mantener el tamaño total consistente. + +#### Consejo profesional +El recuento máximo de columnas para Databar Expanded Stacked es 8. Establecer un valor superior al límite lo limitará al máximo, pero es mejor validar tu entrada de antemano. + +### Paso 4: Guardar la imagen del código de barras con el diseño de columnas + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** es la acción que escribe el código de barras renderizado en disco. PNG es sin pérdida, lo que preserva los bordes nítidos requeridos para un escaneo fiable. + +### Paso 5: Crear un segundo generador para el mismo tipo de código de barras (diseño de filas) + +Si prefieres una pila vertical, trabajas con filas en lugar de columnas. El código a continuación reutiliza el mismo valor pero crea una nueva instancia de `BarcodeGenerator` para evitar mezclar configuraciones de columnas y filas. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Paso 6: Establecer el número de filas (diseño vertical) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** organiza los módulos del código de barras verticalmente. Un diseño de tres filas reduce la altura de cada pila individual, haciendo que el código de barras sea adecuado para recibos estrechos o pantallas móviles. + +#### Caso límite +Si estableces `rows` en 1, la biblioteca genera un Databar de una sola fila (equivalente a un Databar estándar). Los valores por debajo de 1 se ignoran y se restablecen al valor predeterminado (1 fila). + +### Paso 7: Guardar la imagen del código de barras con el diseño de filas + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Nuevamente, **save barcode image** usando PNG para mantener la salida nítida. + +## Ejemplo completo ejecutable + +Unir todas las piezas te brinda un script autónomo que puedes incorporar a cualquier proyecto Python. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Salida esperada** + +Ejecutar el script crea dos archivos PNG: + +* `output/ExpandedCols4.png` – un código de barras extendido a través de cuatro columnas +* `output/ExpandedRows3.png` – un código de barras comprimido en tres filas + +Ambas imágenes pueden abrirse en cualquier visor de imágenes o importarse directamente en facturas PDF, plantillas de etiquetas o páginas web. + +## Preguntas frecuentes y solución de problemas + +| Question | Answer | +|----------|--------| +| *What if the barcode looks blurry?* | Increase the image resolution by setting `barcode_generator.parameters.image_width` and `image_height` before calling `save`. | +| *Can I use other image formats?* | Yes. Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. | +| *Is there a limit on the data length?* | Databar Expanded Stacked supports up to 74 numeric characters. Exceeding the limit raises a `ArgumentException`. | +| *How do I change the foreground color?* | Use `barcode_generator.parameters.barcode.color = Color.Blue` (import `System.Drawing.Color`). | +| *Can I combine columns and rows?* | No. The API treats columns and rows as mutually exclusive layout modes. Choose one per barcode instance. | + +## Próximos pasos + +Ahora que puedes **configure Databar barcode layout**, considera explorar estos temas relacionados: + +* **Add text captions** – use `barcode_generator.parameters.barcode.code_text` to display the encoded value beneath the image. +* **Embed the barcode in a PDF** – combine the generated PNG with `aspose.pdf` to create printable documents. +* **Dynamic sizing** – calculate optimal column or row counts based on label dimensions at runtime. +* **Batch processing** – loop over a CSV of product codes to generate a library of barcode images automatically. + +Experimenta con diferentes valores de columnas y filas para ver cómo afectan la fiabilidad del escaneo en tus dispositivos objetivo. Cuanto más pruebes, mejor comprenderás los compromisos entre el tamaño del código de barras, la legibilidad y las limitaciones de espacio. + +--- + +*¡Feliz codificación! Si encontraste útil este tutorial, compártelo con tus compañeros o deja un comentario sobre los desafíos de diseño que enfrentaste.* + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Crear imagen de código de barras DotCode – filas y columnas (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Crear imagen de código de barras c# – Configurar filas y columnas de Codablock F](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [Ajuste de altura del código de barras Databar unidimensional](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/spanish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/spanish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..0538c790f --- /dev/null +++ b/barcode/spanish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-08-12 +description: Crear imagen de código de barras en C# usando BarCodeGenerator. Aprende + a generar DataBar, controlar el tamaño de la imagen del código de barras y crear + múltiples códigos de barras de forma eficiente. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: es +lastmod: 2026-08-12 +og_description: Crea una imagen de código de barras en C# con BarCodeGenerator. Este + tutorial muestra paso a paso cómo generar códigos DataBar, ajustar el tamaño de + la imagen del código de barras y producir múltiples códigos de barras. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Crear imagen de código de barras en C# – guía completa de BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Crear imagen de código de barras en C# con BarCodeGenerator +url: /es/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear imagen de código de barras en C# con BarCodeGenerator + +Si necesitas **crear una imagen de código de barras** en una aplicación .NET, esta guía te muestra exactamente cómo hacerlo con la clase `BarCodeGenerator`. Ya sea que estés construyendo un sistema POS minorista o una herramienta de seguimiento de inventario, aprenderás a generar símbolos DataBar, controlar el tamaño de la imagen del código de barras y producir varios códigos de barras en una sola ejecución. + +También descubrirás cómo la API **barcode generator c#** te permite ajustar dimensiones, cambiar formatos de salida y manejar casos límite como cadenas de datos inválidas. Al final del tutorial podrás **crear múltiples códigos de barras** con confianza sin escribir código repetitivo. + +## Requisitos previos + +Antes de comenzar, asegúrate de tener: + +- .NET 6.0 o posterior instalado +- Un entorno de desarrollo (Visual Studio, Rider o VS Code) +- El paquete NuGet Aspose.BarCode for .NET (o cualquier biblioteca compatible que proporcione `BarCodeGenerator`) + +Puedes agregar el paquete con: + +```bash +dotnet add package Aspose.BarCode +``` + +## Qué cubre este tutorial + +1. Configurar una instancia de **barcode generator c#** para la codificación DataBar Omni‑directional. +2. Ajustar el **barcode image size** cambiando la X‑dimension y la altura de la barra. +3. Usar un bucle para **create multiple barcodes** con diferentes alturas. +4. Guardar las imágenes como archivos PNG y verificar la salida. + +Todas las fragmentos de código están completos y listos para copiar y pegar en un nuevo proyecto de consola. + +![Ejemplo de creación de imagen de código de barras](barcode-example.png){alt="Ejemplo de creación de imagen de código de barras"} + +## Paso 1: Inicializar el generador – conceptos básicos de creación de imagen de código de barras + +El primer paso es instanciar `BarCodeGenerator` con la simbología deseada. Para un símbolo DataBar Omni‑directional utilizas `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Por qué es importante:** Instanciar el generador define las reglas de codificación y la carga de datos. Si omites el valor correcto de `EncodeTypes`, la biblioteca producirá un código de barras no compatible o lanzará una excepción. + +## Paso 2: Configurar X‑dimension y altura de la barra – controlar el tamaño de la imagen del código de barras + +El tamaño visual de un código de barras está determinado por dos parámetros: + +| Parámetro | Qué controla | Rango típico | +|-----------|--------------|--------------| +| `x_dimension.pixels` | Ancho del módulo más pequeño (el “punto”) | 1 – 4 px | +| `bar_height.pixels` | Altura de las barras verticales | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Consejo profesional:** Una X‑dimension más pequeña produce una imagen de mayor resolución pero puede ser más difícil de escanear en impresoras de baja calidad. Ajusta el valor según el equipo de escaneo objetivo. + +## Paso 3: Guardar el primer código de barras – crear imagen de código de barras para altura de 30 px + +Ahora puedes generar la imagen y escribirla en disco. El método `Save` acepta una ruta de archivo y un enum de formato de imagen. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Resultado esperado:** Aparece un archivo PNG llamado `Databar30.png` en `C:\Barcodes`. Al abrir el archivo se muestra un símbolo DataBar Omni‑directional con un patrón claro y de alto contraste. + +## Paso 4: Cambiar la altura y generar imágenes adicionales – crear múltiples códigos de barras + +Para **create multiple barcodes** con diferentes dimensiones solo necesitas modificar la propiedad `BarHeight` y llamar a `Save` nuevamente. Esto evita volver a instanciar el generador, lo que ahorra memoria y tiempo de CPU. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Por qué funciona:** El objeto `BarCodeGenerator` mantiene todo el estado de configuración. Cambiar una sola propiedad actualiza el motor de renderizado para la siguiente llamada a `Save`, permitiéndote **create multiple barcodes** de manera eficiente. + +## Paso 5: Avanzado – cómo generar DataBar con datos personalizados + +El ejemplo anterior usa una carga útil GS1 estática. En escenarios del mundo real a menudo necesitas incrustar identificadores de producto variables. La biblioteca acepta cualquier cadena que coincida con la especificación DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Punto clave:** Establecer `generator.CodeText` actualiza los datos codificados sin recrear el objeto. Este es el patrón recomendado de **how to generate databar** al manejar grandes conjuntos de datos. + +## Paso 6: Verificar y solucionar problemas – asegurando el tamaño correcto de la imagen del código de barras + +Después de generar las imágenes, puede que quieras confirmar programáticamente que las dimensiones coinciden con tus expectativas. La clase `Image` de `System.Drawing` puede leer el archivo y reportar su tamaño. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Si la altura no refleja el valor que estableciste, verifica: + +- **X‑dimension**: Un valor muy pequeño puede hacer que el renderizador redondee la altura. +- **Image format**: Algunos formatos (p.ej., JPEG) aplican compresión que puede alterar las dimensiones de píxeles al guardar. PNG conserva las dimensiones exactas. + +## Paso 7: Mejores prácticas para el tamaño de la imagen del código de barras y el rendimiento + +| Recomendación | Razón | +|----------------|--------| +| Mantener `x_dimension.pixels` entre 2 – 3 px para la mayoría de los escáneres. | Equilibra legibilidad y tamaño de archivo. | +| Usar PNG para salida sin pérdida cuando la imagen será impresa. | Garantiza dimensiones exactas y bordes nítidos. | +| Reutilizar una única instancia de `BarCodeGenerator` al generar muchos códigos de barras. | Reduce la sobrecarga de asignación de objetos. | +| Validar la cadena de entrada contra el estándar GS1 antes de asignarla a `CodeText`. | Previene excepciones en tiempo de ejecución y escaneos inválidos. | +| Almacenar las imágenes generadas en una carpeta dedicada con una convención de nombres clara (p.ej., `Databar_{GTIN}.png`). | Simplifica el procesamiento posterior y los registros de auditoría. | + +## Ejemplo completo en funcionamiento + +A continuación se muestra el programa completo que incorpora todos los pasos desde la inicialización hasta la verificación. Copia el código en un nuevo proyecto de consola y ejecútalo. + + + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Generar imagen de código de barras – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Crear imagen de código de barras DotCode – filas y columnas (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Cómo crear zona silenciosa de código de barras para ITF-14 usando Aspose.BarCode para .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/spanish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/spanish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..4e7882ae3 --- /dev/null +++ b/barcode/spanish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-12 +description: Crea un databar omnidireccional con Python y aprende cómo generar una + imagen de código de barras en Python usando Aspose.BarCode. Sigue la guía paso a + paso para obtener una solución completa. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: es +lastmod: 2026-08-12 +og_description: Crea un databar omnidireccional con Python y genera una imagen de + código de barras en minutos. Este tutorial muestra un ejemplo completo y ejecutable. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Crea una barra de datos omnidireccional – guía completa de Python +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Crear una imagen de databar omnidireccional y código de barras en Python +url: /es/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear databar omnidireccional e imagen de código de barras en Python + +Si necesitas **crear databar omnidireccional** en un proyecto Python, esta guía te muestra cómo hacerlo y también cómo **crear imagen de código de barras python** usando la biblioteca Aspose.BarCode. Obtendrás un script listo‑para‑ejecutar que produce dos archivos PNG con diferentes relaciones de aspecto. + +Generar un DataBar que siga la especificación omnidireccional es un requisito común para aplicaciones de retail y logística. El tutorial cubre la instalación, configuración de la dimensión X, ajuste de la relación de aspecto y guardado de las imágenes finales. No se requieren servicios externos; todo se ejecuta localmente. + +## Lo que necesitarás + +Antes de comenzar, asegúrate de tener: + +* Python 3.8 o superior instalado en tu máquina. +* Acceso a una terminal o símbolo del sistema. +* Permiso de escritura en una carpeta donde se guardarán las imágenes del código de barras. + +La única dependencia de terceros es **Aspose.BarCode for Python via .NET**, que soporta el tipo DataBar omnidireccional de forma nativa. + +## Paso 1: Instalar Aspose.BarCode para Python + +Aspose.BarCode proporciona la clase `BarcodeGenerator` usada en el código de ejemplo. Instala el paquete con `pip`: + +```bash +pip install aspose-barcode +``` + +El paquete incluye los enlaces necesarios al runtime de .NET, por lo que no necesitas instalar el SDK de .NET por separado. + +## Paso 2: Importar la biblioteca y crear el generador + +La primera línea del script crea un generador para un DataBar omnidireccional apilado. El valor GTIN‑14 `(01)12345678901231` se usa como dato de muestra. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Por qué este paso es importante*: La constante `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` indica a la biblioteca que codifique el valor como un DataBar omnidireccional, que es el formato requerido por muchos escáneres de punto de venta. + +## Paso 3: Establecer la dimensión X (ancho del módulo) + +La dimensión X define el ancho del módulo de barra más pequeño. Un valor de `2` píxeles produce un código de barras claro y legible sin un tamaño de archivo excesivo. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Por qué este paso es importante*: Ajustar la dimensión X te permite equilibrar la legibilidad y las dimensiones de la imagen. Una dimensión X demasiado pequeña puede renderizarse pobremente en impresoras de baja resolución. + +## Paso 4: Configurar la relación de aspecto y guardar la primera imagen + +La relación de aspecto influye en la altura total del DataBar respecto a su ancho. Una relación de aspecto de `15` crea un estilo visual compacto. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Consejo profesional**: Usa `pathlib.Path` para construir la ruta de salida, lo que crea automáticamente los directorios faltantes. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Paso 5: Cambiar la relación de aspecto para un segundo estilo visual y guardar otra imagen + +Cambiar la relación de aspecto a `30` produce un código de barras más alto que puede ser requerido por hardware de escáner específico. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Por qué este paso es importante*: Diferentes minoristas y dispositivos de escaneo tienen restricciones de tamaño distintas. Proveer ambas relaciones de aspecto en un solo script te permite generar el estilo exacto que necesitas sin duplicar código. + +## Script completo – crear databar omnidireccional e imagen de código de barras python + +A continuación se muestra el ejemplo completo y ejecutable que incorpora todos los pasos anteriores. Guárdalo como `generate_databar.py` y ejecútalo con `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Salida esperada + +Ejecutar el script crea los siguientes archivos: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Ambas imágenes muestran un DataBar omnidireccional válido que puede ser escaneado por equipos de retail estándar. + +![ejemplo de crear databar omnidireccional imagen de código de barras en Python](example_databar.png "crear databar omnidireccional imagen de código de barras python") + +*La imagen anterior es un marcador de posición que ilustra los dos archivos PNG guardados.* + +## Resolución de problemas comunes + +| Problema | Razón | Solución | +|----------|-------|----------| +| `ImportError: No module named aspose` | Aspose.BarCode no está instalado o está instalado en un entorno diferente. | Activa el entorno virtual correcto y ejecuta `pip install aspose-barcode`. | +| `PermissionError` al guardar | El script no tiene permiso de escritura para la carpeta de destino. | Elige un directorio que poseas o ejecuta el script con los privilegios adecuados. | +| El código de barras no se escanea | Dimensión X demasiado baja o relación de aspecto incompatible con el escáner. | Aumenta `x_dimension.pixels` a 3 o 4, y prueba diferentes valores de `aspect_ratio` (p. ej., 20, 25). | +| Falta runtime de .NET | Aspose.BarCode depende del runtime de .NET en Windows/Linux. | Instala el runtime más reciente de .NET desde el sitio de Microsoft; la documentación del paquete brinda guías específicas por plataforma. | + +## Extender el ejemplo + +Puedes adaptar el script para generar otras variantes de DataBar (p. ej., `DATABAR_STACKED`, `DATABAR_EXPANDED`). Reemplaza la constante `EncodeTypes` según corresponda: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Si necesitas incrustar el código de barras en un PDF, Aspose.PDF para Python puede importar directamente el archivo PNG o puedes usar el método `save` con `BarCodeImageFormat.Pdf`. + +## Conclusión + +Este tutorial mostró cómo **crear databar omnidireccional** y cómo **crear imagen de código de barras python** usando Aspose.BarCode. Ahora dispones de un script completo y reproducible que genera dos archivos PNG con diferentes relaciones de aspecto, maneja problemas comunes y puede ampliarse a otros formatos de código de barras. + +A continuación, explora la generación de códigos QR, la incorporación del código de barras en facturas PDF o la automatización del procesamiento por lotes para catálogos de productos extensos. Cada uno de esos temas se basa en el mismo patrón `BarcodeGenerator` demostrado aquí. ¡Feliz codificación! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to create barcode image and render it in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/spanish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/spanish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..4ec8c5bbe --- /dev/null +++ b/barcode/spanish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-08-12 +description: Cómo generar códigos de barras rápidamente usando Python. Aprende a crear + códigos de barras a partir de datos y exportar la imagen del código de barras con + una única biblioteca. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: es +lastmod: 2026-08-12 +og_description: Cómo generar códigos de barras en Python con Aspose.BarCode. Sigue + esta guía para crear códigos de barras a partir de datos y exportar la imagen del + código de barras como PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Cómo generar códigos de barras en Python – guía rápida y fiable +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Cómo generar códigos de barras en Python – guía completa paso a paso +url: /es/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo generar códigos de barras en Python – guía completa paso a paso + +Si necesitas **how to generate barcode** en una aplicación Python, este tutorial te muestra el código exacto que necesitas. Aprenderás a **create barcode from data**, ajustar su apariencia y **export barcode image** como un archivo PNG, todo en menos de diez líneas de código. + +Generar un código de barras puede parecer una preocupación separada del resto de la lógica de negocio, pero con una única biblioteca puedes mantener el proceso integrado con tu base de código existente. En las secciones siguientes verás un ejemplo completo y ejecutable, comprenderás por qué cada línea es importante y descubrirás variaciones comunes, como cambiar el ancho del módulo o dibujar un código de barras solo con contorno. + +## Cómo generar códigos de barras con la biblioteca Aspose.BarCode + +La biblioteca Aspose.BarCode para Python (a través de .NET) ofrece una API sencilla para muchas simbologías, incluido el código de barras Planet utilizado en esta guía. Antes de comenzar, asegúrate de que tienes el paquete instalado: + +```bash +pip install aspose-barcode +``` + +> **Consejo profesional:** Usa un entorno virtual para evitar conflictos de versiones con otros proyectos. + +### 1. Importar las clases requeridas + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Estas importaciones te dan acceso a la clase generadora, la enumeración de tipos de códigos de barras y la enumeración de formatos de imagen utilizada al guardar el resultado. + +### 2. Crear código de barras a partir de datos + +El primer paso es **create barcode from data**. El constructor `BarcodeGenerator` recibe la simbología y la cadena cruda que deseas codificar. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +El valor `EncodeTypes.Planet` selecciona el código de barras Planet, mientras que `"123456"` es la carga útil que aparecerá en la imagen final. + +### 3. Ajustar la dimensión X (ancho del módulo) + +La dimensión X controla el ancho de cada módulo del código de barras (la barra delgada). Configurarla a 4 píxeles produce una imagen clara y legible sin que el archivo sea demasiado grande. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Por qué es importante:** Una dimensión X mayor mejora la fiabilidad del escaneo en impresoras de baja resolución, mientras que un valor menor reduce el tamaño del archivo para uso web. + +### 4. Exportar imagen del código de barras (estilo relleno) + +Ahora puedes **export barcode image** usando el método `save`. El ejemplo guarda un archivo PNG, pero puedes elegir JPEG, BMP o TIFF cambiando la enumeración `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +El archivo `PlanetFilled.png` contiene un código de barras Planet completamente relleno, listo para imprimir o incrustar en un PDF. + +### 5. Crear un segundo generador para un código de barras solo con contorno + +Si necesitas una versión de contorno (barras vacías), debes crear un nuevo generador porque la bandera `filled_bars` no puede modificarse después de guardar la imagen. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Aplicar la misma configuración de dimensión X + +Al crear un segundo generador, debes repetir cualquier configuración visual que quieras mantener consistente. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Desactivar las barras rellenas para un código de barras de contorno + +Establecer `filled_bars` a `False` indica al renderizador que dibuje solo los contornos de cada módulo, produciendo una imagen más ligera que puede ser útil para propósitos de diseño. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Exportar la imagen del código de barras de contorno + +Finalmente, **export barcode image** nuevamente, esta vez guardando la versión de contorno. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Ahora tienes dos archivos PNG: uno con barras sólidas (`PlanetFilled.png`) y otro solo con contornos (`PlanetEmpty.png`). + +## Exportar imagen del código de barras en otros formatos (opcional) + +El método `save` admite varios formatos. Para exportar como JPEG con 90 % de calidad: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Si necesitas un fondo transparente para uso web, elige PNG con canal alfa: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Variaciones comunes y casos límite + +| Escenario | Cambio necesario | Fragmento de código | +|----------|------------------|----------------------| +| **Diferente simbología** (p.ej., QR) | Usar un valor diferente de `EncodeTypes` | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Color de primer plano personalizado** | Establecer `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Mayor resolución** | Incrementar DPI mediante `image_width` y `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Cadenas de datos largas** | Asegurar que la longitud de los datos cumpla la especificación de la simbología | Validar la longitud antes de crear el generador | + +> **Cuidado:** Proporcionar datos que superen la longitud máxima para la simbología elegida genera una excepción en tiempo de ejecución. Siempre valida la longitud de la cadena o captura `ArgumentException`. + +## Ejemplo completo y ejecutable + +A continuación se muestra el script completo que puedes copiar y pegar en un archivo llamado `generate_planet_barcode.py`. Ajusta `YOUR_DIRECTORY` a una carpeta que exista en tu máquina. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Ejecutar este script genera dos archivos PNG en el directorio especificado. Verifica la salida abriendo las imágenes en cualquier visor; ambas deberían mostrar un código de barras Planet que codifica la cadena `123456`. + +## Conclusión + +Ahora sabes **how to generate barcode** en Python usando Aspose.BarCode, cómo **create barcode from data**, y cómo **export barcode image** tanto en estilos rellenos como de contorno. El mismo patrón se aplica a otras simbologías, formatos de imagen y personalizaciones visuales, brindándote una base flexible para cualquier funcionalidad relacionada con códigos de barras en tu aplicación. + +### Próximos pasos + +* Explora otras simbologías como QR, Code‑128 o DataMatrix cambiando `EncodeTypes.Planet` por el valor deseado. +* Integra los archivos PNG generados en informes PDF usando bibliotecas como `ReportLab` o `PyPDF2`. +* Experimenta con valores dinámicos de dimensión X para adaptar el tamaño del código de barras según la resolución de pantalla o DPI de la impresora. + +¡Feliz codificación, y siéntete libre de adaptar el ejemplo para que se ajuste a los requisitos de tu propio proyecto! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/swedish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/swedish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..299302efb --- /dev/null +++ b/barcode/swedish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-08-12 +description: Exempel på streckkodsgenerator som visar hur man genererar streckkod + med exakt pixelförstorlek. Lär dig att ställa in modulbredd, stapelhöjd och skapa + Planet‑streckkoder. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: sv +lastmod: 2026-08-12 +og_description: Exemplet på streckkodsgenerator visar hur man genererar en streckkod + med exakta pixeldimensioner. Följ den här guiden för att kontrollera modulbredd + och stapelhöjd för Planet‑ och RM4SCC‑koder. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: exempel på streckkodsgenerator – anpassa pixelstorlek i C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Exempel på streckkodsgenerator – steg‑för‑steg‑guide för anpassade pixelstorlekar +url: /sv/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# barcode generator example – steg‑för‑steg guide för anpassade pixelformater + +Om du behöver ett **barcode generator example** som låter dig kontrollera varje pixel, visar den här guiden exakt hur du gör det. Du kommer att lära dig att ställa in modulbredden, definiera en fast stapelhöjd och generera både Planet‑ och RM4SCC‑streckkoder med förutsägbara dimensioner. + +De flesta utvecklare har problem med “hur man genererar streckkod”‑bilder som ser likadana ut på varje skärm eller skrivare. Kodsnuttarna nedan löser problemet genom att exponera pixel‑nivå‑parametrarna i Aspose.BarCode för .NET‑biblioteket, så att du kan producera konsekvent output utan gissningar. + +## Vad du kommer att lära dig + +* Hur du installerar det nödvändiga NuGet‑paketet. +* Hur du genererar en Planet‑streckkod med automatiskt beräknad höjd. +* Hur du genererar en Planet‑streckkod med en explicit 100‑pixel‑höjd. +* Hur du genererar en RM4SCC‑streckkod med samma explicita höjd. +* Varför **barcode pixel size** är viktigt för skannings‑tillförlitlighet. +* Tips för felsökning av vanliga problem när du genererar Planet‑streckkodsbilder. + +Du behöver bara .NET 6 eller senare, en grundläggande C#‑utvecklingsmiljö och en internetanslutning för att hämta NuGet‑paketet. + +--- + +## barcode generator example – konfigurera utvecklingsmiljön + +Innan du skriver någon kod, se till att Aspose.BarCode‑biblioteket är tillgängligt för ditt projekt. + +### Install the Aspose.BarCode package + +Öppna en terminal i din projektmapp och kör: + +```bash +dotnet add package Aspose.BarCode +``` + +Kommandot lägger till den senaste stabila versionen av **Aspose.BarCode** i ditt `csproj`. När återställningen är klar kan du börja använda klassen `BarcodeGenerator`. + +> **Pro tip:** Sikta på .NET 6 eller .NET 7 för att dra nytta av de senaste prestandaförbättringarna och standard‑UTF‑8‑hantering. + +### Add the necessary `using` directives + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Dessa namnrymder exponerar `BarcodeGenerator`‑klassen och `BarCodeImageFormat`‑enum som används senare i handledningen. + +--- + +## Hur du genererar streckkod med anpassad pixelform + +De följande tre stegen illustrerar det kompletta **barcode generator example**. Varje steg bygger på det föregående, så du kan kopiera‑klistra in hela blocket i en konsolapp och köra det utan ändringar. + +### Steg 1 – generera en Planet‑streckkod med automatiskt beräknad höjd + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Why this works:** +*`XDimension`‑egenskapen definierar bredden på en enskild streckkodmodul (det minsta svarta eller vita elementet). När du utelämnar `BarHeight` beräknar biblioteket en höjd som behåller standard‑aspektförhållandet för Planet‑koder.* + +**Expected output:** En PNG‑fil med namnet `PlanetAuto.png` som innehåller en ren Planet‑streckkod. Dess höjd anpassas till 4‑pixel‑modulbredden, vanligtvis omkring 60 pixel för en sex‑tecken‑payload. + +### Steg 2 – generera en Planet‑streckkod med en explicit 100‑pixel‑höjd + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Why you might need this:** +Ibland förväntar sig skanningsutrustningen en minsta stapelhöjd för pålitlig detektering. Genom att sätta `BarHeight.Pixels` garanterar du att varje genererad bild uppfyller detta krav, oavsett den kodade datalängden. + +**Expected output:** `PlanetHeight100.png` visar samma data som tidigare, men staplarna är exakt 100 pixel höga, vilket ger dig full kontroll över den visuella storleken. + +### Steg 3 – generera en RM4SCC‑streckkod med samma explicita höjd + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Why this matters:** +`EncodeTypes.RM4SCC` är en staplad linjär streckkod som används inom logistik. Att matcha dess stapelhöjd med Planet‑streckkoden förenklar batch‑bearbetning när båda symbolerna förekommer på samma etikett. + +**Expected output:** `RM4SCCHeight100.png` visar en perfekt dimensionerad RM4SCC‑streckkod, med samma 100‑pixel‑höjd som du satte för Planet‑koden. + +> **Result verification:** Öppna varje PNG i en bildvisare och bekräfta att de svarta staplarna är exakt 4 pixel breda och, där du specificerat, 100 pixel höga. Du kan också mata in filerna i en streckkodsläsarapp för att säkerställa att de avkodas till “123456”. + +--- + +## Förstå streckkodens pixelform och stapelhöjd + +### Vad är **barcode pixel size**? + +*Pixel size* avser det fysiska antalet skärm‑ eller skrivarpixlar som representerar en enskild modul (`XDimension`). En större pixelform ger en större streckkod, vilket kan vara lättare för lågupplösta skannrar men tar upp mer etikettutrymme. + +### Hur påverkar `BarHeight` läsbarheten? + +`BarHeight`‑egenskapen styr staplarnas vertikala längd. Standarder för de flesta 1‑D‑streckkoder (inklusive Planet och RM4SCC) rekommenderar en minsta höjd på 10 mm vid 300 dpi, vilket motsvarar ungefär 118 pixel. Att sätta en höjd under detta kan orsaka läsfel, särskilt med mobila kameror. + +### När bör du låta biblioteket beräkna höjden automatiskt? + +Om du bara genererar streckkoder för visning på skärm håller den automatiska beräkningen aspektförhållandet konsekvent och minskar behovet av manuell finjustering. För tryckta etiketter som måste uppfylla strikta ISO‑specifikationer bör du **explicit sätta stapelhöjden**. + +--- + +## Vanliga fallgropar och bästa praxis när du genererar Planet‑streckkod + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| Bars appear too thin or thick | `XDimension` left at default (1 pixel) on high‑resolution displays | Set `XDimension.Pixels` to at least 3‑4 for visual clarity | +| Scanner cannot read the code | `BarHeight` is too small for the scanner’s focal length | Use `BarHeight.Pixels` ≥ 100 for most mobile scanners | +| Image is blurry after scaling | Saving as JPEG introduces compression artifacts | Save as PNG (`BarCodeImageFormat.Png`) for lossless output | +| Unexpected barcode type | Wrong `EncodeTypes` enum value | Double‑check you’re using `EncodeTypes.Planet` for Planet symbology | + +### Pro tip on performance + +När du genererar tusentals streckkoder i ett batch‑jobb, återanvänd en enda `BarcodeGenerator`‑instans och ändra bara `CodeText` och storleksparametrarna mellan sparningar. Detta undviker upprepade allokeringar av interna renderingsobjekt och kan minska körningstiden med upp till 30 %. + +--- + +## Fullt fungerande exempel – sätt ihop allt + +Skapa ett nytt konsolprojekt (`dotnet new console -n BarcodeDemo`) och ersätt innehållet i `Program.cs` med följande: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Kör programmet med `dotnet run`. Efter körning hittar du tre PNG‑filer i projektmappen, var och en illustrerar ett annat **barcode generator example**‑scenario. + +--- + +## Nästa steg och relaterade ämnen + +* **How to generate barcode in other formats** – utforska `EncodeTypes.Code128`, `EncodeTypes.QR` och `EncodeTypes.DataMatrix` för 2‑D‑behov. +* **Embedding barcodes in PDFs** – kombinera Aspose.BarCode med Aspose.PDF för att placera streckkoder direkt på fakturamallar. +* **Dynamic barcode size based on user input** – calculate + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/swedish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/swedish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..b32b88aef --- /dev/null +++ b/barcode/swedish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-08-12 +description: Konfigurera Databar-streckkodslayout i Python snabbt. Lär dig att ställa + in kolumner, rader och spara bilder med streckkodsgeneratorbiblioteket. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: sv +lastmod: 2026-08-12 +og_description: Konfigurera Databar-streckkodslayout i Python för att kontrollera + kolumner, rader och bildutmatning. Följ den här guiden för en färdig lösning som + är klar att köra. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Konfigurera Databar streckkodslayout i Python – komplett handledning +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Konfigurera Databar streckkodslayout i Python – steg‑för‑steg‑guide +url: /sv/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konfigurera Databar streckkodslayout i Python – steg‑för‑steg‑guide + +Om du behöver **konfigurera Databar streckkodslayout i Python**, guidar den här artikeln dig genom hela processen. Du får se hur du ställer in antalet kolumner eller rader för en Databar Expanded Stacked‑streckkod och hur du sparar den resulterande bilden med ett enda anrop till streckkodsgeneratorbiblioteket. + +Att kontrollera layouten är avgörande när du bäddar in streckkoder på smal förpackning, kvitton eller mobila skärmar. I avsnitten nedan går vi igenom de nödvändiga importerna, de två layoutalternativen (kolumner och rader) och bästa praxis för att spara en ren PNG‑bild. + +## Vad du behöver + +* Python 3.8 eller nyare +* `aspose.barcode` (eller något kompatibelt streckkodsgenereringspaket) installerat + ```bash + pip install aspose-barcode + ``` +* Skrivbehörighet till en mapp där PNG‑filerna kommer att lagras + +Inga ytterligare externa verktyg krävs—biblioteket hanterar rendering, skalning och bildkodning internt. + +## Så konfigurerar du Databar streckkodslayout i Python + +Kärnan i lösningen är klassen `BarcodeGenerator`. Den accepterar en `EncodeTypes`‑enum som identifierar streckkodssymboliken—i detta fall `EncodeTypes.DatabarExpandedStacked`. Efter att generatorn har skapats kan du justera layouten genom att sätta egenskaperna `columns` eller `rows` på parameterobjektet `data_bar`. + +### Steg 1: Importera de nödvändiga klasserna + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Dessa importeringar ger dig åtkomst till generatorn, uppräkningen för Databar‑typer och konstanten för PNG‑bildformatet. + +### Steg 2: Skapa en streckkodsgenerator för Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Varför detta steg?* +`EncodeTypes.DatabarExpandedStacked` talar om för biblioteket att producera **Databar Expanded Stacked**‑symboliken, som stödjer längre numeriska strängar samtidigt som den behåller ett kompakt fotavtryck. Det andra argumentet är data som ska kodas; det kan vara vilken sträng som helst som uppfyller Databar‑specifikationen. + +### Steg 3: Ställ in antalet kolumner (horisontell layout) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** är nyckelfrasen för denna operation. När du ökar antalet kolumner sprider sig streckkoden horisontellt, vilket kan vara användbart för breda etiketter. Biblioteket beräknar automatiskt om modulbredden för att hålla den totala storleken konsekvent. + +#### Proffstips +Det maximala antalet kolumner för Databar Expanded Stacked är 8. Om du anger ett värde högre än gränsen kommer det att begränsas till maxvärdet, men det är bättre att validera din inmatning i förväg. + +### Steg 4: Spara streckkodsbilden med kolumnlayouten + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** är handlingen som skriver den renderade streckkoden till disk. PNG är förlustfri, vilket bevarar de skarpa kanterna som krävs för pålitlig avläsning. + +### Steg 5: Skapa en andra generator för samma streckkodstyp (radlayout) + +Om du föredrar en vertikal stapel arbetar du med rader istället för kolumner. Koden nedan återanvänder samma värde men skapar en ny `BarcodeGenerator`‑instans för att undvika att blanda kolumn- och radinställningar. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Steg 6: Ställ in antalet rader (vertikal layout) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** ordnar streckkodens moduler vertikalt. En layout med tre rader minskar höjden på varje enskild stapel, vilket gör streckkoden lämplig för smala kvitton eller mobila skärmar. + +#### Kantfall +Om du sätter `rows` till 1 genererar biblioteket en enradig Databar (motsvarande en standard‑Databar). Värden under 1 ignoreras och återställs till standardvärdet (1 rad). + +### Steg 7: Spara streckkodsbilden med radlayouten + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Återigen **save barcode image** med PNG för att hålla resultatet skarpt. + +## Fullt körbart exempel + +När alla delar sätts ihop får du ett självständigt skript som du kan lägga in i vilket Python‑projekt som helst. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Förväntat resultat** + +När skriptet körs skapas två PNG‑filer: + +* `output/ExpandedCols4.png` – en streckkod utsträckt över fyra kolumner +* `output/ExpandedRows3.png` – en streckkod komprimerad till tre rader + +Båda bilderna kan öppnas i vilken bildvisare som helst eller importeras direkt i PDF‑fakturor, etikettmallar eller webbsidor. + +## Vanliga frågor och felsökning + +| Fråga | Svar | +|----------|--------| +| *Vad händer om streckkoden ser suddig ut?* | Öka bildens upplösning genom att sätta `barcode_generator.parameters.image_width` och `image_height` innan du anropar `save`. | +| *Kan jag använda andra bildformat?* | Ja. Ersätt `BarCodeImageFormat.Png` med `Jpeg`, `Bmp` eller `Gif` efter behov. | +| *Finns det en gräns för datalängden?* | Databar Expanded Stacked stödjer upp till 74 numeriska tecken. Att överskrida gränsen kastar ett `ArgumentException`. | +| *Hur ändrar jag förgrundsfärgen?* | Använd `barcode_generator.parameters.barcode.color = Color.Blue` (importera `System.Drawing.Color`). | +| *Kan jag kombinera kolumner och rader?* | Nej. API:et behandlar kolumner och rader som ömsesidigt uteslutande layoutlägen. Välj ett per streckkodinstans. | + +## Nästa steg + +Nu när du kan **konfigurera Databar streckkodslayout**, överväg att utforska dessa relaterade ämnen: + +* **Lägg till textbeskrivningar** – använd `barcode_generator.parameters.barcode.code_text` för att visa det kodade värdet under bilden. +* **Bädda in streckkoden i en PDF** – kombinera den genererade PNG‑filen med `aspose.pdf` för att skapa utskrivbara dokument. +* **Dynamisk storlek** – beräkna optimalt antal kolumner eller rader baserat på etikettens dimensioner vid körning. +* **Batch‑bearbetning** – loopa över en CSV med produktkoder för att automatiskt generera ett bibliotek av streckkods‑bilder. + +Experimentera med olika kolumn‑ och radvärden för att se hur de påverkar skanningspålitligheten på dina mål­enheter. Ju mer du testar, desto bättre förstår du avvägningarna mellan streckkodsstorlek, läsbarhet och utrymmesbegränsningar. + +--- + +*Lycklig kodning! Om du fann den här handledningen användbar, dela den med kollegor eller lämna en kommentar om de layoututmaningar du stött på.* + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Skapa DotCode streckkodsbild – rader & kolumner (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Skapa streckkodsbild c# – Konfigurera Codablock F rader & kolumner](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [En-dimensionell Databar streckkodshöjdsjustering](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/swedish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/swedish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..229bb2a17 --- /dev/null +++ b/barcode/swedish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-08-12 +description: Skapa streckkodbild i C# med BarCodeGenerator. Lär dig hur du genererar + DataBar, styr streckkodens bildstorlek och skapar flera streckkoder effektivt. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: sv +lastmod: 2026-08-12 +og_description: Skapa streckkodbild i C# med BarCodeGenerator. Denna handledning visar + steg för steg hur du genererar DataBar‑koder, justerar streckkodens bildstorlek + och skapar flera streckkoder. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Skapa streckkodbild i C# – komplett guide till BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Skapa streckkodbild i C# med BarCodeGenerator +url: /sv/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa streckkodbild i C# med BarCodeGenerator + +Om du behöver **skapa streckkodbild** i en .NET‑applikation visar den här guiden exakt hur du gör det med `BarCodeGenerator`‑klassen. Oavsett om du bygger ett detaljhandels‑POS‑system eller ett verktyg för lager‑spårning, kommer du att lära dig att generera DataBar‑symboler, kontrollera streckkodens bildstorlek och producera flera streckkoder i ett kör. + +Du kommer också att upptäcka hur **barcode generator c#**‑API:t låter dig justera dimensioner, byta utdataformat och hantera kantfall som ogiltiga datasträngar. I slutet av tutorialen kan du självsäkert **skapa flera streckkoder** utan att skriva repetitiv kod. + +## Förutsättningar + +Innan du börjar, se till att du har: + +- .NET 6.0 eller senare installerat +- En utvecklingsmiljö (Visual Studio, Rider eller VS Code) +- Aspose.BarCode for .NET NuGet‑paketet (eller något kompatibelt bibliotek som tillhandahåller `BarCodeGenerator`) + +Du kan lägga till paketet med: + +```bash +dotnet add package Aspose.BarCode +``` + +## Vad den här tutorialen täcker + +1. Skapa en **barcode generator c#**‑instans för DataBar Omni‑directional‑kodning. +2. Justera **barcode image size** genom att ändra X‑dimension och stapelhöjd. +3. Använda en loop för att **create multiple barcodes** med olika höjder. +4. Spara bilderna som PNG‑filer och verifiera resultatet. + +Alla kodsnuttar är kompletta och redo att kopieras in i ett nytt konsolprojekt. + +![Create barcode image example](barcode-example.png){alt="Create barcode image example"} + +## Steg 1: Initiera generatorn – grunderna för att skapa streckkodbild + +Det första steget är att instansiera `BarCodeGenerator` med önskad symbolik. För en DataBar Omni‑directional‑symbol använder du `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Varför detta är viktigt:** Att instansiera generatorn definierar kodningsreglerna och datapayloaden. Om du utelämnar rätt `EncodeTypes`‑värde kommer biblioteket att producera en icke‑stödd streckkod eller kasta ett undantag. + +## Steg 2: Konfigurera X‑dimension och stapelhöjd – kontrollera streckkodens bildstorlek + +Den visuella storleken på en streckkod styrs av två parametrar: + +| Parameter | Vad den styr | Typiskt intervall | +|-----------|--------------|-------------------| +| `x_dimension.pixels` | Bredden på den minsta modulen (”punkten”) | 1 – 4 px | +| `bar_height.pixels` | Höjden på de vertikala staplarna | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Proffstips:** En mindre X‑dimension ger en högre upplösning men kan bli svårare att skanna på lågkvalitativa skrivare. Justera värdet baserat på den skanningsutrustning du riktar dig mot. + +## Steg 3: Spara den första streckkoden – skapa streckkodbild för 30 px höjd + +Nu kan du generera bilden och skriva den till disk. `Save`‑metoden accepterar en filsökväg och ett bildformat‑enum. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Förväntat resultat:** En PNG‑fil med namnet `Databar30.png` visas i `C:\Barcodes`. När du öppnar filen ser du en DataBar Omni‑directional‑symbol med ett tydligt, högkontrastmönster. + +## Steg 4: Ändra höjden och generera ytterligare bilder – skapa flera streckkoder + +För att **create multiple barcodes** med olika dimensioner behöver du bara ändra egenskapen `BarHeight` och anropa `Save` igen. Detta undviker att åter‑instansiera generatorn, vilket sparar minne och CPU‑tid. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Varför detta fungerar:** `BarCodeGenerator`‑objektet behåller all konfigurationsstatus. Att ändra en enda egenskap uppdaterar renderingsmotorn för nästa `Save`‑anrop, vilket låter dig **create multiple barcodes** effektivt. + +## Steg 5: Avancerat – hur man genererar DataBar med anpassad data + +Exemplet ovan använder en statisk GS1‑payload. I verkliga scenarier måste du ofta bädda in variabla produktidentifierare. Biblioteket accepterar vilken sträng som helst som uppfyller DataBar‑specifikationen. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Viktigt:** Att sätta `generator.CodeText` uppdaterar den kodade datan utan att återskapa objektet. Detta är det rekommenderade **how to generate databar**‑mönstret när du hanterar stora datamängder. + +## Steg 6: Verifiera och felsöka – säkerställ korrekt streckkodbildsstorlek + +Efter att ha genererat bilderna kan du vilja programatiskt bekräfta att dimensionerna matchar dina förväntningar. `Image`‑klassen från `System.Drawing` kan läsa filen och rapportera dess storlek. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Om höjden inte motsvarar det värde du angav, kontrollera: + +- **X‑dimension**: Ett mycket litet värde kan få renderaren att avrunda höjden. +- **Bildformat**: Vissa format (t.ex. JPEG) applicerar kompression som kan ändra pixeldimensioner vid sparning. PNG bevarar exakta dimensioner. + +## Steg 7: Bästa praxis för streckkodbildsstorlek och prestanda + +| Rekommendation | Orsak | +|----------------|-------| +| Håll `x_dimension.pixels` mellan 2 – 3 px för de flesta skannrar. | Balans mellan läsbarhet och filstorlek. | +| Använd PNG för förlustfri output när bilden ska skrivas ut. | Garanti för exakta dimensioner och skarpa kanter. | +| Återanvänd en enda `BarCodeGenerator`‑instans när du genererar många streckkoder. | Minskar objektallokeringskostnaden. | +| Validera inmatningssträngen mot GS1‑standarden innan du tilldelar den till `CodeText`. | Förhindrar körningstid‑undantag och ogiltiga skanningar. | +| Spara genererade bilder i en dedikerad mapp med ett tydligt namnschema (t.ex. `Databar_{GTIN}.png`). | Förenklar efterföljande bearbetning och auditspår. | + +## Fullt fungerande exempel + +Nedan är det kompletta programmet som inkluderar alla steg från initiering till verifiering. Kopiera koden till ett nytt konsolprojekt och kör det. + + + +## Vad du bör lära dig härnäst? + +Följande tutorialer täcker närbesläktade ämnen som bygger vidare på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationssätt i dina egna projekt. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to Create Barcode Quiet Zone for ITF-14 Using Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/swedish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/swedish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..0999b3d80 --- /dev/null +++ b/barcode/swedish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-08-12 +description: Skapa omnidirektionell databar med Python och lär dig hur du skapar streckkodsbild + i Python med Aspose.BarCode. Följ steg‑för‑steg‑guiden för en komplett lösning. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: sv +lastmod: 2026-08-12 +og_description: Skapa en omnidirektionell databar med Python och generera en streckkodbild + i Python på några minuter. Den här handledningen visar ett komplett, körbart exempel. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Skapa omnidirektionell databar – fullständig Python‑guide +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Skapa en omnidirektionell databar- och streckkodbild i Python +url: /sv/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa omnidirektionell databar och streckkodbild i Python + +Om du behöver **skapa omnidirektionell databar** i ett Python‑projekt, visar den här guiden hur du gör det och även hur du **skapar streckkodbild i Python** med Aspose.BarCode‑biblioteket. Du får ett färdigt skript som genererar två PNG‑filer med olika bildförhållanden. + +Att generera en DataBar som följer den omnidirektionella specifikationen är ett vanligt krav för detaljhandels‑ och logistikapplikationer. Handledningen täcker installation, konfiguration av X‑dimensionen, justering av bildförhållandet och sparande av de slutliga bilderna. Inga externa tjänster krävs; allt körs lokalt. + +## Vad du behöver + +* Python 3.8 eller nyare installerat på din maskin. +* Tillgång till en terminal eller kommandoprompt. +* Skrivrättighet till en mapp där streckkodbilderna ska sparas. + +Den enda tredjepartsberoendet är **Aspose.BarCode for Python via .NET**, som stöder den omnidirektionella DataBar‑typen direkt ur lådan. + +## Steg 1: Installera Aspose.BarCode för Python + +Aspose.BarCode tillhandahåller klassen `BarcodeGenerator` som används i exempel‑koden. Installera paketet med `pip`: + +```bash +pip install aspose-barcode +``` + +Paketet innehåller de nödvändiga .NET‑runtime‑bindningarna, så du behöver inte installera .NET‑SDK separat. + +## Steg 2: Importera biblioteket och skapa generatorn + +Den första raden i skriptet skapar en generator för en staplad omnidirektionell DataBar. GTIN‑14‑värdet `(01)12345678901231` används som exempeldata. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Varför detta steg är viktigt*: Konstanten `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` talar om för biblioteket att koda värdet som en omnidirektionell DataBar, vilket är det format som många kassascannrar kräver. + +## Steg 3: Ställ in X‑dimensionen (modulbredd) + +X‑dimensionen definierar bredden på den minsta stapelmodulen. Ett värde på `2` pixlar ger en tydlig, läsbar streckkod utan onödig filstorlek. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Varför detta steg är viktigt*: Genom att justera X‑dimensionen kan du balansera läsbarhet och bildstorlek. En X‑dimension som är för liten kan återges dåligt på lågupplösta skrivare. + +## Steg 4: Konfigurera bildförhållandet och spara den första bilden + +Bildförhållandet påverkar DataBarens totala höjd i förhållande till dess bredd. Ett bildförhållande på `15` skapar en kompakt visuell stil. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Proffstips**: Använd `pathlib.Path` för att bygga utdata‑sökvägen, vilket automatiskt skapar saknade kataloger. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Steg 5: Ändra bildförhållandet för en andra visuell stil och spara en annan bild + +Att byta bildförhållandet till `30` ger en högre streckkod som kan krävas av specifik scanner‑hardware. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Varför detta steg är viktigt*: Olika återförsäljare och scanningsenheter har olika storleksbegränsningar. Genom att erbjuda båda bildförhållandena i ett enda skript kan du generera exakt den stil du behöver utan att duplicera kod. + +## Fullt skript – skapa omnidirektionell databar och streckkodbild i Python + +Nedan är det kompletta, körbara exemplet som inkluderar alla tidigare steg. Spara det som `generate_databar.py` och kör det med `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Förväntat resultat + +När skriptet körs skapas följande filer: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Båda bilderna visar en giltig omnidirektionell DataBar som kan skannas av standardutrustning i detaljhandeln. + +![exempel på skapa omnidirektionell databar streckkodbild i Python](example_databar.png "skapa omnidirektionell databar streckkodbild i Python") + +*Bilden ovan är en platshållare som illustrerar de två sparade PNG‑filerna.* + +## Hantera vanliga problem + +| Problem | Orsak | Lösning | +|-------|--------|-----| +| `ImportError: No module named aspose` | Aspose.BarCode är inte installerat eller installerat i en annan miljö. | Aktivera rätt virtuell miljö och kör `pip install aspose-barcode`. | +| `PermissionError` när du sparar | Skriptet saknar skrivrättighet till mål‑mappen. | Välj en katalog du har rättigheter till eller kör skriptet med lämpliga privilegier. | +| Streckkoden skannas inte | X‑dimensionen är för låg eller bildförhållandet är inkompatibelt med scannern. | Öka `x_dimension.pixels` till 3 eller 4, och testa olika `aspect_ratio`‑värden (t.ex. 20, 25). | +| Saknad .NET‑runtime | Aspose.BarCode är beroende av .NET‑runtime på Windows/Linux. | Installera den senaste .NET‑runtime från Microsofts webbplats; paketdokumentationen ger plattforms‑specifik vägledning. | + +## Utöka exemplet + +Du kan anpassa skriptet för att generera andra DataBar‑varianter (t.ex. `DATABAR_STACKED`, `DATABAR_EXPANDED`). Byt ut `EncodeTypes`‑konstanten därefter: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Om du behöver bädda in streckkoden i en PDF, kan Aspose.PDF for Python importera PNG‑filen direkt eller så kan du använda `save`‑metoden med `BarCodeImageFormat.Pdf`. + +## Slutsats + +Denna handledning visade hur man **skapar omnidirektionell databar** och hur man **skapar streckkodbild i Python** med Aspose.BarCode. Du har nu ett komplett, reproducerbart skript som genererar två PNG‑filer med olika bildförhållanden, hanterar vanliga fallgropar och kan utökas till andra streckkodformat. + +Nästa steg är att utforska generering av QR‑koder, lägga till streckkoden i PDF‑fakturor eller automatisera batch‑behandling för stora produktkataloger. Varje ämne bygger på samma `BarcodeGenerator`‑mönster som demonstrerats här. Lycka till med kodningen! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstrerats i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Generera streckkodbild – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Skapa DotCode streckkodbild – rader & kolumner (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Hur man skapar streckkodbild och renderar den i Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/swedish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/swedish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..0b6d15b21 --- /dev/null +++ b/barcode/swedish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-08-12 +description: Hur man snabbt genererar streckkod med Python. Lär dig att skapa streckkod + från data och exportera streckkodsbild med ett enda bibliotek. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: sv +lastmod: 2026-08-12 +og_description: Hur man genererar streckkod i Python med Aspose.BarCode. Följ den + här guiden för att skapa streckkod från data och exportera streckkodsbilden som + PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Hur du genererar streckkod i Python – snabb, pålitlig guide +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Hur man genererar streckkod i Python – komplett steg‑för‑steg‑guide +url: /sv/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Så genererar du streckkod i Python – komplett steg‑för‑steg‑guide + +Om du behöver **how to generate barcode** i en Python‑applikation visar den här handledningen exakt vilken kod du behöver. Du kommer att lära dig att **create barcode from data**, justera dess utseende och **export barcode image** som en PNG‑fil – allt på mindre än tio kodrader. + +Att generera en streckkod kan kännas som ett separat problem jämfört med resten av din affärslogik, men med ett enda bibliotek kan du hålla processen i linje med din befintliga kodbas. I avsnitten som följer kommer du att se ett komplett, körbart exempel, förstå varför varje rad är viktig och upptäcka vanliga variationer såsom att ändra modulbredden eller rita en streckkod som bara visar konturer. + +## Så genererar du streckkod med Aspose.BarCode‑biblioteket + +Aspose.BarCode‑biblioteket för Python (via .NET) erbjuder ett enkelt API för många symbologier, inklusive Planet‑streckkoden som används i den här guiden. Innan du börjar, se till att du har paketet installerat: + +```bash +pip install aspose-barcode +``` + +> **Pro tip:** Använd en virtuell miljö för att undvika versionskonflikter med andra projekt. + +### 1. Importera de nödvändiga klasserna + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Dessa importeringar ger dig åtkomst till generator‑klassen, uppräkningen av streckkodstyper och bildformat‑enum som används när resultatet sparas. + +### 2. Skapa streckkod från data + +Det första steget är att **create barcode from data**. `BarcodeGenerator`‑konstruktorn tar symbologin och den råa strängen du vill koda. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +`EncodeTypes.Planet`‑värdet väljer Planet‑streckkoden, medan `"123456"` är den data som kommer att visas i den slutliga bilden. + +### 3. Justera X‑dimensionen (modulbredd) + +X‑dimensionen styr bredden på varje streckkodmodul (den tunna stapeln). Att sätta den till 4 pixlar ger en tydlig, läsbar bild utan att filen blir för stor. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Why this matters:** En större X‑dimension förbättrar skanningspålitligheten på lågupplösta skrivare, medan ett mindre värde minskar filstorleken för webbbruk. + +### 4. Exportera streckkodbild (fylld stil) + +Nu kan du **export barcode image** med `save`‑metoden. Exemplet sparar en PNG‑fil, men du kan välja JPEG, BMP eller TIFF genom att ändra `BarCodeImageFormat`‑enum. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +Filen `PlanetFilled.png` innehåller en helt fylld Planet‑streckkod, redo för utskrift eller inbäddning i en PDF. + +### 5. Skapa en andra generator för en streckkod som bara visar konturer + +Om du behöver en konturversion (tomma staplar) måste du skapa en ny generator eftersom `filled_bars`‑flaggan inte kan växlas efter att bilden har sparats. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Applicera samma X‑dimensioninställning + +När du skapar en andra generator måste du upprepa alla visuella inställningar du vill behålla konsekventa. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Inaktivera fyllda staplar för en konturstreckkod + +Att sätta `filled_bars` till `False` instruerar renderaren att bara rita konturerna för varje modul, vilket ger en lättare bild som kan vara användbar för designändamål. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Exportera konturstreckkodsbilden + +Slutligen **export barcode image** igen, den här gången sparar du konturversionen. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Du har nu två PNG‑filer: en med solida staplar (`PlanetFilled.png`) och en med endast konturer (`PlanetEmpty.png`). + +## Exportera streckkodbild i andra format (valfritt) + +`save`‑metoden stöder flera format. För att exportera som JPEG med 90 % kvalitet: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Om du behöver en transparent bakgrund för webbbruk, välj PNG med en alfakanal: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Vanliga variationer och kantfall + +| Scenario | Nödvändig ändring | Kodsnutt | +|----------|-------------------|----------| +| **Olika symbologi** (t.ex. QR) | Använd ett annat `EncodeTypes`‑värde | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Anpassad förgrundsfärg** | Ställ in `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Högre upplösning** | Öka DPI via `image_width` och `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Stora datasträngar** | Säkerställ att datalängden passar symbologins specifikation | Validate length before creating the generator | + +> **Watch out for:** Att leverera data som överskrider den maximala längden för den valda symbologin kastar ett körningsexception. Validera alltid stränglängden eller fånga `ArgumentException`. + +## Fullständigt, körbart exempel + +Nedan är det kompletta skriptet som du kan kopiera‑och‑klistra in i en fil med namnet `generate_planet_barcode.py`. Anpassa `YOUR_DIRECTORY` till en mapp som finns på din dator. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +När du kör detta skript skapas två PNG‑filer i den angivna katalogen. Verifiera resultatet genom att öppna bilderna i en bildvisare; båda bör visa en Planet‑streckkod som kodar strängen `123456`. + +## Slutsats + +Du vet nu **how to generate barcode** i Python med Aspose.BarCode, hur du **create barcode from data**, och hur du **export barcode image** i både fyllda och konturstilar. Samma mönster gäller för andra symbologier, bildformat och visuella anpassningar, vilket ger dig en flexibel grund för alla streckkod‑relaterade funktioner i din applikation. + +### Nästa steg + +* Utforska andra symbologier såsom QR, Code‑128 eller DataMatrix genom att byta `EncodeTypes.Planet` mot önskat värde. +* Integrera de genererade PNG‑filerna i PDF‑rapporter med bibliotek som `ReportLab` eller `PyPDF2`. +* Experimentera med dynamiska X‑dimensionvärden för att anpassa streckkodsstorleken baserat på skärmupplösning eller skrivardpi. + +Lycka till med kodandet, och känn dig fri att anpassa exemplet så att det passar dina egna projektkrav! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/thai/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/thai/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..f89edc50c --- /dev/null +++ b/barcode/thai/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-08-12 +description: ตัวอย่างเครื่องสร้างบาร์โค้ดที่แสดงวิธีการสร้างบาร์โค้ดด้วยขนาดพิกเซลที่แม่นยำ + เรียนรู้การตั้งค่าความกว้างของโมดูล ความสูงของบาร์ และสร้างบาร์โค้ด Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: th +lastmod: 2026-08-12 +og_description: ตัวอย่างเครื่องสร้างบาร์โค้ดแสดงวิธีการสร้างบาร์โค้ดด้วยขนาดพิกเซลที่แม่นยำ + ปฏิบัติตามคำแนะนำนี้เพื่อควบคุมความกว้างของโมดูลและความสูงของบาร์สำหรับโค้ด Planet + และ RM4SCC +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: ตัวอย่างการสร้างบาร์โค้ด – ปรับขนาดพิกเซลใน C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: ตัวอย่างเครื่องสร้างบาร์โค้ด – คู่มือขั้นตอนต่อขั้นสำหรับขนาดพิกเซลที่กำหนดเอง +url: /th/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ตัวอย่างตัวสร้างบาร์โค้ด – คู่มือขั้นตอนโดยละเอียดสำหรับขนาดพิกเซลที่กำหนดเอง + +หากคุณต้องการ **ตัวอย่างตัวสร้างบาร์โค้ด** ที่ให้คุณควบคุมทุกพิกเซล คู่มือนี้จะแสดงวิธีทำอย่างละเอียด คุณจะได้เรียนรู้การตั้งค่าความกว้างของโมดูล กำหนดความสูงของบาร์แบบคงที่ และสร้างบาร์โค้ด Planet และ RM4SCC ที่มีขนาดคาดเดาได้ + +นักพัฒนาส่วนใหญ่มักประสบปัญหา “วิธีการสร้างภาพบาร์โค้ด” ที่แสดงผลเหมือนกันบนทุกหน้าจอหรือเครื่องพิมพ์ โค้ดสแนปช็อตด้านล่างแก้ปัญหานี้โดยเปิดเผยพารามิเตอร์ระดับพิกเซลของไลบรารี Aspose.BarCode for .NET ทำให้คุณสามารถผลิตผลลัพธ์ที่สม่ำเสมอโดยไม่ต้องเดา + +## สิ่งที่คุณจะได้เรียนรู้ + +* วิธีการติดตั้งแพ็กเกจ NuGet ที่จำเป็น +* วิธีการสร้างบาร์โค้ด Planet ด้วยความสูงที่คำนวณโดยอัตโนมัติ +* วิธีการสร้างบาร์โค้ด Planet ด้วยความสูง 100 พิกเซลที่ระบุชัดเจน +* วิธีการสร้างบาร์โค้ด RM4SCC โดยใช้ความสูงที่ระบุชัดเจนเดียวกัน +* ทำไม **ขนาดพิกเซลของบาร์โค้ด** ถึงสำคัญต่อความน่าเชื่อถือของการสแกน +* เคล็ดลับการแก้ไขปัญหาที่พบบ่อยเมื่อคุณสร้างภาพบาร์โค้ด Planet + +คุณต้องมี .NET 6 หรือใหม่กว่า สภาพแวดล้อมการพัฒนา C# เบื้องต้น และการเชื่อมต่ออินเทอร์เน็ตเพื่อดึงแพ็กเกจ NuGet + +--- + +## ตัวอย่างตัวสร้างบาร์โค้ด – ตั้งค่าสภาพแวดล้อมการพัฒนา + +ก่อนเขียนโค้ดใด ๆ ให้แน่ใจว่าไลบรารี Aspose.BarCode พร้อมใช้งานในโปรเจกต์ของคุณ + +### ติดตั้งแพ็กเกจ Aspose.BarCode + +เปิดเทอร์มินัลในโฟลเดอร์โปรเจกต์ของคุณและรัน: + +```bash +dotnet add package Aspose.BarCode +``` + +คำสั่งนี้จะเพิ่มเวอร์ชันเสถียรล่าสุดของ **Aspose.BarCode** ไปยังไฟล์ `csproj` ของคุณ หลังจากการกู้คืนเสร็จสิ้น คุณสามารถเริ่มใช้คลาส `BarcodeGenerator` ได้ + +> **Pro tip:** เลือกเป้าหมายเป็น .NET 6 หรือ .NET 7 เพื่อรับประโยชน์จากการปรับปรุงประสิทธิภาพล่าสุดและการจัดการ UTF‑8 เริ่มต้น + +### เพิ่ม `using` directives ที่จำเป็น + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +เนมสเปซเหล่านี้ทำให้คุณเข้าถึงคลาส `BarcodeGenerator` และ enum `BarCodeImageFormat` ที่จะใช้ต่อในบทเรียน + +--- + +## วิธีการสร้างบาร์โค้ดด้วยขนาดพิกเซลที่กำหนดเอง + +ขั้นตอนสามขั้นตอนต่อไปนี้แสดงตัวอย่าง **ตัวสร้างบาร์โค้ด** อย่างครบถ้วน แต่ละขั้นตอนต่อเนื่องจากขั้นตอนก่อนหน้า คุณจึงสามารถคัดลอก‑วางบล็อกทั้งหมดไปยังแอปคอนโซลและรันโดยไม่ต้องแก้ไข + +### ขั้นตอน 1 – สร้างบาร์โค้ด Planet ด้วยความสูงที่คำนวณโดยอัตโนมัติ + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**ทำไมวิธีนี้ถึงได้ผล:** +*คุณสมบัติ `XDimension` กำหนดความกว้างของโมดูลบาร์โค้ดหนึ่งหน่วย (องค์ประกอบสีดำหรือสีขาวที่เล็กที่สุด) เมื่อคุณละเว้น `BarHeight` ไลบรารีจะคำนวณความสูงที่รักษาอัตราส่วนมาตรฐานของโค้ด Planet* + +**ผลลัพธ์ที่คาดหวัง:** ไฟล์ PNG ชื่อ `PlanetAuto.png` ที่มีบาร์โค้ด Planet สะอาด ความสูงของมันปรับตามความกว้างโมดูล 4 พิกเซล โดยทั่วไปประมาณ 60 พิกเซลสำหรับข้อมูลหกอักขระ + +### ขั้นตอน 2 – สร้างบาร์โค้ด Planet ด้วยความสูง 100 พิกเซลที่ระบุชัดเจน + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**เหตุผลที่อาจต้องทำเช่นนี้:** +บางครั้งอุปกรณ์สแกนต้องการความสูงบาร์ขั้นต่ำเพื่อการตรวจจับที่เชื่อถือได้ การตั้งค่า `BarHeight.Pixels` จะรับประกันว่าภาพที่สร้างทุกภาพตรงตามข้อกำหนดนั้น ไม่ว่าจะข้อมูลที่เข้ารหัสยาวเท่าใด + +**ผลลัพธ์ที่คาดหวัง:** `PlanetHeight100.png` แสดงข้อมูลเดียวกับก่อนหน้า แต่บาร์มีความสูงเท่ากับ 100 พิกเซล ให้คุณควบคุมขนาดภาพได้เต็มที่ + +### ขั้นตอน 3 – สร้างบาร์โค้ด RM4SCC ด้วยความสูงที่ระบุชัดเจนเดียวกัน + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**ทำไมเรื่องนี้ถึงสำคัญ:** +`EncodeTypes.RM4SCC` เป็นบาร์โค้ดเชิงเส้นแบบซ้อนที่ใช้ในโลจิสติกส์ การทำให้ความสูงของบาร์สอดคล้องกับบาร์โค้ด Planet จะทำให้การประมวลผลเป็นชุดง่ายขึ้นเมื่อทั้งสองสัญลักษณ์ปรากฏบนฉลากเดียวกัน + +**ผลลัพธ์ที่คาดหวัง:** `RM4SCCHeight100.png` แสดงบาร์โค้ด RM4SCC ที่มีขนาดพอดีตรงกับความสูง 100 พิกเซลที่คุณตั้งไว้สำหรับโค้ด Planet + +> **การตรวจสอบผลลัพธ์:** เปิดไฟล์ PNG แต่ละไฟล์ด้วยโปรแกรมดูรูปภาพและยืนยันว่าบาร์สีดำกว้าง 4 พิกเซลอย่างแม่นยำ และในส่วนที่คุณกำหนดความสูง 100 พิกเซลสูงตามที่ระบุ คุณยังสามารถนำไฟล์เหล่านี้ไปสแกนด้วยแอปสแกนบาร์โค้ดเพื่อให้แน่ใจว่าถอดรหัสเป็น “123456” + +--- + +## ทำความเข้าใจขนาดพิกเซลของบาร์โค้ดและความสูงของบาร์ + +### ขนาดพิกเซลของบาร์โค้ดคืออะไร? + +*ขนาดพิกเซล* หมายถึงจำนวนพิกเซลของหน้าจอหรือเครื่องพิมพ์ที่แทนโมดูลเดียว (`XDimension`) ทางกายภาพ ขนาดพิกเซลที่ใหญ่ขึ้นทำให้บาร์โค้ดใหญ่ขึ้น ซึ่งอาจง่ายต่อสแกนเนอร์ความละเอียดต่ำ แต่จะใช้พื้นที่ฉลากมากขึ้น + +### `BarHeight` มีผลต่อการอ่านอย่างไร? + +คุณสมบัติ `BarHeight` ควบคุมความยาวแนวตั้งของบาร์ มาตรฐานสำหรับบาร์โค้ด 1‑D ส่วนใหญ่ (รวมถึง Planet และ RM4SCC) แนะนำความสูงขั้นต่ำ 10 มม. เมื่อพิมพ์ที่ 300 dpi ซึ่งเทียบเท่าประมาณ 118 พิกเซล การตั้งค่าความสูงต่ำกว่านี้อาจทำให้เกิดข้อผิดพลาดในการอ่าน โดยเฉพาะกับกล้องมือถือ + +### ควรให้ไลบรารีคำนวณความสูงอัตโนมัติเมื่อไหร่? + +หากคุณสร้างบาร์โค้ดเพื่อแสดงบนหน้าจอเท่านั้น การคำนวณอัตโนมัติจะรักษาอัตราส่วนให้คงที่และลดความจำเป็นในการปรับแต่งด้วยตนเอง สำหรับฉลากที่ต้องเป็นไปตามข้อกำหนด ISO อย่างเคร่งครัด คุณควร **ตั้งค่าความสูงของบาร์อย่างชัดเจน** + +--- + +## ข้อผิดพลาดทั่วไปและแนวทางปฏิบัติที่ดีที่สุดเมื่อคุณสร้างบาร์โค้ด Planet + +| ปัญหา | สาเหตุ | วิธีแก้ | +|-------|--------|--------| +| บาร์ดูบางหรือหนามากเกินไป | `XDimension` ถูกทิ้งไว้ค่าเริ่มต้น (1 พิกเซล) บนหน้าจอความละเอียดสูง | ตั้งค่า `XDimension.Pixels` อย่างน้อย 3‑4 เพื่อความชัดเจน | +| สแกนเนอร์ไม่สามารถอ่านโค้ดได้ | `BarHeight` ต่ำเกินไปสำหรับความยาวโฟกัสของสแกนเนอร์ | ใช้ `BarHeight.Pixels` ≥ 100 สำหรับสแกนเนอร์มือถือส่วนใหญ่ | +| ภาพเบลอหลังจากสเกล | การบันทึกเป็น JPEG ทำให้เกิดอาร์ติฟาクトจากการบีบอัด | บันทึกเป็น PNG (`BarCodeImageFormat.Png`) เพื่อผลลัพธ์ไม่มีการสูญเสีย | +| ประเภทบาร์โค้ดไม่ตรงตามที่คาด | ค่า enum `EncodeTypes` ผิด | ตรวจสอบให้แน่ใจว่าคุณใช้ `EncodeTypes.Planet` สำหรับสัญลักษณ์ Planet | + +### เคล็ดลับด้านประสิทธิภาพ + +เมื่อสร้างบาร์โค้ดหลายพันรายการในงานแบตช์ ให้ใช้อินสแตนซ์ `BarcodeGenerator` เพียงตัวเดียวและเปลี่ยน `CodeText` กับพารามิเตอร์ขนาดระหว่างการบันทึกเท่านั้น วิธีนี้จะหลีกเลี่ยงการจัดสรรอ็อบเจกต์การเรนเดอร์ภายในซ้ำ ๆ และสามารถลดเวลาในการทำงานได้ถึง 30 % + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ – รวมทุกอย่างเข้าด้วยกัน + +สร้างโปรเจกต์คอนโซลใหม่ (`dotnet new console -n BarcodeDemo`) แล้วแทนที่เนื้อหาใน `Program.cs` ด้วยโค้ดต่อไปนี้: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +รันโปรแกรมด้วย `dotnet run` หลังจากทำงานเสร็จคุณจะพบไฟล์ PNG สามไฟล์ในโฟลเดอร์โปรเจกต์ แต่ละไฟล์แสดงสถานการณ์ **ตัวอย่างตัวสร้างบาร์โค้ด** ที่แตกต่างกัน + +--- + +## ขั้นตอนต่อไปและหัวข้อที่เกี่ยวข้อง + +* **วิธีการสร้างบาร์โค้ดในรูปแบบอื่น** – สำรวจ `EncodeTypes.Code128`, `EncodeTypes.QR` และ `EncodeTypes.DataMatrix` สำหรับความต้องการ 2‑D +* **การฝังบาร์โค้ดใน PDF** – ผสาน Aspose.BarCode กับ Aspose.PDF เพื่อวางบาร์โค้ดโดยตรงบนเทมเพลตใบแจ้งหนี้ +* **ขนาดบาร์โค้ดแบบไดนามิกตามข้อมูลผู้ใช้** – คำนวณ + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานครบถ้วนพร้อมคำอธิบายขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้แบบต่าง ๆ ในโครงการของคุณ + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/thai/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/thai/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..734aa277f --- /dev/null +++ b/barcode/thai/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: กำหนดค่าเลย์เอาต์บาร์โค้ด Databar ใน Python อย่างรวดเร็ว เรียนรู้การตั้งค่าคอลัมน์ + แถว และบันทึกรูปภาพด้วยไลบรารีสร้างบาร์โค้ด +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: th +lastmod: 2026-08-12 +og_description: กำหนดค่าเลย์เอาต์บาร์โค้ด Databar ใน Python เพื่อควบคุมคอลัมน์ แถว + และผลลัพธ์ภาพ ปฏิบัติตามคู่มือนี้เพื่อรับโซลูชันพร้อมใช้งาน +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: กำหนดค่าเลย์เอาต์บาร์โค้ด Databar ใน Python – บทเรียนครบถ้วน +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: กำหนดค่าเลย์เอาต์บาร์โค้ด Databar ใน Python – คู่มือแบบขั้นตอนต่อขั้นตอน +url: /th/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# กำหนดค่าเลย์เอาต์บาร์โค้ด Databar ใน Python – คู่มือขั้นตอนโดยละเอียด + +หากคุณต้องการ **กำหนดค่าเลย์เอาต์บาร์โค้ด Databar ใน Python** คู่มือนี้จะพาคุณผ่านกระบวนการทั้งหมด คุณจะได้เห็นวิธีตั้งค่าจำนวนคอลัมน์หรือแถวสำหรับบาร์โค้ด Databar Expanded Stacked และวิธีบันทึกรูปภาพที่ได้ด้วยการเรียกเพียงครั้งเดียวจากไลบรารีสร้างบาร์โค้ด + +การควบคุมเลย์เอาต์เป็นสิ่งสำคัญเมื่อคุณฝังบาร์โค้ดบนบรรจุภัณฑ์แคบ ใบเสร็จ หรือหน้าจอมือถือ ในส่วนต่อไปนี้เราจะครอบคลุมการนำเข้าไลบรารีที่จำเป็น ตัวเลือกเลย์เอาต์สองแบบ (คอลัมน์และแถว) และแนวทางปฏิบัติที่ดีที่สุดสำหรับการบันทึกรูป PNG ที่คมชัด + +## สิ่งที่คุณต้องมี + +* Python 3.8 หรือใหม่กว่า +* `aspose.barcode` (หรือแพคเกจสร้างบาร์โค้ดที่เข้ากันได้อื่น) ติดตั้งแล้ว + ```bash + pip install aspose-barcode + ``` +* สิทธิ์การเขียนในโฟลเดอร์ที่ไฟล์ PNG จะถูกจัดเก็บ + +ไม่จำเป็นต้องใช้เครื่องมือภายนอกเพิ่มเติม—ไลบรารีจะจัดการการเรนเดอร์ การสเกล และการเข้ารหัสภาพภายใน + +## วิธีกำหนดค่าเลย์เอาต์บาร์โค้ด Databar ใน Python + +หัวใจของวิธีแก้คือคลาส `BarcodeGenerator` มันรับค่า `EncodeTypes` enum ที่ระบุสัญลักษณ์บาร์โค้ด—in this case `EncodeTypes.DatabarExpandedStacked`. หลังจากสร้าง generator แล้วคุณสามารถปรับเลย์เอาต์โดยตั้งค่าคุณสมบัติ `columns` หรือ `rows` บนวัตถุพารามิเตอร์ `data_bar` + +### ขั้นตอนที่ 1: นำเข้าคลาสที่จำเป็น + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +การนำเข้าต่าง ๆ นี้ทำให้คุณเข้าถึง generator, enum สำหรับประเภท Databar, และค่าคงที่รูปแบบภาพ PNG + +### ขั้นตอนที่ 2: สร้าง barcode generator สำหรับ Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*ทำไมต้องทำขั้นตอนนี้?* +`EncodeTypes.DatabarExpandedStacked` บอกไลบรารีให้สร้างสัญลักษณ์ **Databar Expanded Stacked** ซึ่งรองรับสตริงตัวเลขยาวขึ้นในขณะที่ยังคงมีขนาดกะทัดรัด พารามิเตอร์ที่สองคือข้อมูลที่จะเข้ารหัส; สามารถเป็นสตริงใดก็ได้ที่ตรงตามสเปคของ Databar + +### ขั้นตอนที่ 3: ตั้งค่าจำนวนคอลัมน์ (เลย์เอาต์แนวนอน) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** เป็นวลีสำคัญสำหรับการดำเนินการนี้ เมื่อคุณเพิ่มจำนวนคอลัมน์ บาร์โค้ดจะกระจายออกในแนวนอน ซึ่งอาจเป็นประโยชน์สำหรับป้ายกว้าง ไลบรารีจะคำนวณความกว้างโมดูลใหม่โดยอัตโนมัติเพื่อให้ขนาดโดยรวมคงที่ + +#### เคล็ดลับพิเศษ +จำนวนคอลัมน์สูงสุดสำหรับ Databar Expanded Stacked คือ 8 การตั้งค่าค่าที่สูงกว่าขีดจำกัดจะถูกจำกัดไว้ที่ค่าสูงสุด แต่ควรตรวจสอบค่าที่รับเข้าก่อน + +### ขั้นตอนที่ 4: บันทึกรูปบาร์โค้ดด้วยเลย์เอาต์คอลัมน์ + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** คือการกระทำที่เขียนบาร์โค้ดที่เรนเดอร์แล้วลงดิสก์ PNG เป็นรูปแบบ lossless ซึ่งรักษาขอบคมที่จำเป็นสำหรับการสแกนที่เชื่อถือได้ + +### ขั้นตอนที่ 5: สร้าง generator ตัวที่สองสำหรับประเภทบาร์โค้ดเดียวกัน (เลย์เอาต์แถว) + +หากคุณต้องการสแต็กแนวตั้ง ให้ทำงานกับแถวแทนคอลัมน์ โค้ดด้านล่างใช้ค่าเดียวกันแต่สร้างอินสแตนซ์ `BarcodeGenerator` ใหม่เพื่อหลีกเลี่ยงการผสมผสานการตั้งค่าคอลัมน์และแถว + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### ขั้นตอนที่ 6: ตั้งค่าจำนวนแถว (เลย์เอาต์แนวตั้ง) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** จัดเรียงโมดูลบาร์โค้ดในแนวตั้ง การจัดเรียงแบบสามแถวจะลดความสูงของแต่ละสแต็ก ทำให้บาร์โค้ดเหมาะกับใบเสร็จแคบหรือหน้าจอมือถือ + +#### กรณีขอบ +หากคุณตั้งค่า `rows` เป็น 1 ไลบรารีจะสร้าง Databar แถวเดียว (เทียบเท่ากับ Databar มาตรฐาน) ค่าที่ต่ำกว่า 1 จะถูกละเว้นและรีเซ็ตเป็นค่าเริ่มต้น (1 แถว) + +### ขั้นตอนที่ 7: บันทึกรูปบาร์โค้ดด้วยเลย์เอาต์แถว + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +อีกครั้ง เรา **save barcode image** ด้วย PNG เพื่อให้ผลลัพธ์คมชัด + +## ตัวอย่างที่สามารถรันได้ทั้งหมด + +การรวมส่วนต่าง ๆ เข้าด้วยกันจะให้สคริปต์ที่เป็นอิสระซึ่งคุณสามารถใส่ลงในโปรเจกต์ Python ใดก็ได้ + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**ผลลัพธ์ที่คาดหวัง** + +การรันสคริปต์จะสร้างไฟล์ PNG สองไฟล์: + +* `output/ExpandedCols4.png` – บาร์โค้ดที่ขยายออกในสี่คอลัมน์ +* `output/ExpandedRows3.png` – บาร์โค้ดที่บีบอัดเป็นสามแถว + +ทั้งสองภาพสามารถเปิดด้วยโปรแกรมดูภาพใดก็ได้หรือทำการนำเข้าโดยตรงไปยังใบแจ้งหนี้ PDF, เทมเพลตป้าย, หรือหน้าเว็บ + +## คำถามทั่วไปและการแก้ไขปัญหา + +| Question | Answer | +|----------|--------| +| *ถ้าบาร์โค้ดดูเบลอ?* | เพิ่มความละเอียดของภาพโดยตั้งค่า `barcode_generator.parameters.image_width` และ `image_height` ก่อนเรียก `save`. | +| *ฉันสามารถใช้รูปแบบภาพอื่นได้หรือไม่?* | ได้. แทนที่ `BarCodeImageFormat.Png` ด้วย `Jpeg`, `Bmp` หรือ `Gif` ตามต้องการ. | +| *มีขีดจำกัดความยาวของข้อมูลหรือไม่?* | Databar Expanded Stacked รองรับสูงสุด 74 ตัวอักษรตัวเลข. หากเกินขีดจำกัดจะเกิด `ArgumentException`. | +| *ฉันจะเปลี่ยนสีพื้นหน้าอย่างไร?* | ใช้ `barcode_generator.parameters.barcode.color = Color.Blue` (นำเข้า `System.Drawing.Color`). | +| *ฉันสามารถรวมคอลัมน์และแถวได้หรือไม่?* | ไม่ได้. API ถือว่าคอลัมน์และแถวเป็นโหมดเลย์เอาต์ที่ไม่สามารถใช้ร่วมกันได้. เลือกหนึ่งโหมดต่ออินสแตนซ์ของบาร์โค้ด. | + +## ขั้นตอนต่อไป + +ตอนนี้คุณสามารถ **กำหนดค่าเลย์เอาต์บาร์โค้ด Databar** แล้ว ลองสำรวจหัวข้อที่เกี่ยวข้องต่อไปนี้: + +* **เพิ่มคำบรรยายข้อความ** – ใช้ `barcode_generator.parameters.barcode.code_text` เพื่อแสดงค่าที่เข้ารหัสใต้ภาพ +* **ฝังบาร์โค้ดใน PDF** – ผสาน PNG ที่สร้างกับ `aspose.pdf` เพื่อสร้างเอกสารที่พิมพ์ได้ +* **การกำหนดขนาดแบบไดนามิก** – คำนวณจำนวนคอลัมน์หรือแถวที่เหมาะสมตามขนาดป้ายในเวลารัน +* **การประมวลผลเป็นชุด** – วนลูปผ่าน CSV ของรหัสสินค้าเพื่อสร้างไลบรารีรูปบาร์โค้ดโดยอัตโนมัติ + +ทดลองใช้ค่าคอลัมน์และแถวต่าง ๆ เพื่อดูว่ามันส่งผลต่อความน่าเชื่อถือของการสแกนบนอุปกรณ์เป้าหมายอย่างไร ยิ่งคุณทดสอบมากเท่าไหร่ คุณก็จะเข้าใจการแลกเปลี่ยนระหว่างขนาดบาร์โค้ด ความอ่านง่าย และข้อจำกัดของพื้นที่ได้ดียิ่งขึ้น + +--- + +*ขอให้เขียนโค้ดอย่างสนุก! หากคุณพบว่าคู่มือนี้เป็นประโยชน์, แชร์ให้เพื่อนร่วมทีมหรือแสดงความคิดเห็นเกี่ยวกับความท้าทายของการกำหนดเลย์เอาต์ที่คุณเจอ* + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานทางเลือกในโปรเจกต์ของคุณเอง + +- [สร้างภาพบาร์โค้ด DotCode – แถวและคอลัมน์ (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [สร้างภาพบาร์โค้ด c# – กำหนดค่า Codablock F แถวและคอลัมน์](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [การปรับความสูงของบาร์โค้ด Databar มิติเดียว](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/thai/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/thai/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..d6ec8aca4 --- /dev/null +++ b/barcode/thai/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-08-12 +description: สร้างภาพบาร์โค้ดใน C# ด้วย BarCodeGenerator เรียนรู้วิธีสร้าง DataBar + ควบคุมขนาดภาพบาร์โค้ด และสร้างบาร์โค้ดหลายรายการอย่างมีประสิทธิภาพ +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: th +lastmod: 2026-08-12 +og_description: สร้างภาพบาร์โค้ดใน C# ด้วย BarCodeGenerator. บทเรียนนี้แสดงขั้นตอนโดยละเอียดในการสร้างรหัส + DataBar, ปรับขนาดภาพบาร์โค้ด, และสร้างบาร์โค้ดหลายรายการ. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: สร้างภาพบาร์โค้ดใน C# – คู่มือ BarCodeGenerator อย่างครบถ้วน +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: สร้างภาพบาร์โค้ดใน C# ด้วย BarCodeGenerator +url: /th/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างภาพบาร์โค้ดใน C# ด้วย BarCodeGenerator + +หากคุณต้องการ **สร้างภาพบาร์โค้ด** ในแอปพลิเคชัน .NET คู่มือนี้จะแสดงให้คุณเห็นอย่างละเอียดว่าต้องทำอย่างไรด้วยคลาส `BarCodeGenerator` ไม่ว่าคุณจะกำลังสร้างระบบ POS สำหรับร้านค้าปลีกหรือเครื่องมือการติดตามสินค้าคงคลัง คุณจะได้เรียนรู้การสร้างสัญลักษณ์ DataBar การควบคุมขนาดภาพบาร์โค้ด และการผลิตบาร์โค้ดหลายรายการในหนึ่งการทำงาน + +คุณยังจะได้ค้นพบว่า API **barcode generator c#** ช่วยให้คุณปรับขนาด เปลี่ยนรูปแบบผลลัพธ์ และจัดการกรณีขอบเช่นสตริงข้อมูลที่ไม่ถูกต้องได้อย่างไร เมื่อจบบทเรียนคุณจะสามารถ **สร้างบาร์โค้ดหลายรายการ** ได้อย่างมั่นใจโดยไม่ต้องเขียนโค้ดซ้ำซ้อน + +## สิ่งที่ต้องเตรียมก่อน + +- .NET 6.0 หรือรุ่นที่ใหม่กว่า ติดตั้งแล้ว +- สภาพแวดล้อมการพัฒนา (Visual Studio, Rider หรือ VS Code) +- แพคเกจ NuGet Aspose.BarCode for .NET (หรือไลบรารีที่เข้ากันได้ซึ่งให้ `BarCodeGenerator`) + +คุณสามารถเพิ่มแพคเกจด้วย: + +```bash +dotnet add package Aspose.BarCode +``` + +## สิ่งที่บทเรียนนี้ครอบคลุม + +1. ตั้งค่าอินสแตนซ์ **barcode generator c#** สำหรับการเข้ารหัส DataBar Omni‑directional. +2. ปรับ **ขนาดภาพบาร์โค้ด** โดยการเปลี่ยน X‑dimension และความสูงของบาร์. +3. ใช้ลูปเพื่อ **สร้างบาร์โค้ดหลายรายการ** ด้วยความสูงที่แตกต่างกัน. +4. บันทึกภาพเป็นไฟล์ PNG และตรวจสอบผลลัพธ์. + +โค้ดสแนปทั้งหมดสมบูรณ์และพร้อมคัดลอก‑วางลงในโปรเจกต์คอนโซลใหม่ + +![Create barcode image example](barcode-example.png){alt="ตัวอย่างการสร้างภาพบาร์โค้ด"} + +## ขั้นตอนที่ 1: เริ่มต้นตัวสร้าง – พื้นฐานการสร้างภาพบาร์โค้ด + +ขั้นตอนแรกคือการสร้างอินสแตนซ์ `BarCodeGenerator` ด้วยสัญลักษณ์ที่ต้องการ สำหรับสัญลักษณ์ DataBar Omni‑directional คุณใช้ `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**ทำไมจึงสำคัญ:** การสร้างอินสแตนซ์ของตัวสร้างกำหนดกฎการเข้ารหัสและข้อมูลที่ส่ง หากคุณละเว้นค่า `EncodeTypes` ที่ถูกต้อง ไลบรารีจะสร้างบาร์โค้ดที่ไม่รองรับหรือโยนข้อยกเว้น + +## ขั้นตอนที่ 2: กำหนดค่า X‑dimension และความสูงของบาร์ – ควบคุมขนาดภาพบาร์โค้ด + +ขนาดภาพของบาร์โค้ดถูกกำหนดโดยสองพารามิเตอร์: + +| Parameter | สิ่งที่ควบคุม | ช่วงทั่วไป | +|-----------|------------------|---------------| +| `x_dimension.pixels` | ความกว้างของโมดูลที่เล็กที่สุด ( “จุด” ) | 1 – 4 px | +| `bar_height.pixels` | ความสูงของบาร์แนวตั้ง | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**เคล็ดลับ:** X‑dimension ที่เล็กลงจะให้ภาพความละเอียดสูงขึ้น แต่อาจสแกนได้ยากบนเครื่องพิมพ์คุณภาพต่ำ ปรับค่าตามอุปกรณ์สแกนที่คุณต้องการ + +## ขั้นตอนที่ 3: บันทึกบาร์โค้ดแรก – สร้างภาพบาร์โค้ดความสูง 30 px + +ตอนนี้คุณสามารถสร้างภาพและบันทึกลงดิสก์ได้ เมธอด `Save` รับพาธไฟล์และ enum ของรูปแบบภาพ + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**ผลลัพธ์ที่คาดหวัง:** ไฟล์ PNG ชื่อ `Databar30.png` จะปรากฏใน `C:\Barcodes` การเปิดไฟล์จะแสดงสัญลักษณ์ DataBar Omni‑directional ที่มีลวดลายคมชัดและคอนทราสต์สูง + +## ขั้นตอนที่ 4: เปลี่ยนความสูงและสร้างภาพเพิ่มเติม – สร้างบาร์โค้ดหลายรายการ + +เพื่อ **สร้างบาร์โค้ดหลายรายการ** ด้วยมิติที่แตกต่างกัน คุณเพียงแค่แก้ไขคุณสมบัติ `BarHeight` แล้วเรียก `Save` อีกครั้ง วิธีนี้หลีกเลี่ยงการสร้างอินสแตนซ์ใหม่ของตัวสร้าง ซึ่งช่วยประหยัดหน่วยความจำและเวลา CPU + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**ทำไมวิธีนี้ถึงได้ผล:** วัตถุ `BarCodeGenerator` เก็บสถานะการกำหนดค่าทั้งหมด การเปลี่ยนคุณสมบัติเดียวจะอัปเดตเอนจินการเรนเดอร์สำหรับการเรียก `Save` ครั้งต่อไป ทำให้คุณสามารถ **สร้างบาร์โค้ดหลายรายการ** ได้อย่างมีประสิทธิภาพ + +## ขั้นตอนที่ 5: ขั้นสูง – วิธีสร้าง DataBar ด้วยข้อมูลกำหนดเอง + +ตัวอย่างข้างต้นใช้ข้อมูล GS1 แบบคงที่ ในสถานการณ์จริงคุณมักต้องฝังตัวระบุผลิตภัณฑ์ที่เปลี่ยนแปลงได้ ไลบรารีรับสตริงใด ๆ ที่ตรงกับสเปค DataBar + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**ประเด็นสำคัญ:** การตั้งค่า `generator.CodeText` จะอัปเดตข้อมูลที่เข้ารหัสโดยไม่ต้องสร้างอ็อบเจกต์ใหม่ นี่เป็นรูปแบบ **how to generate databar** ที่แนะนำเมื่อจัดการชุดข้อมูลขนาดใหญ่ + +## ขั้นตอนที่ 6: ตรวจสอบและแก้ไขปัญหา – การรับประกันขนาดภาพบาร์โค้ดที่ถูกต้อง + +หลังจากสร้างภาพแล้ว คุณอาจต้องการตรวจสอบโดยโปรแกรมว่าขนาดตรงกับที่คาดหวังหรือไม่ คลาส `Image` จาก `System.Drawing` สามารถอ่านไฟล์และรายงานขนาดได้ + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +หากความสูงไม่ตรงกับค่าที่คุณตั้งไว้ ให้ตรวจสอบ: + +- **X‑dimension**: ค่าที่เล็กมากอาจทำให้ตัวเรนเดอร์ปัดค่าความสูง +- **รูปแบบภาพ**: รูปแบบบางอย่าง (เช่น JPEG) ใช้การบีบอัดที่อาจเปลี่ยนขนาดพิกเซลเมื่อบันทึก PNG จะรักษาขนาดที่แน่นอน + +## ขั้นตอนที่ 7: แนวทางปฏิบัติที่ดีที่สุดสำหรับขนาดภาพบาร์โค้ดและประสิทธิภาพ + +| Recommendation | Reason | +|----------------|--------| +| รักษา `x_dimension.pixels` ระหว่าง 2 – 3 px สำหรับสแกนเนอร์ส่วนใหญ่. | สมดุลระหว่างความอ่านง่ายและขนาดไฟล์. | +| ใช้ PNG สำหรับผลลัพธ์แบบไม่มีการสูญเสียเมื่อภาพจะถูกพิมพ์. | รับประกันขนาดที่แม่นยำและขอบคมชัด. | +| ใช้ `BarCodeGenerator` ตัวเดียวซ้ำเมื่อสร้างบาร์โค้ดหลายรายการ. | ลดภาระการจัดสรรอ็อบเจกต์. | +| ตรวจสอบสตริงอินพุตกับมาตรฐาน GS1 ก่อนกำหนดให้ `CodeText`. | ป้องกันข้อยกเว้นในระหว่างรันและการสแกนที่ไม่ถูกต้อง. | +| เก็บภาพที่สร้างไว้ในโฟลเดอร์เฉพาะพร้อมรูปแบบการตั้งชื่อที่ชัดเจน (เช่น `Databar_{GTIN}.png`). | ทำให้การประมวลผลต่อเนื่องและการตรวจสอบง่ายขึ้น. | + +## ตัวอย่างการทำงานเต็มรูปแบบ + +ด้านล่างเป็นโปรแกรมเต็มที่รวมทุกขั้นตอนตั้งแต่การเริ่มต้นจนถึงการตรวจสอบ คัดลอกโค้ดไปยังโปรเจกต์คอนโซลใหม่และรันมัน + + + +## สิ่งที่คุณควรเรียนต่อไป + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการนำไปใช้ทางเลือกในโครงการของคุณ + +- [สร้างภาพบาร์โค้ด – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [สร้างภาพบาร์โค้ด DotCode – แถวและคอลัมน์ (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [วิธีสร้าง Quiet Zone ของบาร์โค้ดสำหรับ ITF-14 ด้วย Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/thai/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/thai/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..8ee87ac87 --- /dev/null +++ b/barcode/thai/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-08-12 +description: สร้าง Omni Directional Databar ด้วย Python และเรียนรู้วิธีสร้างภาพบาร์โค้ดด้วย + Python โดยใช้ Aspose.BarCode. ปฏิบัติตามคู่มือขั้นตอนต่อขั้นตอนเพื่อรับโซลูชันที่ครบถ้วน. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: th +lastmod: 2026-08-12 +og_description: สร้างดาต้าแบร์แบบหลายทิศทางด้วย Python และสร้างภาพบาร์โค้ดด้วย Python + ภายในไม่กี่นาที บทเรียนนี้แสดงตัวอย่างที่สมบูรณ์และสามารถรันได้ +og_image_alt: example of create omni directional databar barcode image in Python +og_title: สร้างแถบข้อมูลหลายทิศทาง – คู่มือ Python ฉบับเต็ม +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: สร้างภาพแถบข้อมูลและบาร์โค้ดแบบหลายทิศทางใน Python +url: /th/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้าง Omni‑directional DataBar และภาพบาร์โค้ดใน Python + +หากคุณต้องการ **สร้าง Omni‑directional DataBar** ในโปรเจกต์ Python คำแนะนำนี้จะแสดงวิธีทำและยังสอนวิธี **สร้างภาพบาร์โค้ดด้วย Python** โดยใช้ไลบรารี Aspose.BarCode คุณจะได้สคริปต์พร้อมรันที่สร้างไฟล์ PNG สองไฟล์ที่มีอัตราส่วนภาพต่างกัน + +การสร้าง DataBar ตามสเปค Omni‑directional เป็นความต้องการทั่วไปสำหรับแอปพลิเคชันด้านการค้าปลีกและโลจิสติกส์ บทเรียนนี้ครอบคลุมการติดตั้ง การกำหนดค่า X‑dimension การปรับอัตราส่วนภาพ และการบันทึกภาพขั้นสุดท้าย ไม่ต้องพึ่งบริการภายนอก; ทุกอย่างทำงานแบบออฟไลน์ + +## สิ่งที่คุณต้องมี + +ก่อนเริ่มทำตามขั้นตอน ให้ตรวจสอบว่าคุณมี: + +* Python 3.8 หรือใหม่กว่า ติดตั้งบนเครื่องของคุณ +* เข้าถึงเทอร์มินัลหรือ command prompt +* สิทธิ์การเขียนในโฟลเดอร์ที่ภาพบาร์โค้ดจะถูกบันทึก + +ไลบรารีภายนอกที่จำเป็นเพียงอย่างเดียวคือ **Aspose.BarCode for Python via .NET** ซึ่งรองรับประเภท Omni‑directional DataBar โดยอัตโนมัติ + +## ขั้นตอนที่ 1: ติดตั้ง Aspose.BarCode for Python + +Aspose.BarCode มีคลาส `BarcodeGenerator` ที่ใช้ในโค้ดตัวอย่าง ติดตั้งแพคเกจด้วย `pip`: + +```bash +pip install aspose-barcode +``` + +แพคเกจนี้รวมไบน์ดิงของ .NET runtime ที่จำเป็นไว้แล้ว คุณจึงไม่ต้องติดตั้ง .NET SDK แยกต่างหาก + +## ขั้นตอนที่ 2: นำเข้าไลบรารีและสร้าง generator + +บรรทัดแรกของสคริปต์สร้าง generator สำหรับ stacked Omni‑directional DataBar ค่า GTIN‑14 `(01)12345678901231` ถูกใช้เป็นข้อมูลตัวอย่าง + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*ทำไมขั้นตอนนี้สำคัญ*: ค่าคงที่ `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` บอกไลบรารีให้เข้ารหัสค่าเป็น Omni‑directional DataBar ซึ่งเป็นรูปแบบที่เครื่องสแกนจุดขายหลายเครื่องต้องการ + +## ขั้นตอนที่ 3: ตั้งค่า X‑dimension (ความกว้างโมดูล) + +X‑dimension กำหนดความกว้างของโมดูลบาร์ที่เล็กที่สุด ค่า `2` พิกเซลให้บาร์โค้ดที่ชัดเจนและอ่านง่ายโดยไม่ทำให้ไฟล์ใหญ่เกินไป + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*ทำไมขั้นตอนนี้สำคัญ*: การปรับ X‑dimension ช่วยให้คุณสมดุลระหว่างความอ่านง่ายและขนาดภาพ X‑dimension ที่เล็กเกินไปอาจทำให้บาร์โค้ดแสดงผลไม่ดีบนเครื่องพิมพ์ความละเอียดต่ำ + +## ขั้นตอนที่ 4: กำหนดอัตราส่วนภาพและบันทึกภาพแรก + +อัตราส่วนภาพมีผลต่อความสูงรวมของ DataBar เมื่อเทียบกับความกว้าง อัตราส่วน `15` ให้สไตล์ที่กระชับ + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **เคล็ดลับ**: ใช้ `pathlib.Path` เพื่อสร้างเส้นทางเอาต์พุต ซึ่งจะสร้างโฟลเดอร์ที่ขาดหายไปโดยอัตโนมัติ + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## ขั้นตอนที่ 5: เปลี่ยนอัตราส่วนภาพเพื่อสไตล์ที่สองและบันทึกภาพอีกหนึ่งไฟล์ + +การสลับอัตราส่วนเป็น `30` จะได้บาร์โค้ดที่สูงขึ้น ซึ่งอาจจำเป็นสำหรับฮาร์ดแวร์สแกนเนอร์บางรุ่น + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*ทำไมขั้นตอนนี้สำคัญ*: ร้านค้าต่าง ๆ และอุปกรณ์สแกนมีข้อจำกัดขนาดที่แตกต่างกัน การให้ทั้งสองอัตราส่วนในสคริปต์เดียวทำให้คุณสร้างสไตล์ที่ต้องการโดยไม่ต้องทำซ้ำโค้ด + +## สคริปต์เต็ม – สร้าง Omni‑directional DataBar และภาพบาร์โค้ดใน Python + +ด้านล่างเป็นตัวอย่างที่ทำงานได้ครบถ้วนซึ่งรวมทุกขั้นตอนก่อนหน้า บันทึกเป็น `generate_databar.py` แล้วรันด้วย `python generate_databar.py` + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### ผลลัพธ์ที่คาดหวัง + +การรันสคริปต์จะสร้างไฟล์ต่อไปนี้: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +ทั้งสองภาพแสดง Omni‑directional DataBar ที่ถูกต้องและสามารถสแกนได้ด้วยอุปกรณ์ค้าปลีกมาตรฐาน + +![ตัวอย่างการสร้าง omni directional databar barcode image ใน Python](example_databar.png "สร้าง omni directional databar barcode image python") + +*ภาพด้านบนเป็นเพียงตัวอย่างเพื่อแสดงไฟล์ PNG สองไฟล์ที่บันทึกไว้* + +## การจัดการปัญหาทั่วไป + +| ปัญหา | สาเหตุ | วิธีแก้ | +|-------|--------|-----| +| `ImportError: No module named aspose` | Aspose.BarCode ยังไม่ได้ติดตั้งหรือติดตั้งในสภาพแวดล้อมอื่น | เปิดใช้งาน virtual environment ที่ถูกต้องและรัน `pip install aspose-barcode` | +| `PermissionError` ขณะบันทึก | สคริปต์ไม่มีสิทธิ์เขียนในโฟลเดอร์เป้าหมาย | เลือกไดเรกทอรีที่คุณเป็นเจ้าของหรือรันสคริปต์ด้วยสิทธิ์ที่เหมาะสม | +| บาร์โค้ดสแกนไม่ผ่าน | X‑dimension ต่ำเกินไปหรืออัตราส่วนภาพไม่เข้ากับสแกนเนอร์ | เพิ่มค่า `x_dimension.pixels` เป็น 3 หรือ 4 และลองค่า `aspect_ratio` ต่าง ๆ (เช่น 20, 25) | +| ขาด .NET runtime | Aspose.BarCode ต้องการ .NET runtime บน Windows/Linux | ติดตั้ง .NET runtime ล่าสุดจากเว็บไซต์ Microsoft; คู่มือแพคเกจมีคำแนะนำตามแพลตฟอร์ม | + +## การขยายตัวอย่าง + +คุณสามารถปรับสคริปต์ให้สร้าง DataBar ประเภทอื่น (เช่น `DATABAR_STACKED`, `DATABAR_EXPANDED`) โดยเปลี่ยนค่าคงที่ `EncodeTypes` ตามต้องการ: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +หากต้องการฝังบาร์โค้ดลงใน PDF, Aspose.PDF for Python สามารถนำเข้าไฟล์ PNG โดยตรง หรือใช้เมธอด `save` พร้อม `BarCodeImageFormat.Pdf` + +## สรุป + +บทเรียนนี้แสดงวิธี **สร้าง omni directional databar** และวิธี **สร้าง barcode image python** ด้วย Aspose.BarCode ตอนนี้คุณมีสคริปต์ที่ทำงานได้ครบถ้วนซึ่งสร้าง PNG สองไฟล์ที่มีอัตราส่วนภาพต่างกัน จัดการกับปัญหาที่พบบ่อย และสามารถขยายไปยังรูปแบบบาร์โค้ดอื่นได้ + +ต่อไปลองสร้าง QR code, ฝังบาร์โค้ดลงในใบแจ้งหนี้ PDF, หรือทำการประมวลผลแบบแบตช์สำหรับแคตตาล็อกสินค้าใหญ่ ทุกหัวข้อนี้ต่อยอดจากแพทเทิร์น `BarcodeGenerator` ที่แสดงในที่นี้ ขอให้สนุกกับการเขียนโค้ด! + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่นในโปรเจกต์ของคุณ + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to create barcode image and render it in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/thai/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/thai/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..0ab265639 --- /dev/null +++ b/barcode/thai/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,252 @@ +--- +category: general +date: 2026-08-12 +description: วิธีสร้างบาร์โค้ดอย่างรวดเร็วด้วย Python. เรียนรู้การสร้างบาร์โค้ดจากข้อมูลและส่งออกภาพบาร์โค้ดด้วยไลบรารีเดียว. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: th +lastmod: 2026-08-12 +og_description: วิธีสร้างบาร์โค้ดใน Python ด้วย Aspose.BarCode. ทำตามคำแนะนำนี้เพื่อสร้างบาร์โค้ดจากข้อมูลและส่งออกภาพบาร์โค้ดเป็น + PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: วิธีสร้างบาร์โค้ดใน Python – คู่มือเร็วและเชื่อถือได้ +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: วิธีสร้างบาร์โค้ดใน Python – คู่มือขั้นตอนเต็มรูปแบบ +url: /th/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีสร้างบาร์โค้ดใน Python – คู่มือขั้นตอนเต็ม + +หากคุณต้องการ **วิธีสร้างบาร์โค้ด** ในแอปพลิเคชัน Python นี้ คู่มือจะแสดงโค้ดที่คุณต้องการอย่างแม่นยำ คุณจะได้เรียนรู้การ **สร้างบาร์โค้ดจากข้อมูล**, ปรับลักษณะของมัน, และ **ส่งออกภาพบาร์โค้ด** เป็นไฟล์ PNG—ทั้งหมดในโค้ดไม่เกินสิบบรรทัด + +การสร้างบาร์โค้ดอาจรู้สึกเหมือนเป็นเรื่องแยกจากตรรกะธุรกิจอื่น ๆ ของคุณ แต่ด้วยไลบรารีเดียวคุณสามารถทำให้กระบวนการนี้ทำงานร่วมกับโค้ดฐานที่มีอยู่ได้อย่างราบรื่น ในส่วนต่อไปนี้คุณจะได้เห็นตัวอย่างที่ทำงานได้เต็มรูปแบบ เข้าใจว่าทำไมแต่ละบรรทัดจึงสำคัญ และค้นพบการปรับเปลี่ยนทั่วไป เช่น การเปลี่ยนความกว้างของโมดูลหรือการวาดบาร์โค้ดแบบโครงร่างเท่านั้น + +## วิธีสร้างบาร์โค้ดด้วยไลบรารี Aspose.BarCode + +ไลบรารี Aspose.BarCode สำหรับ Python (ผ่าน .NET) มี API ที่ตรงไปตรงมาสำหรับสัญลักษณ์หลายประเภท รวมถึงบาร์โค้ด Planet ที่ใช้ในคู่มือนี้ ก่อนเริ่มต้นให้แน่ใจว่าคุณได้ติดตั้งแพคเกจแล้ว: + +```bash +pip install aspose-barcode +``` + +> **เคล็ดลับมืออาชีพ:** ใช้ virtual environment เพื่อหลีกเลี่ยงความขัดแย้งของเวอร์ชันกับโปรเจกต์อื่น + +### 1. นำเข้าคลาสที่จำเป็น + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +การนำเข้าเหล่านี้ทำให้คุณเข้าถึงคลาส generator, enumeration ของประเภทบาร์โค้ด, และ enum ของรูปแบบภาพที่ใช้เมื่อบันทึกผลลัพธ์ + +### 2. สร้างบาร์โค้ดจากข้อมูล + +ขั้นตอนแรกคือการ **สร้างบาร์โค้ดจากข้อมูล** ตัวสร้าง `BarcodeGenerator` รับสัญลักษณ์และสตริงดิบที่คุณต้องการเข้ารหัส + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +ค่า `EncodeTypes.Planet` เลือกบาร์โค้ด Planet ส่วน `"123456"` คือข้อมูลที่จะปรากฏในภาพสุดท้าย + +### 3. ปรับ X‑dimension (ความกว้างของโมดูล) + +X‑dimension ควบคุมความกว้างของแต่ละโมดูลของบาร์โค้ด (แถบบาง) การตั้งค่าเป็น 4 พิกเซลให้ภาพที่ชัดเจนและอ่านง่ายโดยไม่ทำให้ไฟล์ใหญ่เกินไป + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **ทำไมจึงสำคัญ:** X‑dimension ที่ใหญ่ขึ้นช่วยเพิ่มความน่าเชื่อถือในการสแกนบนเครื่องพิมพ์ความละเอียดต่ำ ในขณะที่ค่าที่เล็กลงช่วยลดขนาดไฟล์สำหรับการใช้งานบนเว็บ + +### 4. ส่งออกภาพบาร์โค้ด (สไตล์เติมเต็ม) + +ตอนนี้คุณสามารถ **ส่งออกภาพบาร์โค้ด** ด้วยเมธอด `save` ตัวอย่างบันทึกเป็นไฟล์ PNG แต่คุณสามารถเลือก JPEG, BMP หรือ TIFF ได้โดยเปลี่ยนค่า enum `BarCodeImageFormat` + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +ไฟล์ `PlanetFilled.png` มีบาร์โค้ด Planet ที่เติมเต็มเต็มรูปแบบ พร้อมสำหรับการพิมพ์หรือฝังใน PDF + +### 5. สร้าง generator ที่สองสำหรับบาร์โค้ดแบบโครงร่างเท่านั้น + +หากคุณต้องการเวอร์ชันโครงร่าง (แถบว่าง) คุณต้องสร้าง generator ใหม่ เนื่องจากไม่สามารถสลับค่า `filled_bars` หลังจากบันทึกภาพได้ + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. ใช้การตั้งค่า X‑dimension เดียวกัน + +เมื่อคุณสร้าง generator ที่สอง คุณต้องทำซ้ำการตั้งค่าภาพใด ๆ ที่ต้องการให้สอดคล้องกัน + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. ปิดการเติมแถบสำหรับบาร์โค้ดแบบโครงร่าง + +การตั้งค่า `filled_bars` เป็น `False` บอก renderer ให้วาดเฉพาะโครงร่างของแต่ละโมดูล ทำให้ได้ภาพที่เบากว่าและอาจเป็นประโยชน์สำหรับการออกแบบ + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. ส่งออกภาพบาร์โค้ดแบบโครงร่าง + +สุดท้าย **ส่งออกภาพบาร์โค้ด** อีกครั้ง ครั้งนี้บันทึกเป็นเวอร์ชันโครงร่าง + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +ตอนนี้คุณมีไฟล์ PNG สองไฟล์: หนึ่งไฟล์ที่มีแถบเต็ม (`PlanetFilled.png`) และอีกไฟล์ที่มีเพียงโครงร่าง (`PlanetEmpty.png`) + +## ส่งออกภาพบาร์โค้ดในรูปแบบอื่น (ทางเลือก) + +เมธอด `save` รองรับหลายรูปแบบ เพื่อส่งออกเป็น JPEG ด้วยคุณภาพ 90 %: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +หากต้องการพื้นหลังโปร่งใสสำหรับการใช้งานบนเว็บ ให้เลือก PNG พร้อมช่อง alpha: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## การปรับเปลี่ยนทั่วไปและกรณีขอบ + +| Scenario | Change needed | Code snippet | +|----------|---------------|--------------| +| **Different symbology** (e.g., QR) | Use a different `EncodeTypes` value | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Custom foreground color** | Set `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Higher resolution** | Increase DPI via `image_width` and `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Large data strings** | Ensure data length fits the symbology spec | Validate length before creating the generator | + +> **ระวัง:** การใส่ข้อมูลที่ยาวเกินกว่าขนาดสูงสุดของสัญลักษณ์ที่เลือกจะทำให้เกิดข้อยกเว้นใน runtime ควรตรวจสอบความยาวของสตริงหรือจับ `ArgumentException` เสมอ + +## ตัวอย่างเต็มที่สามารถรันได้ + +ด้านล่างเป็นสคริปต์ทั้งหมดที่คุณสามารถคัดลอก‑วางลงในไฟล์ชื่อ `generate_planet_barcode.py` ปรับ `YOUR_DIRECTORY` ให้เป็นโฟลเดอร์ที่มีอยู่บนเครื่องของคุณ + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +การรันสคริปต์นี้จะสร้างไฟล์ PNG สองไฟล์ในไดเรกทอรีที่ระบุ ตรวจสอบผลลัพธ์โดยเปิดภาพในโปรแกรมดูภาพใดก็ได้; ทั้งสองไฟล์ควรแสดงบาร์โค้ด Planet ที่เข้ารหัสสตริง `123456` + +## สรุป + +คุณได้เรียนรู้ **วิธีสร้างบาร์โค้ด** ใน Python ด้วย Aspose.BarCode, **สร้างบาร์โค้ดจากข้อมูล**, และ **ส่งออกภาพบาร์โค้ด** ทั้งในสไตล์เติมเต็มและโครงร่าง รูปแบบเดียวกันนี้สามารถนำไปใช้กับสัญลักษณ์อื่น ๆ, รูปแบบภาพ, และการปรับแต่งด้านภาพ ทำให้คุณมีพื้นฐานที่ยืดหยุ่นสำหรับฟีเจอร์ที่เกี่ยวกับบาร์โค้ดใด ๆ ในแอปพลิเคชันของคุณ + +### ขั้นตอนต่อไป + +* สำรวจสัญลักษณ์อื่น ๆ เช่น QR, Code‑128, หรือ DataMatrix โดยเปลี่ยน `EncodeTypes.Planet` เป็นค่าที่ต้องการ +* ผสานไฟล์ PNG ที่สร้างขึ้นเข้าไปในรายงาน PDF ด้วยไลบรารีเช่น `ReportLab` หรือ `PyPDF2` +* ทดลองใช้ค่าตัวแปร X‑dimension แบบไดนามิกเพื่อปรับขนาดบาร์โค้ดตามความละเอียดหน้าจอหรือ DPI ของเครื่องพิมพ์ + +ขอให้เขียนโค้ดสนุกและปรับตัวอย่างให้ตรงกับความต้องการของโปรเจกต์ของคุณได้เลย! + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานครบถ้วนพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานแบบต่าง ๆ ในโปรเจกต์ของคุณเอง + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/turkish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/turkish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..f8ca1a64a --- /dev/null +++ b/barcode/turkish/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-08-12 +description: Tam piksel boyutuyla barkod oluşturmayı gösteren barkod oluşturucu örneği. + Modül genişliğini, çubuk yüksekliğini ayarlamayı öğrenin ve Planet barkodları oluşturun. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: tr +lastmod: 2026-08-12 +og_description: Barkod oluşturucu örneği, tam piksel boyutlarıyla barkod oluşturmanın + nasıl yapılacağını gösterir. Planet ve RM4SCC kodları için modül genişliğini ve + çubuk yüksekliğini kontrol etmek üzere bu kılavuzu izleyin. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: barkod oluşturucu örneği – C#'ta piksel boyutunu özelleştir +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Barkod oluşturucu örneği – özel piksel boyutları için adım adım kılavuz +url: /tr/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# barkod oluşturucu örneği – özel piksel boyutları için adım adım kılavuz + +Eğer her pikseli kontrol etmenizi sağlayan bir **barcode generator example** istiyorsanız, bu kılavuz tam olarak nasıl yapılacağını gösterir. Modül genişliğini ayarlamayı, sabit bir çubuk yüksekliği tanımlamayı ve hem Planet hem de RM4SCC barkodlarını öngörülebilir boyutlarla üretmeyi öğreneceksiniz. + +Çoğu geliştirici, “barkod nasıl üretilir” sorusuna yanıt ararken, her ekran veya yazıcıda aynı görünen görüntüler elde etmekte zorlanır. Aşağıdaki kod parçacıkları, Aspose.BarCode for .NET kütüphanesinin piksel‑seviyesindeki parametrelerini ortaya çıkararak bu sorunu çözer; böylece tahmin yürütmeden tutarlı çıktı üretebilirsiniz. + +## Öğrenecekleriniz + +* Gerekli NuGet paketini nasıl kuracağınızı. +* Otomatik hesaplanan yükseklikle bir Planet barkodu nasıl oluşturacağınızı. +* Açıkça 100 piksel yüksekliğiyle bir Planet barkodu nasıl oluşturacağınızı. +* Aynı açık yüksekliği kullanarak bir RM4SCC barkodu nasıl oluşturacağınızı. +* **barcode pixel size**'ın tarama güvenilirliği için neden önemli olduğunu. +* Planet barkod görüntüleri oluştururken yaygın sorunları gidermek için ipuçları. + +Yalnızca .NET 6 veya üzeri, temel bir C# geliştirme ortamı ve NuGet paketini çekmek için bir internet bağlantısı gerekir. + +--- + +## barkod oluşturucu örneği – geliştirme ortamını kurma + +Kod yazmaya başlamadan önce Aspose.BarCode kütüphanesinin projenizde mevcut olduğundan emin olun. + +### Aspose.BarCode paketini kurun + +Proje klasörünüzde bir terminal açın ve şu komutu çalıştırın: + +```bash +dotnet add package Aspose.BarCode +``` + +Bu komut, **Aspose.BarCode**'in en son kararlı sürümünü `csproj` dosyanıza ekler. Geri yükleme tamamlandıktan sonra `BarcodeGenerator` sınıfını kullanmaya başlayabilirsiniz. + +> **Pro tip:** .NET 6 veya .NET 7 hedefleyerek en yeni performans iyileştirmelerinden ve varsayılan UTF‑8 işleme avantajlarından yararlanın. + +### Gerekli `using` yönergelerini ekleyin + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Bu ad alanları, öğreticide daha sonra kullanılacak `BarcodeGenerator` sınıfını ve `BarCodeImageFormat` enumunu ortaya çıkarır. + +--- + +## Özel piksel boyutlu barkod nasıl oluşturulur + +Aşağıdaki üç adım, tam **barcode generator example**'ı gösterir. Her adım bir önceki üzerine inşa edilir; böylece tüm bloğu bir console uygulamasına kopyalayıp değiştirmeden çalıştırabilirsiniz. + +### Adım 1 – otomatik hesaplanan yükseklikle bir Planet barkodu oluşturma + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Neden bu şekilde çalışır:** +*`XDimension` özelliği, tek bir barkod modülünün (en küçük siyah veya beyaz eleman) genişliğini tanımlar. `BarHeight` belirtilmediğinde, kütüphane Planet kodları için standart en‑boy oranını koruyan bir yükseklik hesaplar.* + +**Beklenen çıktı:** `PlanetAuto.png` adlı bir PNG dosyası, temiz bir Planet barkodu içerir. Yüksekliği, 4‑piksel modül genişliğine uyum sağlar; genellikle altı karakterlik bir veri için yaklaşık 60 piksel olur. + +### Adım 2 – açıkça 100 piksel yüksekliğiyle bir Planet barkodu oluşturma + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Neden buna ihtiyaç duyabilirsiniz:** +Bazı tarama ekipmanları, güvenilir algılamalar için minimum çubuk yüksekliği bekler. `BarHeight.Pixels` ayarlayarak, kodun uzunluğundan bağımsız olarak her oluşturulan görüntünün bu gereksinimi karşılamasını garantilersiniz. + +**Beklenen çıktı:** `PlanetHeight100.png` aynı veriyi gösterir, ancak çubuklar tam olarak 100 piksel yüksekliğindedir; böylece görsel boyut üzerinde tam kontrol elde edersiniz. + +### Adım 3 – aynı açık yüksekliğiyle bir RM4SCC barkodu oluşturma + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Neden bu önemlidir:** +`EncodeTypes.RM4SCC`, lojistikte kullanılan yığılmış lineer bir barkoddur. Çubuk yüksekliğini Planet barkodu ile aynı seviyeye getirmek, her iki sembolün aynı etiket üzerinde yer alması durumunda toplu işleme sürecini basitleştirir. + +**Beklenen çıktı:** `RM4SCCHeight100.png` mükemmel boyutta bir RM4SCC barkodu gösterir; Planet kodu için ayarladığınız 100‑piksel yüksekliğe eşittir. + +> **Sonuç doğrulaması:** Her PNG'yi bir görüntü görüntüleyicide açın ve siyah çubukların tam 4 piksel genişliğinde ve belirttiğiniz yerde 100 piksel yüksekliğinde olduğundan emin olun. Dosyaları bir barkod tarayıcı uygulamasına da aktararak “123456” kodunu çözdüklerini kontrol edebilirsiniz. + +--- + +## Barkod piksel boyutu ve çubuk yüksekliğini anlama + +### **barcode pixel size** nedir? + +*Pixel size*, tek bir modülü (`XDimension`) temsil eden ekran veya yazıcı piksel sayısını ifade eder. Daha büyük bir pixel size, daha büyük bir barkod üretir; bu, düşük çözünürlüklü tarayıcılar için daha kolay olabilir ancak etiket alanını daha fazla tüketir. + +### `BarHeight` okunabilirliği nasıl etkiler? + +`BarHeight` özelliği, çubukların dikey uzunluğunu kontrol eder. Çoğu 1‑D barkod (Planet ve RM4SCC dahil) için standartlar, 300 dpi'de basıldığında minimum 10 mm yükseklik önerir; bu da yaklaşık 118 piksele denk gelir. Bu değerin altında bir yükseklik ayarlamak, özellikle mobil kameralarla okuma hatalarına yol açabilir. + +### Kütüphanenin yüksekliği otomatik olarak hesaplamasına ne zaman izin vermelisiniz? + +Barkodları yalnızca ekranda göstermek için üretiyorsanız, otomatik hesaplama en‑boy oranını tutarlı tutar ve manuel ayarlama ihtiyacını azaltır. Katı ISO şartlarını karşılaması gereken basılı etiketler için **çubuk yüksekliğini açıkça ayarlamalısınız**. + +--- + +## Planet barkodu oluştururken yaygın tuzaklar ve en iyi uygulamalar + +| Tuzak | Neden olur | Çözüm | +|---------|----------------|-----| +| Çubuklar çok ince veya kalın görünüyor | `XDimension` yüksek çözünürlüklü ekranlarda varsayılan (1 pixel) olarak bırakıldı | Görsel netlik için `XDimension.Pixels` değerini en az 3‑4 olarak ayarlayın | +| Tarayıcı kodu okuyamıyor | `BarHeight` tarayıcının odak uzunluğu için çok küçük | Çoğu mobil tarayıcı için `BarHeight.Pixels` ≥ 100 kullanın | +| Ölçeklendirme sonrası görüntü bulanık | JPEG olarak kaydetmek sıkıştırma artefaktları oluşturur | Kayıpsız çıktı için PNG (`BarCodeImageFormat.Png`) olarak kaydedin | +| Beklenmeyen barkod türü | Yanlış `EncodeTypes` enum değeri | `EncodeTypes.Planet` kullandığınızdan emin olun | + +### Performans hakkında ipucu + +Binlerce barkodu toplu bir işte üretirken tek bir `BarcodeGenerator` örneğini yeniden kullanın ve sadece `CodeText` ile boyut parametrelerini kaydetmeler arasında değiştirin. Bu, iç render nesnelerinin tekrar tekrar tahsis edilmesini önler ve yürütme süresini %30’a kadar azaltabilir. + +--- + +## Tam çalışan örnek – her şeyi bir araya getirin + +Yeni bir console projesi oluşturun (`dotnet new console -n BarcodeDemo`) ve `Program.cs` içeriğini aşağıdaki ile değiştirin: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Programı `dotnet run` ile çalıştırın. Çalıştırma sonrası proje klasöründe üç PNG dosyası bulacaksınız; her biri farklı bir **barcode generator example** senaryosunu gösterir. + +--- + +## Sonraki adımlar ve ilgili konular + +* **Farklı formatlarda barkod nasıl oluşturulur** – 2‑D ihtiyaçlar için `EncodeTypes.Code128`, `EncodeTypes.QR` ve `EncodeTypes.DataMatrix`'i keşfedin. +* **Barkodları PDF'lere gömme** – barkodları doğrudan fatura şablonlarına yerleştirmek için Aspose.BarCode'u Aspose.PDF ile birleştirin. +* **Kullanıcı girdisine göre dinamik barkod boyutu** – hesaplayın + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini ustalaşmanıza ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak tam çalışan kod örnekleri ve adım adım açıklamalar içerir. + +- [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [How to Generate Barcode in Java Create and Set Size for Whole Picture](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [How to create code128 barcode Java and set bar height](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/turkish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/turkish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..a1cb9b1aa --- /dev/null +++ b/barcode/turkish/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-08-12 +description: Python'da Databar barkod düzenini hızlıca yapılandırın. Sütunları, satırları + ayarlamayı ve barkod oluşturucu kütüphanesiyle görüntüleri kaydetmeyi öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: tr +lastmod: 2026-08-12 +og_description: Python'da Databar barkod düzenini yapılandırarak sütunları, satırları + ve görüntü çıktısını kontrol edin. Hazır‑çalıştırılabilir bir çözüm için bu kılavuzu + izleyin. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Python'da Databar barkod düzenini yapılandırma – tam öğretici +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Python'da Databar barkod düzenini yapılandırma – adım adım rehber +url: /tr/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python'da Databar barkod düzenini yapılandırma – adım adım kılavuz + +**Python'da Databar barkod düzenini yapılandırmanız** gerekiyorsa, bu kılavuz sizi tüm süreç boyunca yönlendirecek. Databar Expanded Stacked barkod için sütun veya satır sayısını nasıl ayarlayacağınızı ve ortaya çıkan görüntüyü barkod oluşturucu kütüphanesine tek bir çağrı ile nasıl kaydedeceğinizi göreceksiniz. + +Kontrol edilen düzen, barkodları dar ambalajlarda, makbuzlarda veya mobil ekranlarda gömmeniz gerektiğinde çok önemlidir. Aşağıdaki bölümlerde gerekli içe aktarmaları, iki düzen seçeneğini (sütunlar ve satırlar) ve temiz bir PNG görüntüsü kaydetmek için en iyi uygulamaları ele alacağız. + +## İhtiyacınız olanlar + +* Python 3.8 ve üzeri +* `aspose.barcode` (veya uyumlu herhangi bir barkod‑oluşturma paketi) yüklü + ```bash + pip install aspose-barcode + ``` +* PNG dosyalarının saklanacağı klasöre yazma izni + +Ek bir dış araç gerekmiyor—kütüphane renderleme, ölçekleme ve görüntü kodlamasını dahili olarak yönetir. + +## Python'da Databar barkod düzenini nasıl yapılandırılır + +Çözümün çekirdeği `BarcodeGenerator` sınıfıdır. Barkod sembolojisini tanımlayan bir `EncodeTypes` enum'ı kabul eder—bu durumda `EncodeTypes.DatabarExpandedStacked`. Üreteci oluşturduktan sonra, `data_bar` parametre nesnesindeki `columns` veya `rows` özelliklerini ayarlayarak düzeni değiştirebilirsiniz. + +### Adım 1: Gerekli sınıfları içe aktarın + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Bu içe aktarmalar, oluşturucuya, Databar tipleri için enumerasyona ve PNG görüntü formatı sabitine erişim sağlar. + +### Adım 2: Databar Expanded Stacked için bir barkod oluşturucu oluşturun + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Why this step?* +`EncodeTypes.DatabarExpandedStacked` kütüphaneye **Databar Expanded Stacked** sembolojisini üretmesini söyler; bu, daha uzun sayısal dizeleri desteklerken kompakt bir alan bırakır. İkinci argüman kodlanacak veridir; Databar spesifikasyonuna uyan herhangi bir dize olabilir. + +### Adım 3: Sütun sayısını ayarlayın (yatay düzen) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** bu işlem için ana ifadedir. Sütun sayısını artırdığınızda barkod yatay olarak yayılır; bu, geniş etiketler için faydalı olabilir. Kütüphane, genel boyutu tutarlı tutmak için modül genişliğini otomatik olarak yeniden hesaplar. + +#### Pro ipucu +Databar Expanded Stacked için maksimum sütun sayısı 8'dir. Sınırın üzerindeki bir değer ayarlandığında maksimuma sınırlanır, ancak girişi önceden doğrulamak daha iyidir. + +### Adım 4: Sütun düzeniyle barkod görüntüsünü kaydedin + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** render edilen barkodu diske yazan eylemdir. PNG kayıpsızdır ve güvenilir tarama için gereken keskin kenarları korur. + +### Adım 5: Aynı barkod türü için ikinci bir oluşturucu oluşturun (satır düzeni) + +Dikey bir yığın tercih ediyorsanız, sütunlar yerine satırlarla çalışırsınız. Aşağıdaki kod aynı değeri yeniden kullanır ancak sütun ve satır ayarlarını karıştırmamak için yeni bir `BarcodeGenerator` örneği oluşturur. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Adım 6: Satır sayısını ayarlayın (dikey düzen) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** barkod modüllerini dikey olarak düzenler. Üç satırlı bir düzen, her bir yığının yüksekliğini azaltır ve barkodu dar makbuzlar veya mobil ekranlar için uygun hâle getirir. + +#### Kenar durumu +`rows` değerini 1 olarak ayarlarsanız, kütüphane tek satırlı bir Databar (standart Databar eşdeğeri) üretir. 1'in altındaki değerler yok sayılır ve varsayılan (1 satır) olarak sıfırlanır. + +### Adım 7: Satır düzeniyle barkod görüntüsünü kaydedin + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Yine, çıktıyı net tutmak için PNG kullanarak **save barcode image** yapıyoruz. + +## Tam çalıştırılabilir örnek + +Tüm parçaları bir araya getirerek, herhangi bir Python projesine ekleyebileceğiniz bağımsız bir betik elde edersiniz. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Beklenen çıktı** + +Betik çalıştırıldığında iki PNG dosyası oluşturulur: + +* `output/ExpandedCols4.png` – dört sütun boyunca uzatılmış bir barkod +* `output/ExpandedRows3.png` – üç satıra sıkıştırılmış bir barkod + +Her iki görüntü de herhangi bir görüntü görüntüleyicide açılabilir veya doğrudan PDF faturalarına, etiket şablonlarına veya web sayfalarına aktarılabilir. + +## Yaygın sorular ve sorun giderme + +| Question | Answer | +|----------|--------| +| *Barkod bulanık görünürse ne yapmalıyım?* | `save` metodunu çağırmadan önce `barcode_generator.parameters.image_width` ve `image_height` ayarlarını yaparak görüntü çözünürlüğünü artırın. | +| *Başka görüntü formatları kullanabilir miyim?* | Evet. Gerektiği gibi `BarCodeImageFormat.Png` yerine `Jpeg`, `Bmp` veya `Gif` kullanın. | +| *Veri uzunluğu için bir limit var mı?* | Databar Expanded Stacked, en fazla 74 sayısal karakteri destekler. Limiti aşmak bir `ArgumentException` hatası oluşturur. | +| *Ön plan rengini nasıl değiştiririm?* | `barcode_generator.parameters.barcode.color = Color.Blue` ifadesini kullanın (`System.Drawing.Color`'ı içe aktarın). | +| *Sütunları ve satırları birleştirebilir miyim?* | Hayır. API, sütunları ve satırları karşılıklı olarak dışlayıcı düzen modları olarak değerlendirir. Her barkod örneği için birini seçin. | + +## Sonraki adımlar + +Artık **Databar barkod düzenini yapılandırabildiğinize** göre, aşağıdaki ilgili konuları keşfetmeyi düşünün: + +* **Metin altyazıları ekleyin** – kodlanmış değeri görüntünün altına göstermek için `barcode_generator.parameters.barcode.code_text` kullanın. +* **Barkodu bir PDF'e gömün** – oluşturulan PNG'yi `aspose.pdf` ile birleştirerek yazdırılabilir belgeler oluşturun. +* **Dinamik boyutlandırma** – çalışma zamanında etiket boyutlarına göre optimal sütun veya satır sayısını hesaplayın. +* **Toplu işleme** – ürün kodlarının bir CSV'si üzerinde döngü yaparak barkod görüntüleri kütüphanesini otomatik olarak oluşturun. + +Farklı sütun ve satır değerleriyle deneme yaparak bunların hedef cihazlarınızda tarama güvenilirliğini nasıl etkilediğini görün. Ne kadar çok test ederseniz, barkod boyutu, okunabilirlik ve alan kısıtlamaları arasındaki dengeyi o kadar iyi anlarsınız. + +--- + +*Kodlamaktan keyif alın! Bu kılavuzu faydalı bulduysanız, ekip arkadaşlarınızla paylaşın veya karşılaştığınız düzen zorlukları hakkında bir yorum bırakın.* + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, adım adım açıklamalarla birlikte tam çalışan kod örnekleri içerir; böylece ek API özelliklerini öğrenebilir ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfedebilirsiniz. + +- [DotCode barkod görüntüsü oluşturma – satırlar ve sütunlar (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [c# ile barkod görüntüsü oluşturma – Codablock F Satır ve Sütunlarını Yapılandırma](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [Tek Boyutlu Databar Barkod Yükseklik Ayarı](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/turkish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/turkish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..71fcd9bf8 --- /dev/null +++ b/barcode/turkish/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: BarCodeGenerator kullanarak C#'de barkod resmi oluşturun. DataBar nasıl + oluşturulur, barkod resim boyutu nasıl kontrol edilir ve birden fazla barkod verimli + bir şekilde nasıl üretilir öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: tr +lastmod: 2026-08-12 +og_description: BarCodeGenerator ile C#’ta barkod resmi oluşturun. Bu öğreticide adım + adım DataBar kodları nasıl oluşturulur, barkod görüntüsü boyutu nasıl ayarlanır + ve birden fazla barkod nasıl üretilir gösterilmektedir. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: C#'ta barkod resmi oluşturma – tam BarCodeGenerator rehberi +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: BarCodeGenerator ile C#'ta barkod resmi oluştur +url: /tr/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# ile BarCodeGenerator kullanarak barkod resmi oluşturma + +Bir .NET uygulamasında **barkod resmi oluşturmanız** gerekiyorsa, bu kılavuz `BarCodeGenerator` sınıfını kullanarak bunu tam olarak nasıl yapacağınızı gösterir. Perakende POS sistemi ya da envanter takibi aracı oluşturuyor olun, DataBar sembolleri oluşturmayı, barkod resmi boyutunu kontrol etmeyi ve tek bir çalıştırmada birden fazla barkod üretmeyi öğreneceksiniz. + +Ayrıca **barcode generator c#** API'sinin boyutları ayarlamanıza, çıktı formatlarını değiştirmenize ve geçersiz veri dizeleri gibi uç durumları ele almanıza nasıl izin verdiğini keşfedeceksiniz. Öğreticinin sonunda, tekrarlayan kod yazmadan güvenle **birden fazla barkod oluşturabilirsiniz**. + +## Önkoşullar + +- .NET 6.0 veya daha yeni bir sürüm yüklü +- Bir geliştirme ortamı (Visual Studio, Rider veya VS Code) +- Aspose.BarCode for .NET NuGet paketi (veya `BarCodeGenerator` sağlayan herhangi bir uyumlu kütüphane) + +Paketi eklemek için: + +```bash +dotnet add package Aspose.BarCode +``` + +## Bu öğreticinin kapsamı + +1. DataBar Omni‑directional kodlaması için bir **barcode generator c#** örneği oluşturma. +2. X‑dimension ve bar yüksekliğini değiştirerek **barkod resmi boyutunu** ayarlama. +3. Farklı yüksekliklerde **birden fazla barkod oluşturmak** için bir döngü kullanma. +4. Görüntüleri PNG dosyaları olarak kaydetme ve çıktıyı doğrulama. + +Tüm kod parçacıkları eksiksizdir ve yeni bir konsol projesine kopyala‑yapıştır yapmaya hazırdır. + +![Create barcode image example](barcode-example.png){alt="Barkod resmi oluşturma örneği"} + +## Adım 1: Üreteci başlatma – barkod resmi temelleri + +İlk adım, istenen semboloji ile `BarCodeGenerator` örneğini oluşturmaktır. DataBar Omni‑directional sembolü için `EncodeTypes.DatabarOmniDirectional` kullanırsınız. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Neden önemli:** Üreteci örneklemek, kodlama kurallarını ve veri yükünü tanımlar. Doğru `EncodeTypes` değerini atlamanız durumunda kütüphane desteklenmeyen bir barkod üretir veya bir istisna fırlatır. + +## Adım 2: X‑dimension ve bar yüksekliğini yapılandırma – barkod resmi boyutunu kontrol etme + +Bir barkodun görsel boyutu iki parametre tarafından belirlenir: + +| Parametre | Ne kontrol eder | Tipik aralık | +|-----------|------------------|---------------| +| `x_dimension.pixels` | En küçük modülün (“nokta”) genişliği | 1 – 4 px | +| `bar_height.pixels` | Dikey çubukların yüksekliği | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Pro ipucu:** Daha küçük bir X‑dimension, daha yüksek çözünürlüklü bir görüntü sağlar ancak düşük kaliteli yazıcılarda taramayı zorlaştırabilir. Değeri, hedef tarama ekipmanınıza göre ayarlayın. + +## Adım 3: İlk barkodu kaydet – 30 px yükseklik için barkod resmi oluşturma + +Şimdi görüntüyü oluşturabilir ve diske yazabilirsiniz. `Save` yöntemi bir dosya yolu ve bir görüntü formatı enum'ı alır. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Beklenen sonuç:** `C:\Barcodes` içinde `Databar30.png` adlı bir PNG dosyası oluşur. Dosyayı açtığınızda net, yüksek kontrastlı bir DataBar Omni‑directional sembolü görürsünüz. + +## Adım 4: Yüksekliği değiştir ve ek görüntüler oluştur – birden fazla barkod oluşturma + +Farklı boyutlarda **birden fazla barkod oluşturmak** için sadece `BarHeight` özelliğini değiştirip `Save` metodunu tekrar çağırmanız yeterlidir. Bu, üreticiyi yeniden örneklemeden kaçınır ve bellek ile CPU süresinden tasarruf sağlar. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Neden işe yarar:** `BarCodeGenerator` nesnesi tüm yapılandırma durumunu tutar. Tek bir özelliği değiştirmek, bir sonraki `Save` çağrısı için render motorunu günceller ve **birden fazla barkodu** verimli bir şekilde oluşturmanıza olanak tanır. + +## Adım 5: İleri – özel veri ile DataBar nasıl oluşturulur + +Yukarıdaki örnek statik bir GS1 yükü kullanıyor. Gerçek dünyada genellikle değişken ürün tanımlayıcıları eklemeniz gerekir. Kütüphane, DataBar spesifikasyonuna uyan herhangi bir dizeyi kabul eder. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Önemli nokta:** `generator.CodeText` ayarlanması, nesneyi yeniden oluşturmadan kodlanmış veriyi günceller. Bu, büyük veri kümeleriyle çalışırken önerilen **how to generate databar** (databar nasıl oluşturulur) desenidir. + +## Adım 6: Doğrulama ve sorun giderme – doğru barkod resmi boyutunu sağlama + +Görüntüleri oluşturduktan sonra, boyutların beklentilerinize uygun olduğunu programlı olarak doğrulamak isteyebilirsiniz. `System.Drawing` içindeki `Image` sınıfı dosyayı okuyabilir ve boyutunu raporlayabilir. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Eğer yükseklik ayarladığınız değeri yansıtmıyorsa, kontrol edin: + +- **X‑dimension**: Çok küçük bir değer, renderlayıcının yüksekliği yuvarlamasına neden olabilir. +- **Image format**: Bazı formatlar (ör. JPEG) kaydetme sırasında sıkıştırma uygular ve piksel boyutlarını değiştirebilir. PNG tam boyutları korur. + +## Adım 7: Barkod resmi boyutu ve performans için en iyi uygulamalar + +| Öneri | Sebep | +|----------------|--------| +| Çoğu tarayıcı için `x_dimension.pixels` değerini 2 – 3 px arasında tutun. | Okunabilirlik ile dosya boyutunu dengeler. | +| Görüntü basılacaksa kayıpsız çıktı için PNG kullanın. | Tam boyutları ve keskin kenarları garanti eder. | +| Çok sayıda barkod üretirken tek bir `BarCodeGenerator` örneğini yeniden kullanın. | Nesne tahsis yükünü azaltır. | +| `CodeText`'e atamadan önce girdi dizesini GS1 standardına göre doğrulayın. | Çalışma zamanı istisnalarını ve geçersiz taramaları önler. | +| Oluşturulan görüntüleri net bir adlandırma kuralı ile ayrı bir klasörde saklayın (ör. `Databar_{GTIN}.png`). | Sonraki işlemeyi ve denetim izlerini basitleştirir. | + +## Tam çalışan örnek + +Aşağıda, başlatmadan doğrulamaya kadar tüm adımları içeren tam program bulunmaktadır. Kodu yeni bir konsol projesine kopyalayın ve çalıştırın. + + + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [Barkod resmi oluştur – GS1 Kupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode barkod resmi oluştur – satırlar ve sütunlar (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [ITF-14 için Barkod Sessiz Bölgesi Nasıl Oluşturulur – Aspose.BarCode for .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/turkish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/turkish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..175ec5309 --- /dev/null +++ b/barcode/turkish/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-08-12 +description: Python ile çok yönlü databar oluşturun ve Aspose.BarCode kullanarak Python’da + barkod resmi oluşturmayı öğrenin. Tam bir çözüm için adım adım rehberi izleyin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: tr +lastmod: 2026-08-12 +og_description: Python ile çok yönlü bir databar oluşturun ve dakikalar içinde bir + barkod resmi üretin. Bu öğretici, eksiksiz ve çalıştırılabilir bir örnek gösterir. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Omni yönlü veri çubuğu oluşturma – tam Python rehberi +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Python'da çok yönlü databar ve barkod resmi oluşturun +url: /tr/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Omni yönlü databar ve barkod görüntüsü oluşturma Python'da + +If you need to **create omni directional databar** in a Python project, this guide shows you how to do it and also how to **create barcode image python** using the Aspose.BarCode library. You will get a ready‑to‑run script that produces two PNG files with different aspect ratios. + +Generating a DataBar that follows the Omni‑directional specification is a common requirement for retail and logistics applications. The tutorial covers installation, configuration of the X‑dimension, adjustment of the aspect ratio, and saving the final images. No external services are required; everything runs locally. + +## Gerekenler + +* Python 3.8 veya daha yeni bir sürümün makinenizde kurulu olması. +* Bir terminal veya komut istemcisine erişim. +* Barkod görüntülerinin kaydedileceği klasöre yazma izni. + +The only third‑party dependency is **Aspose.BarCode for Python via .NET**, which supports the Omni‑directional DataBar type out of the box. + +## Adım 1: Aspose.BarCode for Python'ı Kurun + +Aspose.BarCode örnek kodda kullanılan `BarcodeGenerator` sınıfını sağlar. Paketi `pip` ile kurun: + +```bash +pip install aspose-barcode +``` + +The package includes the necessary .NET runtime bindings, so you do not need to install the .NET SDK separately. + +## Adım 2: Kütüphaneyi içe aktarın ve oluşturucuyu yaratın + +The first line of the script creates a generator for a stacked Omni‑directional DataBar. The GTIN‑14 value `(01)12345678901231` is used as sample data. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Bu adımın önemi*: `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` sabiti, kütüphaneye değeri birçok satış noktası tarayıcısı tarafından gereken format olan Omni‑directional DataBar olarak kodlamasını söyler. + +## Adım 3: X‑dimension'ı (modül genişliği) ayarlayın + +The X‑dimension defines the width of the smallest bar module. A value of `2` pixels produces a clear, readable barcode without excessive file size. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Bu adımın önemi*: X‑dimension'ı ayarlamak, okunabilirlik ile görüntü boyutları arasında denge kurmanıza olanak tanır. Çok küçük bir X‑dimension, düşük çözünürlüklü yazıcılarda kötü görünebilir. + +## Adım 4: En‑boy oranını yapılandırın ve ilk görüntüyü kaydedin + +The aspect ratio influences the overall height of the DataBar relative to its width. An aspect ratio of `15` creates a compact visual style. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Pro ipucu**: Çıktı yolunu oluşturmak için `pathlib.Path` kullanın; bu, eksik dizinleri otomatik olarak oluşturur. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Adım 5: İkinci bir görsel stil için en‑boy oranını değiştirin ve başka bir görüntüyü kaydedin + +Switching the aspect ratio to `30` produces a taller barcode that may be required by specific scanner hardware. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Bu adımın önemi*: Farklı perakendeciler ve tarama cihazları farklı boyut kısıtlamalarına sahiptir. Tek bir script içinde her iki en‑boy oranını sunmak, kodu çoğaltmadan ihtiyacınız olan tam stili üretmenizi sağlar. + +## Tam script – omni directional databar ve barcode image python oluşturma + +Below is the complete, runnable example that incorporates all previous steps. Save it as `generate_databar.py` and run it with `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Beklenen çıktı + +Running the script creates the following files: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Both images display a valid Omni‑directional DataBar that can be scanned by standard retail equipment. + +![Python'da omni directional databar barkod görüntüsü oluşturma örneği](example_databar.png "omni directional databar barkod görüntüsü oluşturma python") + +*Yukarıdaki görüntü, kaydedilen iki PNG dosyasını gösteren bir yer tutucudur.* + +## Yaygın sorunları ele alma + +| Issue | Reason | Fix | +|-------|--------|-----| +| `ImportError: No module named aspose` | Aspose.BarCode yüklü değil veya farklı bir ortamda yüklü. | Doğru sanal ortamı etkinleştirin ve `pip install aspose-barcode` komutunu çalıştırın. | +| `PermissionError` when saving | Script hedef klasöre yazma izni yok. | Sahip olduğunuz bir dizin seçin veya script'i uygun yetkilerle çalıştırın. | +| Barcode does not scan | X‑dimension çok düşük veya en‑boy oranı tarayıcıyla uyumsuz. | `x_dimension.pixels` değerini 3 veya 4'e artırın ve farklı `aspect_ratio` değerlerini (ör. 20, 25) deneyin. | +| Missing .NET runtime | Aspose.BarCode Windows/Linux'ta .NET çalışma zamanına bağımlıdır. | Microsoft sitesinden en son .NET çalışma zamanını kurun; paket dokümantasyonu platform‑spesifik rehberlik sağlar. | + +## Örneği genişletme + +You can adapt the script to generate other DataBar variants (e.g., `DATABAR_STACKED`, `DATABAR_EXPANDED`). Replace the `EncodeTypes` constant accordingly: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +If you need to embed the barcode in a PDF, Aspose.PDF for Python can import the PNG file directly or you can use the `save` method with `BarCodeImageFormat.Pdf`. + +## Sonuç + +This tutorial showed how to **create omni directional databar** and how to **create barcode image python** using Aspose.BarCode. You now have a complete, reproducible script that generates two PNG files with different aspect ratios, handles common pitfalls, and can be extended to other barcode formats. + +Next, explore generating QR codes, adding the barcode to PDF invoices, or automating batch processing for large product catalogs. Each of those topics builds on the same `BarcodeGenerator` pattern demonstrated here. Happy coding! + +## Sonra Ne Öğrenmelisin? + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Barkod görüntüsü oluştur – GS1 Kupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [DotCode barkod görüntüsü oluştur – satırlar & sütunlar (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Barkod görüntüsü nasıl oluşturulur ve Java'da render edilir](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/turkish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/turkish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..4b63133d9 --- /dev/null +++ b/barcode/turkish/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-08-12 +description: Python kullanarak barkodu hızlı bir şekilde nasıl oluşturabilirsiniz. + Veriden barkod oluşturmayı ve tek bir kütüphane ile barkod görüntüsünü dışa aktarmayı + öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: tr +lastmod: 2026-08-12 +og_description: Python'da Aspose.BarCode ile barkod nasıl oluşturulur. Veriden barkod + oluşturmak ve barkod görüntüsünü PNG olarak dışa aktarmak için bu kılavuzu izleyin. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Python'da barkod nasıl oluşturulur – hızlı, güvenilir rehber +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Python’da barkod nasıl oluşturulur – eksiksiz adım adım rehber +url: /tr/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python’da barkod nasıl oluşturulur – adım adım tam kılavuz + +Bir Python uygulamasında **barkod nasıl oluşturulur** öğrenmek istiyorsanız, bu öğretici tam olarak ihtiyacınız olan kodu gösterir. **Veriden barkod oluşturma**, görünümünü ayarlama ve **barkod görüntüsünü PNG dosyası olarak dışa aktarma** işlemlerini on satırın altında nasıl yapacağınızı öğreneceksiniz. + +Barkod oluşturmak, iş mantığınızın geri kalanından ayrı bir konu gibi görünebilir; ancak tek bir kütüphane sayesinde bu süreci mevcut kod tabanınızla aynı satır içinde tutabilirsiniz. Aşağıdaki bölümlerde tam çalışan bir örnek görecek, her satırın neden önemli olduğunu anlayacak ve modül genişliğini değiştirme ya da sadece dış hatları çizen bir barkod gibi yaygın varyasyonları keşfedeceksiniz. + +## Aspose.BarCode kütüphanesi ile barkod nasıl oluşturulur + +Python (via .NET) için Aspose.BarCode kütüphanesi, bu rehberde kullanılan Planet barkodu da dahil olmak üzere birçok semboloji için basit bir API sunar. Başlamadan önce paketin kurulu olduğundan emin olun: + +```bash +pip install aspose-barcode +``` + +> **İpucu:** Diğer projelerle sürüm çakışmalarını önlemek için bir sanal ortam (virtual environment) kullanın. + +### 1. Gerekli sınıfları içe aktarın + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Bu içe aktarmalar, jeneratör sınıfına, barkod tipleri enum’una ve sonucu kaydederken kullanılacak görüntü formatı enum’una erişmenizi sağlar. + +### 2. Veriden barkod oluşturun + +İlk adım **veriden barkod oluşturma**dır. `BarcodeGenerator` yapıcı (constructor) sembolojiyi ve kodlamak istediğiniz ham dizeyi alır. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +`EncodeTypes.Planet` değeri Planet barkodunu seçerken, `"123456"` son görüntüde görünecek veri yüküdür. + +### 3. X‑boyutunu (modül genişliğini) ayarlayın + +X‑boyutu, her barkod modülünün (ince çubuk) genişliğini kontrol eder. 4 piksel olarak ayarlamak, dosyayı çok büyük yapmadan net, okunabilir bir görüntü sağlar. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Neden önemli:** Daha büyük bir X‑boyutu, düşük çözünürlüklü yazıcılarda tarama güvenilirliğini artırırken, daha küçük bir değer web kullanımı için dosya boyutunu azaltır. + +### 4. Barkod görüntüsünü dışa aktar (dolu stil) + +Şimdi `save` yöntemiyle **barkod görüntüsünü dışa aktar**abilirsiniz. Örnekte PNG dosyası kaydedilir, ancak `BarCodeImageFormat` enum’unu değiştirerek JPEG, BMP veya TIFF de seçebilirsiniz. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +`PlanetFilled.png` dosyası, yazdırmaya ya da PDF’e gömmeye hazır, tamamen dolu bir Planet barkodu içerir. + +### 5. Sadece dış hatları çizen ikinci bir jeneratör oluşturun + +Eğer sadece dış hatları (boş çubuklar) isteyen bir versiyona ihtiyacınız varsa, `filled_bars` bayrağı görüntü kaydedildikten sonra değiştirilemeyeceği için yeni bir jeneratör oluşturmalısınız. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Aynı X‑boyutu ayarını uygulayın + +İkinci bir jeneratör oluşturduğunuzda, tutarlı kalmasını istediğiniz tüm görsel ayarları tekrarlamanız gerekir. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Dolu çubukları devre dışı bırakın (dış hatlı barkod) + +`filled_bars` değerini `False` yapmak, renderlayıcıya her modülün sadece dış hatlarını çizmeyi söyler; bu, tasarım amaçları için faydalı olabilecek daha hafif bir görüntü üretir. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Dış hatlı barkod görüntüsünü dışa aktar + +Son olarak **barkod görüntüsünü dışa aktar**ın, bu sefer dış hatlı versiyonu kaydedin. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Artık iki PNG dosyanız var: biri dolu çubuklu (`PlanetFilled.png`), diğeri sadece dış hatlı (`PlanetEmpty.png`). + +## Barkod görüntüsünü diğer formatlarda dışa aktar (isteğe bağlı) + +`save` yöntemi çeşitli formatları destekler. JPEG olarak %90 kaliteyle dışa aktarmak için: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Web kullanımı için şeffaf bir arka plan istiyorsanız, alfa kanalı olan PNG’yi seçin: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Yaygın varyasyonlar ve kenar durumları + +| Senaryo | Gereken değişiklik | Kod snippet | +|----------|-------------------|--------------| +| **Farklı semboloji** (ör. QR) | Farklı bir `EncodeTypes` değeri kullanın | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Özel ön plan rengi** | `fore_color` ayarlayın | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Daha yüksek çözünürlük** | DPI’yı `image_width` ve `image_height` ile artırın | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Uzun veri dizileri** | Verinin uzunluğunun semboloji spesifikasyonuna uygun olduğundan emin olun | Oluşturucu öncesi uzunluğu doğrulayın | + +> **Dikkat:** Seçilen semboloji için maksimum uzunluğu aşan veri sağlamak çalışma zamanında bir istisna (runtime exception) oluşturur. Dize uzunluğunu her zaman doğrulayın veya `ArgumentException` yakalayın. + +## Tam, çalıştırılabilir örnek + +Aşağıda `generate_planet_barcode.py` adlı bir dosyaya kopyalayıp yapıştırabileceğiniz tam betik yer alıyor. `YOUR_DIRECTORY` kısmını makinenizde mevcut bir klasöre göre ayarlayın. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Bu betiği çalıştırdığınızda belirtilen dizinde iki PNG dosyası oluşur. Çıktıyı herhangi bir görüntü görüntüleyicide açarak doğrulayın; ikisi de `123456` dizesini kodlayan bir Planet barkodu göstermelidir. + +## Sonuç + +Artık Python’da Aspose.BarCode kullanarak **barkod nasıl oluşturulur** biliyorsunuz, **veriden barkod oluşturma** ve **barkod görüntüsünü dışa aktarma** işlemlerini dolu ve dış hatlı stillerle yapabiliyorsunuz. Aynı desen diğer sembolojiler, görüntü formatları ve görsel özelleştirmeler için de geçerlidir; bu da uygulamanızdaki herhangi bir barkod‑ile‑ilgili özellik için esnek bir temel sağlar. + +### Sonraki adımlar + +* `EncodeTypes.Planet` yerine istediğiniz değeri koyarak QR, Code‑128 veya DataMatrix gibi diğer sembolojileri keşfedin. +* `ReportLab` veya `PyPDF2` gibi kütüphanelerle oluşturulan PNG dosyalarını PDF raporlarına entegre edin. +* Ekran çözünürlüğüne veya yazıcı DPI’sına göre barkod boyutunu dinamik olarak ayarlamak için X‑boyutu değerlerini deneyin. + +İyi kodlamalar, örneği kendi proje gereksinimlerinize göre uyarlamaktan çekinmeyin! + +## Bir sonraki öğrenmeniz gerekenler + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini ustalaşmanız ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmeniz için adım adım açıklamalı tam çalışan kod örnekleri içerir. + +- [How to Generate Barcode Image in Java with Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [How to Generate Barcode Java – Complete Configuration Guide](/barcode/english/java/barcode-configuration/) +- [How to create code128 barcode images in Java with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/vietnamese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md b/barcode/vietnamese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md new file mode 100644 index 000000000..118790352 --- /dev/null +++ b/barcode/vietnamese/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-08-12 +description: Ví dụ trình tạo mã vạch cho thấy cách tạo mã vạch với kích thước pixel + chính xác. Học cách đặt độ rộng mô-đun, chiều cao thanh và tạo mã vạch Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to generate barcode +- barcode pixel size +- generate planet barcode +- barcode height setting +language: vi +lastmod: 2026-08-12 +og_description: Ví dụ trình tạo mã vạch cho thấy cách tạo mã vạch với kích thước pixel + chính xác. Hãy làm theo hướng dẫn này để kiểm soát độ rộng mô-đun và chiều cao thanh + cho các mã Planet và RM4SCC. +og_image_alt: Screenshot of a barcode generator example showing a Planet barcode with + custom pixel size +og_title: Ví dụ trình tạo mã vạch – tùy chỉnh kích thước pixel trong C# +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + headline: barcode generator example – step‑by‑step guide for custom pixel sizes + type: TechArticle +- description: barcode generator example that shows how to generate barcode with precise + pixel size. Learn to set module width, bar height and create Planet barcodes. + name: barcode generator example – step‑by‑step guide for custom pixel sizes + steps: + - name: Install the Aspose.BarCode package + text: 'Open a terminal in your project folder and run:' + - name: Add the necessary `using` directives + text: '```csharp using Aspose.BarCode.Generation; using Aspose.BarCode.BarCodeImageFormat; + ```' + - name: – generate a Planet barcode with automatically calculated height + text: '```csharp // Step 1: Generate a Planet barcode with automatically calculated + height BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate a Planet barcode with an explicit 100‑pixel height + text: '```csharp // Step 2: Generate a Planet barcode with an explicit 100‑pixel + height BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, + "123456");' + - name: – generate an RM4SCC barcode with the same explicit height + text: '```csharp // Step 3: Generate an RM4SCC barcode with the same explicit + height BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, + "123456");' + - name: What is **barcode pixel size**? + text: '*Pixel size* refers to the physical number of screen or printer pixels + that represent a single module (`XDimension`). A larger pixel size yields a + bigger barcode, which can be easier for low‑resolution scanners but consumes + more label real‑estate.' + - name: How does `BarHeight` affect readability? + text: The `BarHeight` property controls the vertical length of the bars. Standards + for most 1‑D barcodes (including Planet and RM4SCC) recommend a minimum height + of 10 mm when printed at 300 dpi, which translates to roughly 118 pixels. Setting + a height below that can cause read errors, especially on mobil + - name: When should you let the library calculate height automatically? + text: If you’re generating barcodes for on‑screen display only, the automatic + calculation keeps the aspect ratio consistent and reduces the amount of manual + tweaking needed. For printed labels that must meet strict ISO specifications, + you should **explicitly set the bar height**. + - name: Pro tip on performance + text: When generating thousands of barcodes in a batch job, reuse a single `BarcodeGenerator` + instance and only change the `CodeText` and size parameters between saves. This + avoids repeated allocation of internal rendering objects and can cut execution + time by up to 30 %. + type: HowTo +tags: +- barcode +- C# +- Aspose.BarCode +title: Ví dụ trình tạo mã vạch – hướng dẫn từng bước cho kích thước pixel tùy chỉnh +url: /vi/python-java/general/barcode-generator-example-step-by-step-guide-for-custom-pixe/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# barcode generator example – hướng dẫn từng bước cho kích thước pixel tùy chỉnh + +Nếu bạn cần một **barcode generator example** cho phép kiểm soát từng pixel, hướng dẫn này sẽ chỉ cho bạn cách thực hiện. Bạn sẽ học cách đặt độ rộng module, xác định chiều cao thanh cố định, và tạo cả mã vạch Planet và RM4SCC với kích thước dự đoán được. + +Hầu hết các nhà phát triển gặp khó khăn với các hình ảnh “how to generate barcode” trông giống nhau trên mọi màn hình hoặc máy in. Các đoạn mã dưới đây giải quyết vấn đề này bằng cách mở ra các tham số mức pixel của thư viện Aspose.BarCode for .NET, giúp bạn tạo ra kết quả nhất quán mà không cần đoán mò. + +## Những gì bạn sẽ học + +* Cách cài đặt gói NuGet cần thiết. +* Cách tạo mã vạch Planet với chiều cao được tính tự động. +* Cách tạo mã vạch Planet với chiều cao 100 pixel rõ ràng. +* Cách tạo mã vạch RM4SCC bằng cùng chiều cao rõ ràng. +* Tại sao **barcode pixel size** quan trọng đối với độ tin cậy khi quét. +* Mẹo khắc phục các vấn đề phổ biến khi bạn tạo hình ảnh mã vạch Planet. + +Bạn chỉ cần .NET 6 trở lên, môi trường phát triển C# cơ bản, và kết nối internet để tải gói NuGet. + +--- + +## barcode generator example – thiết lập môi trường phát triển + +Trước khi viết bất kỳ mã nào, hãy đảm bảo thư viện Aspose.BarCode có sẵn trong dự án của bạn. + +### Cài đặt gói Aspose.BarCode + +Mở một terminal trong thư mục dự án và chạy: + +```bash +dotnet add package Aspose.BarCode +``` + +Lệnh này sẽ thêm phiên bản ổn định mới nhất của **Aspose.BarCode** vào `csproj` của bạn. Sau khi khôi phục hoàn tất, bạn có thể bắt đầu sử dụng lớp `BarcodeGenerator`. + +> **Pro tip:** Nhắm mục tiêu .NET 6 hoặc .NET 7 để tận dụng các cải tiến hiệu năng mới nhất và xử lý UTF‑8 mặc định. + +### Thêm các chỉ thị `using` cần thiết + +```csharp +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; +``` + +Các không gian tên này cung cấp lớp `BarcodeGenerator` và enum `BarCodeImageFormat` sẽ được sử dụng sau trong hướng dẫn. + +--- + +## Cách tạo mã vạch với kích thước pixel tùy chỉnh + +Ba bước sau đây minh họa **barcode generator example** hoàn chỉnh. Mỗi bước dựa trên bước trước, vì vậy bạn có thể sao chép‑dán toàn bộ khối vào một ứng dụng console và chạy mà không thay đổi. + +### Bước 1 – tạo mã vạch Planet với chiều cao được tính tự động + +```csharp +// Step 1: Generate a Planet barcode with automatically calculated height +BarcodeGenerator planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Set module width (x‑dimension) to 4 pixels +planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + +// Save the image as PNG +planetAuto.Save("PlanetAuto.png", BarCodeImageFormat.Png); +``` + +**Tại sao cách này hoạt động:** +*Thuộc tính `XDimension` xác định độ rộng của một module mã vạch duy nhất (phần tử đen hoặc trắng nhỏ nhất). Khi bạn bỏ qua `BarHeight`, thư viện sẽ tính chiều cao duy trì tỷ lệ chuẩn cho mã Planet.* + +**Kết quả mong đợi:** Một tệp PNG tên `PlanetAuto.png` chứa mã vạch Planet sạch sẽ. Chiều cao của nó thích ứng với độ rộng module 4 pixel, thường khoảng 60 pixel cho dữ liệu sáu ký tự. + +### Bước 2 – tạo mã vạch Planet với chiều cao 100 pixel rõ ràng + +```csharp +// Step 2: Generate a Planet barcode with an explicit 100‑pixel height +BarcodeGenerator planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + +// Keep the same module width +planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Force the bar height to 100 pixels +planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +planetFixed.Save("PlanetHeight100.png", BarCodeImageFormat.Png); +``` + +**Tại sao bạn có thể cần điều này:** +Đôi khi thiết bị quét yêu cầu chiều cao thanh tối thiểu để phát hiện đáng tin cậy. Bằng cách đặt `BarHeight.Pixels`, bạn đảm bảo mọi hình ảnh được tạo đáp ứng yêu cầu này, bất kể độ dài dữ liệu được mã hoá. + +**Kết quả mong đợi:** `PlanetHeight100.png` hiển thị cùng dữ liệu như trước, nhưng các thanh có chiều cao chính xác 100 pixel, cho bạn kiểm soát hoàn toàn kích thước hiển thị. + +### Bước 3 – tạo mã vạch RM4SCC với cùng chiều cao rõ ràng + +```csharp +// Step 3: Generate an RM4SCC barcode with the same explicit height +BarcodeGenerator rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + +// Use the same module width for consistency +rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + +// Apply the 100‑pixel bar height +rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + +// Save the image +rm4sccFixed.Save("RM4SCCHeight100.png", BarCodeImageFormat.Png); +``` + +**Tại sao điều này quan trọng:** +`EncodeTypes.RM4SCC` là một mã vạch tuyến tính xếp chồng được dùng trong logistics. Đồng nhất chiều cao thanh của nó với mã Planet giúp đơn giản hoá xử lý hàng loạt khi cả hai biểu tượng xuất hiện trên cùng một nhãn. + +**Kết quả mong đợi:** `RM4SCCHeight100.png` hiển thị một mã vạch RM4SCC có kích thước hoàn hảo, khớp với chiều cao 100 pixel bạn đã đặt cho mã Planet. + +> **Result verification:** Mở mỗi tệp PNG trong trình xem ảnh và xác nhận các thanh đen có độ rộng chính xác 4 pixel và, nếu bạn đã chỉ định, chiều cao 100 pixel. Bạn cũng có thể đưa các tệp này vào ứng dụng quét mã vạch để chắc chắn chúng giải mã thành “123456”. + +## Hiểu về kích thước pixel của mã vạch và chiều cao thanh + +### **barcode pixel size** là gì? + +*Pixel size* đề cập đến số lượng pixel vật lý trên màn hình hoặc máy in đại diện cho một module (`XDimension`). Kích thước pixel lớn hơn tạo ra mã vạch to hơn, có thể dễ dàng hơn cho các máy quét độ phân giải thấp nhưng tiêu tốn nhiều không gian nhãn hơn. + +### `BarHeight` ảnh hưởng đến khả năng đọc như thế nào? + +Thuộc tính `BarHeight` kiểm soát độ dài dọc của các thanh. Các tiêu chuẩn cho hầu hết các mã vạch 1‑D (bao gồm Planet và RM4SCC) khuyến nghị chiều cao tối thiểu 10 mm khi in ở 300 dpi, tương đương khoảng 118 pixel. Đặt chiều cao dưới mức này có thể gây lỗi đọc, đặc biệt trên camera di động. + +### Khi nào nên để thư viện tự tính chiều cao? + +Nếu bạn chỉ tạo mã vạch để hiển thị trên màn hình, việc tính tự động giữ tỷ lệ chuẩn và giảm nhu cầu điều chỉnh thủ công. Đối với nhãn in phải đáp ứng các tiêu chuẩn ISO nghiêm ngặt, bạn nên **đặt chiều cao thanh một cách rõ ràng**. + +--- + +## Các sai lầm thường gặp và thực hành tốt khi bạn tạo mã vạch Planet + +| Rủi ro | Nguyên nhân | Cách khắc phục | +|--------|-------------|----------------| +| Các thanh xuất hiện quá mỏng hoặc quá dày | `XDimension` để ở giá trị mặc định (1 pixel) trên màn hình độ phân giải cao | Đặt `XDimension.Pixels` ít nhất 3‑4 để rõ nét | +| Máy quét không thể đọc mã | `BarHeight` quá nhỏ so với tiêu cự của máy quét | Sử dụng `BarHeight.Pixels` ≥ 100 cho hầu hết máy quét di động | +| Hình ảnh bị mờ sau khi phóng to/thu nhỏ | Lưu dưới dạng JPEG gây ra hiện tượng nén và mất chất lượng | Lưu dưới dạng PNG (`BarCodeImageFormat.Png`) để có đầu ra không mất dữ liệu | +| Loại mã vạch không mong muốn | Giá trị enum `EncodeTypes` sai | Kiểm tra lại bạn đang sử dụng `EncodeTypes.Planet` cho biểu tượng Planet | + +### Mẹo về hiệu năng + +Khi tạo hàng ngàn mã vạch trong một công việc batch, hãy tái sử dụng một thể hiện `BarcodeGenerator` duy nhất và chỉ thay đổi `CodeText` và các tham số kích thước giữa các lần lưu. Điều này tránh việc cấp phát lại các đối tượng render nội bộ và có thể giảm thời gian thực thi tới 30 %. + +--- + +## Ví dụ đầy đủ hoạt động – kết hợp mọi thứ lại + +Tạo một dự án console mới (`dotnet new console -n BarcodeDemo`) và thay thế nội dung của `Program.cs` bằng đoạn sau: + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode.BarCodeImageFormat; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Directory where PNG files will be saved + string outputDir = Environment.CurrentDirectory; + + // ---------- Planet barcode – automatic height ---------- + var planetAuto = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetAuto.Parameters.Barcode.XDimension.Pixels = 4; + planetAuto.Save($"{outputDir}/PlanetAuto.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetAuto.png generated."); + + // ---------- Planet barcode – fixed 100‑pixel height ---------- + var planetFixed = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetFixed.Parameters.Barcode.XDimension.Pixels = 4; + planetFixed.Parameters.Barcode.BarHeight.Pixels = 100; + planetFixed.Save($"{outputDir}/PlanetHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("PlanetHeight100.png generated."); + + // ---------- RM4SCC barcode – same fixed height ---------- + var rm4sccFixed = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccFixed.Parameters.Barcode.XDimension.Pixels = 4; + rm4sccFixed.Parameters.Barcode.BarHeight.Pixels = 100; + rm4sccFixed.Save($"{outputDir}/RM4SCCHeight100.png", BarCodeImageFormat.Png); + Console.WriteLine("RM4SCCHeight100.png generated."); + + Console.WriteLine("All barcodes created successfully."); + } + } +} +``` + +Chạy chương trình bằng `dotnet run`. Sau khi thực thi, bạn sẽ thấy ba tệp PNG trong thư mục dự án, mỗi tệp minh họa một kịch bản **barcode generator example** khác nhau. + +--- + +## Các bước tiếp theo và chủ đề liên quan + +* **How to generate barcode in other formats** – khám phá `EncodeTypes.Code128`, `EncodeTypes.QR`, và `EncodeTypes.DataMatrix` cho nhu cầu 2‑D. +* **Embedding barcodes in PDFs** – kết hợp Aspose.BarCode với Aspose.PDF để đặt mã vạch trực tiếp lên mẫu hoá đơn. +* **Dynamic barcode size based on user input** – tính toán + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã đầy đủ hoạt động với giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách tạo mã vạch java: Tạo hình ảnh mã vạch chính xác](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) +- [Cách tạo mã vạch trong Java: Tạo và đặt kích thước cho toàn bộ hình ảnh](/barcode/english/java/barcode-basics/creating-setting-size-whole-picture-barcode/) +- [Cách tạo mã vạch code128 trong Java và đặt chiều cao thanh](/barcode/english/java/barcode-configuration/setting-bars-height/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/vietnamese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md b/barcode/vietnamese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md new file mode 100644 index 000000000..47f883d8f --- /dev/null +++ b/barcode/vietnamese/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: Cấu hình bố cục mã vạch Databar trong Python nhanh chóng. Học cách đặt + cột, hàng và lưu hình ảnh với thư viện tạo mã vạch. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- configure databar barcode layout +- Databar Expanded Stacked +- barcode generator Python +- set barcode columns +- set barcode rows +language: vi +lastmod: 2026-08-12 +og_description: Cấu hình bố cục mã vạch Databar trong Python để kiểm soát cột, hàng + và đầu ra hình ảnh. Tham khảo hướng dẫn này để có giải pháp sẵn sàng chạy. +og_image_alt: Screenshot of a Databar Expanded Stacked barcode with custom column + layout +og_title: Cấu hình bố cục mã vạch Databar trong Python – hướng dẫn đầy đủ +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + headline: Configure Databar barcode layout in Python – step‑by‑step guide + type: TechArticle +- description: Configure Databar barcode layout in Python quickly. Learn to set columns, + rows, and save images with the barcode generator library. + name: Configure Databar barcode layout in Python – step‑by‑step guide + steps: + - name: Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: Create a barcode generator for Databar Expanded Stacked + text: '```python # Initialize the generator with the desired symbology and value + barcode_generator = BarcodeGenerator( EncodeTypes.DatabarExpandedStacked, "Databar + Expanded Stacked long" ) ```' + - name: Set the number of columns (horizontal layout) + text: '```python # Configure the layout to use 4 columns barcode_generator.parameters.barcode.data_bar.columns + = 4 ```' + - name: Save the barcode image with the column layout + text: '```python # Save the image as a PNG file barcode_generator.save("output/ExpandedCols4.png", + BarCodeImageFormat.Png) ```' + - name: Create a second generator for the same barcode type (row layout) + text: If you prefer a vertical stack, you work with rows instead of columns. The + code below re‑uses the same value but creates a fresh `BarcodeGenerator` instance + to avoid mixing column and row settings. + - name: Set the number of rows (vertical layout) + text: '```python # Configure the layout to use 3 rows barcode_generator.parameters.barcode.data_bar.rows + = 3 ```' + - name: Save the barcode image with the row layout + text: '```python # Save the vertically stacked barcode barcode_generator.save("output/ExpandedRows3.png", + BarCodeImageFormat.Png) ```' + type: HowTo +tags: +- barcode +- Python +- Databar +- image generation +title: Cấu hình bố cục mã vạch Databar trong Python – hướng dẫn từng bước +url: /vi/python-java/general/configure-databar-barcode-layout-in-python-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cấu hình bố cục mã vạch Databar trong Python – hướng dẫn từng bước + +Nếu bạn cần **cấu hình bố cục mã vạch Databar trong Python**, hướng dẫn này sẽ dẫn bạn qua toàn bộ quá trình. Bạn sẽ thấy cách đặt số cột hoặc hàng cho mã vạch Databar Expanded Stacked và cách lưu hình ảnh kết quả chỉ với một lần gọi tới thư viện tạo mã vạch. + +Kiểm soát bố cục là điều cần thiết khi bạn nhúng mã vạch lên bao bì hẹp, biên lai hoặc màn hình di động. Trong các phần dưới đây, chúng tôi sẽ đề cập đến các import cần thiết, hai tùy chọn bố cục (cột và hàng), và các thực tiễn tốt nhất để lưu ảnh PNG sạch sẽ. + +## Những gì bạn cần + +* Python 3.8 hoặc mới hơn +* `aspose.barcode` (hoặc bất kỳ gói tạo mã vạch tương thích nào) đã được cài đặt + ```bash + pip install aspose-barcode + ``` +* Quyền ghi vào thư mục nơi các tệp PNG sẽ được lưu + +Không cần công cụ bên ngoài nào thêm—thư viện tự xử lý việc render, scaling và mã hoá hình ảnh bên trong. + +## Cách cấu hình bố cục mã vạch Databar trong Python + +Cốt lõi của giải pháp là lớp `BarcodeGenerator`. Nó nhận một enum `EncodeTypes` xác định loại mã vạch—trong trường hợp này là `EncodeTypes.DatabarExpandedStacked`. Sau khi tạo generator, bạn có thể điều chỉnh bố cục bằng cách đặt các thuộc tính `columns` hoặc `rows` trên đối tượng tham số `data_bar`. + +### Bước 1: Nhập các lớp cần thiết + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Các import này cho phép bạn truy cập vào generator, enum cho các loại Databar, và hằng số định dạng ảnh PNG. + +### Bước 2: Tạo một barcode generator cho Databar Expanded Stacked + +```python +# Initialize the generator with the desired symbology and value +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +*Tại sao bước này?* +`EncodeTypes.DatabarExpandedStacked` yêu cầu thư viện tạo ra ký hiệu **Databar Expanded Stacked**, hỗ trợ các chuỗi số dài hơn trong khi vẫn giữ kích thước gọn nhẹ. Tham số thứ hai là dữ liệu cần mã hoá; nó có thể là bất kỳ chuỗi nào đáp ứng tiêu chuẩn Databar. + +### Bước 3: Đặt số cột (bố cục ngang) + +```python +# Configure the layout to use 4 columns +barcode_generator.parameters.barcode.data_bar.columns = 4 +``` + +**set barcode columns** là cụm từ chính cho thao tác này. Khi bạn tăng số cột, mã vạch sẽ lan rộng theo chiều ngang, điều này có thể hữu ích cho nhãn rộng. Thư viện tự động tính lại độ rộng module để giữ kích thước tổng thể nhất quán. + +#### Mẹo chuyên nghiệp +Số cột tối đa cho Databar Expanded Stacked là 8. Đặt giá trị lớn hơn giới hạn sẽ bị giới hạn lại ở mức tối đa, nhưng tốt hơn là bạn nên kiểm tra đầu vào trước. + +### Bước 4: Lưu ảnh mã vạch với bố cục cột + +```python +# Save the image as a PNG file +barcode_generator.save("output/ExpandedCols4.png", BarCodeImageFormat.Png) +``` + +**save barcode image** là hành động ghi mã vạch đã render ra đĩa. PNG là định dạng không mất dữ liệu, giữ được các cạnh sắc nét cần thiết cho việc quét đáng tin cậy. + +### Bước 5: Tạo một generator thứ hai cho cùng loại mã vạch (bố cục hàng) + +Nếu bạn muốn một chồng dọc, bạn sẽ làm việc với hàng thay vì cột. Đoạn mã dưới đây tái sử dụng cùng một giá trị nhưng tạo một thể hiện `BarcodeGenerator` mới để tránh trộn lẫn cài đặt cột và hàng. + +```python +# New generator instance for row configuration +barcode_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +``` + +### Bước 6: Đặt số hàng (bố cục dọc) + +```python +# Configure the layout to use 3 rows +barcode_generator.parameters.barcode.data_bar.rows = 3 +``` + +**set barcode rows** sắp xếp các module mã vạch theo chiều dọc. Bố cục ba hàng giảm chiều cao của mỗi chồng riêng lẻ, làm cho mã vạch phù hợp với biên lai hẹp hoặc màn hình di động. + +#### Trường hợp đặc biệt +Nếu bạn đặt `rows` thành 1, thư viện sẽ tạo một Databar một hàng (tương đương với Databar tiêu chuẩn). Các giá trị dưới 1 sẽ bị bỏ qua và đặt lại về mặc định (1 hàng). + +### Bước 7: Lưu ảnh mã vạch với bố cục hàng + +```python +# Save the vertically stacked barcode +barcode_generator.save("output/ExpandedRows3.png", BarCodeImageFormat.Png) +``` + +Một lần nữa, chúng ta **save barcode image** bằng PNG để giữ độ nét của đầu ra. + +## Ví dụ đầy đủ có thể chạy + +Kết hợp tất cả các phần lại với nhau sẽ cho bạn một script tự chứa mà bạn có thể đưa vào bất kỳ dự án Python nào. + +```python +# ------------------------------------------------------------ +# configure_databar_layout.py +# Demonstrates how to configure Databar barcode layout in Python +# ------------------------------------------------------------ + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure the output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# ----------------------------------------------------------------- +# 1️⃣ Column layout – 4 columns +# ----------------------------------------------------------------- +col_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +col_generator.parameters.barcode.data_bar.columns = 4 # set barcode columns +col_path = os.path.join(output_dir, "ExpandedCols4.png") +col_generator.save(col_path, BarCodeImageFormat.Png) # save barcode image +print(f"Column layout saved to {col_path}") + +# ----------------------------------------------------------------- +# 2️⃣ Row layout – 3 rows +# ----------------------------------------------------------------- +row_generator = BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, + "Databar Expanded Stacked long" +) +row_generator.parameters.barcode.data_bar.rows = 3 # set barcode rows +row_path = os.path.join(output_dir, "ExpandedRows3.png") +row_generator.save(row_path, BarCodeImageFormat.Png) # save barcode image +print(f"Row layout saved to {row_path}") +``` + +**Kết quả mong đợi** + +Chạy script sẽ tạo ra hai tệp PNG: + +* `output/ExpandedCols4.png` – một mã vạch kéo dài qua bốn cột +* `output/ExpandedRows3.png` – một mã vạch nén thành ba hàng + +Cả hai hình ảnh đều có thể mở bằng bất kỳ trình xem ảnh nào hoặc nhập trực tiếp vào hoá đơn PDF, mẫu nhãn, hoặc trang web. + +## Câu hỏi thường gặp và khắc phục sự cố + +| Câu hỏi | Trả lời | +|----------|--------| +| *Nếu mã vạch bị mờ thì sao?* | Tăng độ phân giải ảnh bằng cách đặt `barcode_generator.parameters.image_width` và `image_height` trước khi gọi `save`. | +| *Tôi có thể dùng các định dạng ảnh khác không?* | Có. Thay `BarCodeImageFormat.Png` bằng `Jpeg`, `Bmp`, hoặc `Gif` tùy nhu cầu. | +| *Có giới hạn độ dài dữ liệu không?* | Databar Expanded Stacked hỗ trợ tối đa 74 ký tự số. Vượt quá giới hạn sẽ gây ra `ArgumentException`. | +| *Làm sao để thay đổi màu nền trước?* | Sử dụng `barcode_generator.parameters.barcode.color = Color.Blue` (import `System.Drawing.Color`). | +| *Tôi có thể kết hợp cả cột và hàng không?* | Không. API coi cột và hàng là các chế độ bố cục loại trừ lẫn nhau. Chỉ chọn một trong mỗi instance của mã vạch. | + +## Các bước tiếp theo + +Bây giờ bạn đã có thể **cấu hình bố cục mã vạch Databar**, hãy xem xét khám phá các chủ đề liên quan sau: + +* **Thêm chú thích văn bản** – sử dụng `barcode_generator.parameters.barcode.code_text` để hiển thị giá trị đã mã hoá dưới hình ảnh. +* **Nhúng mã vạch vào PDF** – kết hợp PNG đã tạo với `aspose.pdf` để tạo tài liệu có thể in. +* **Kích thước động** – tính toán số cột hoặc hàng tối ưu dựa trên kích thước nhãn tại thời gian chạy. +* **Xử lý hàng loạt** – lặp qua một CSV các mã sản phẩm để tự động tạo thư viện ảnh mã vạch. + +Thử nghiệm với các giá trị cột và hàng khác nhau để xem chúng ảnh hưởng như thế nào đến độ tin cậy khi quét trên thiết bị mục tiêu của bạn. Bạn càng thử nghiệm, bạn sẽ càng hiểu rõ các đánh đổi giữa kích thước mã vạch, khả năng đọc và hạn chế không gian. + +--- + +*Chúc lập trình vui vẻ! Nếu bạn thấy hướng dẫn này hữu ích, hãy chia sẻ với đồng nghiệp hoặc để lại bình luận về những thách thức bố cục mà bạn gặp phải.* + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây bao phủ các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Tạo ảnh mã vạch DotCode – hàng & cột (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Tạo ảnh mã vạch c# – Cấu hình Codablock F Hàng & Cột](/barcode/english/net/codablock-f-encoding/codablock-f-row-column-configuration/) +- [Điều chỉnh chiều cao mã vạch Databar một chiều](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-databar-barcode-height-adjustment/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/vietnamese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md b/barcode/vietnamese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md new file mode 100644 index 000000000..982446271 --- /dev/null +++ b/barcode/vietnamese/python-java/general/create-barcode-image-in-c-with-barcodegenerator/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-08-12 +description: Tạo hình ảnh mã vạch trong C# bằng BarCodeGenerator. Tìm hiểu cách tạo + DataBar, kiểm soát kích thước hình ảnh mã vạch và tạo nhiều mã vạch một cách hiệu + quả. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode image +- barcode generator c# +- create multiple barcodes +- how to generate databar +- barcode image size +language: vi +lastmod: 2026-08-12 +og_description: Tạo hình ảnh mã vạch trong C# với BarCodeGenerator. Hướng dẫn này + trình bày chi tiết cách tạo mã DataBar, điều chỉnh kích thước hình ảnh mã vạch và + tạo nhiều mã vạch. +og_image_alt: Screenshot of a generated DataBar barcode image saved as PNG +og_title: Tạo hình ảnh mã vạch trong C# – hướng dẫn đầy đủ BarCodeGenerator +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + headline: Create barcode image in C# with BarCodeGenerator + type: TechArticle +- description: Create barcode image in C# using BarCodeGenerator. Learn how to generate + DataBar, control barcode image size, and create multiple barcodes efficiently. + name: Create barcode image in C# with BarCodeGenerator + steps: + - name: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + text: Setting up a **barcode generator c#** instance for DataBar Omni‑directional + encoding. + - name: Adjusting **barcode image size** by changing X‑dimension and bar height. + text: Adjusting **barcode image size** by changing X‑dimension and bar height. + - name: Using a loop to **create multiple barcodes** with different heights. + text: Using a loop to **create multiple barcodes** with different heights. + - name: Saving the images as PNG files and verifying the output. + text: Saving the images as PNG files and verifying the output. + type: HowTo +tags: +- barcode +- csharp +- barcodegenerator +- databar +- image-processing +title: Tạo hình ảnh mã vạch trong C# với BarCodeGenerator +url: /vi/python-java/general/create-barcode-image-in-c-with-barcodegenerator/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo hình ảnh mã vạch trong C# với BarCodeGenerator + +Nếu bạn cần **tạo hình ảnh mã vạch** trong một ứng dụng .NET, hướng dẫn này sẽ cho bạn thấy chính xác cách thực hiện với lớp `BarCodeGenerator`. Dù bạn đang xây dựng hệ thống POS bán lẻ hay công cụ theo dõi tồn kho, bạn sẽ học cách tạo các ký hiệu DataBar, kiểm soát kích thước hình ảnh mã vạch và tạo nhiều mã vạch trong một lần chạy. + +Bạn cũng sẽ khám phá cách API **barcode generator c#** cho phép bạn điều chỉnh kích thước, chuyển đổi định dạng đầu ra và xử lý các trường hợp đặc biệt như chuỗi dữ liệu không hợp lệ. Khi kết thúc hướng dẫn, bạn có thể tự tin **tạo nhiều mã vạch** mà không cần viết mã lặp đi lặp lại. + +## Yêu cầu trước + +- .NET 6.0 hoặc phiên bản mới hơn đã được cài đặt +- Môi trường phát triển (Visual Studio, Rider, hoặc VS Code) +- Gói NuGet Aspose.BarCode cho .NET (hoặc bất kỳ thư viện tương thích nào cung cấp `BarCodeGenerator`) + +Bạn có thể thêm gói bằng: + +```bash +dotnet add package Aspose.BarCode +``` + +## Nội dung hướng dẫn này + +1. Cài đặt một thể hiện **barcode generator c#** cho mã hoá DataBar Omni‑directional. +2. Điều chỉnh **kích thước hình ảnh mã vạch** bằng cách thay đổi X‑dimension và chiều cao thanh. +3. Sử dụng vòng lặp để **tạo nhiều mã vạch** với các chiều cao khác nhau. +4. Lưu các hình ảnh dưới dạng tệp PNG và xác minh kết quả. + +Tất cả các đoạn mã đều hoàn chỉnh và sẵn sàng để sao chép‑dán vào một dự án console mới. + +![Ví dụ tạo hình ảnh mã vạch](barcode-example.png){alt="Ví dụ tạo hình ảnh mã vạch"} + +## Bước 1: Khởi tạo trình tạo – các kiến thức cơ bản về tạo hình ảnh mã vạch + +Bước đầu tiên là tạo một thể hiện của `BarCodeGenerator` với ký hiệu mong muốn. Đối với ký hiệu DataBar Omni‑directional, bạn sử dụng `EncodeTypes.DatabarOmniDirectional`. + +```csharp +using System; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // Create a barcode generator for DataBar Omni‑directional. + // The string "(01)12345678901231" follows the GS1 Application Identifier format. + var generator = new BarCodeGenerator(EncodeTypes.DatabarOmniDirectional, "(01)12345678901231"); + + // The rest of the steps are performed below. + } + } +} +``` + +**Tại sao điều này quan trọng:** Việc khởi tạo trình tạo xác định các quy tắc mã hoá và dữ liệu tải. Nếu bạn bỏ qua giá trị `EncodeTypes` đúng, thư viện sẽ tạo ra mã vạch không được hỗ trợ hoặc ném ra ngoại lệ. + +## Bước 2: Cấu hình X‑dimension và chiều cao thanh – kiểm soát kích thước hình ảnh mã vạch + +Kích thước hình ảnh của mã vạch được quyết định bởi hai tham số: + +| Tham số | Điều nó điều khiển | Khoảng điển hình | +|-----------|------------------|---------------| +| `x_dimension.pixels` | Độ rộng của mô-đun nhỏ nhất (“điểm”) | 1 – 4 px | +| `bar_height.pixels` | Chiều cao của các thanh dọc | 30 – 150 px | + +```csharp +// Set the module width to 2 px for a crisp, readable image. +generator.Parameters.Barcode.XDimension.Pixels = 2; + +// Set an initial bar height of 30 px. +generator.Parameters.Barcode.BarHeight.Pixels = 30; +``` + +**Mẹo:** X‑dimension nhỏ hơn tạo ra hình ảnh độ phân giải cao hơn nhưng có thể khó quét trên máy in chất lượng thấp. Điều chỉnh giá trị dựa trên thiết bị quét mục tiêu của bạn. + +## Bước 3: Lưu mã vạch đầu tiên – tạo hình ảnh mã vạch cho chiều cao 30 px + +Bây giờ bạn có thể tạo hình ảnh và ghi nó vào đĩa. Phương thức `Save` nhận một đường dẫn tệp và một enum định dạng hình ảnh. + +```csharp +// Save the 30 px high barcode as a PNG file. +string outputFolder = @"C:\Barcodes"; +generator.Save($"{outputFolder}\\Databar30.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar30.png (30 px height)"); +``` + +**Kết quả mong đợi:** Một tệp PNG có tên `Databar30.png` xuất hiện trong `C:\Barcodes`. Mở tệp sẽ hiển thị ký hiệu DataBar Omni‑directional với mẫu rõ ràng, độ tương phản cao. + +## Bước 4: Thay đổi chiều cao và tạo thêm hình ảnh – tạo nhiều mã vạch + +Để **tạo nhiều mã vạch** với các kích thước khác nhau, bạn chỉ cần thay đổi thuộc tính `BarHeight` và gọi lại `Save`. Điều này tránh việc tạo lại trình tạo, giúp tiết kiệm bộ nhớ và thời gian CPU. + +```csharp +// Increase the bar height to 60 px for a larger barcode. +generator.Parameters.Barcode.BarHeight.Pixels = 60; +generator.Save($"{outputFolder}\\Databar60.png", BarCodeImageFormat.Png); +Console.WriteLine("Saved Databar60.png (60 px height)"); + +// You can repeat the process for any height you need. +int[] heights = { 90, 120 }; +foreach (int h in heights) +{ + generator.Parameters.Barcode.BarHeight.Pixels = h; + generator.Save($"{outputFolder}\\Databar{h}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved Databar{h}.png ({h} px height)"); +} +``` + +**Tại sao cách này hoạt động:** Đối tượng `BarCodeGenerator` giữ toàn bộ trạng thái cấu hình. Thay đổi một thuộc tính duy nhất sẽ cập nhật engine render cho lần gọi `Save` tiếp theo, cho phép bạn **tạo nhiều mã vạch** một cách hiệu quả. + +## Bước 5: Nâng cao – cách tạo DataBar với dữ liệu tùy chỉnh + +Ví dụ trên sử dụng payload GS1 tĩnh. Trong các tình huống thực tế, bạn thường cần nhúng các định danh sản phẩm biến đổi. Thư viện chấp nhận bất kỳ chuỗi nào phù hợp với đặc tả DataBar. + +```csharp +string[] gtins = { "01234567890123", "98765432109876", "12345678901234" }; +foreach (var gtin in gtins) +{ + // GS1 Application Identifier (01) + GTIN + generator.CodeText = $"(01){gtin}"; + generator.Parameters.Barcode.BarHeight.Pixels = 50; // uniform height + generator.Save($"{outputFolder}\\Databar_{gtin}.png", BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode for GTIN {gtin}"); +} +``` + +**Điểm chính:** Thiết lập `generator.CodeText` cập nhật dữ liệu đã mã hoá mà không cần tạo lại đối tượng. Đây là mẫu **cách tạo databar** được khuyến nghị khi xử lý các tập dữ liệu lớn. + +## Bước 6: Xác minh và khắc phục – đảm bảo kích thước hình ảnh mã vạch đúng + +Sau khi tạo các hình ảnh, bạn có thể muốn xác nhận một cách lập trình rằng kích thước khớp với mong đợi. Lớp `Image` từ `System.Drawing` có thể đọc tệp và báo cáo kích thước của nó. + +```csharp +using System.Drawing; + +// Verify image dimensions +string[] files = { "Databar30.png", "Databar60.png", "Databar90.png" }; +foreach (var file in files) +{ + using var img = Image.FromFile($"{outputFolder}\\{file}"); + Console.WriteLine($"{file}: {img.Width}px × {img.Height}px"); +} +``` + +Nếu chiều cao không phản ánh giá trị bạn đã đặt, hãy kiểm tra: + +- **X‑dimension**: Giá trị quá nhỏ có thể khiến trình render làm tròn chiều cao. +- **Định dạng hình ảnh**: Một số định dạng (ví dụ, JPEG) áp dụng nén có thể thay đổi kích thước pixel khi lưu. PNG giữ nguyên kích thước chính xác. + +## Bước 7: Các thực hành tốt nhất cho kích thước hình ảnh mã vạch và hiệu năng + +| Khuyến nghị | Lý do | +|----------------|--------| +| Giữ `x_dimension.pixels` trong khoảng 2 – 3 px cho hầu hết máy quét. | Cân bằng khả năng đọc và kích thước tệp. | +| Sử dụng PNG cho đầu ra không mất dữ liệu khi hình ảnh sẽ được in. | Đảm bảo kích thước chính xác và các cạnh sắc nét. | +| Tái sử dụng một thể hiện `BarCodeGenerator` duy nhất khi tạo nhiều mã vạch. | Giảm tải phân bổ đối tượng. | +| Xác thực chuỗi đầu vào theo tiêu chuẩn GS1 trước khi gán cho `CodeText`. | Ngăn ngừa ngoại lệ thời chạy và quét không hợp lệ. | +| Lưu các hình ảnh đã tạo trong thư mục riêng với quy ước đặt tên rõ ràng (ví dụ, `Databar_{GTIN}.png`). | Đơn giản hoá quá trình xử lý tiếp theo và theo dõi audit. | + +## Ví dụ hoàn chỉnh hoạt động + +Dưới đây là chương trình đầy đủ tích hợp tất cả các bước từ khởi tạo đến xác minh. Sao chép mã vào một dự án console mới và chạy nó. + + + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, dựa trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoạt động đầy đủ với các giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Tạo hình ảnh mã vạch – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Tạo hình ảnh mã vạch DotCode – hàng & cột (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Cách tạo vùng yên tĩnh (Quiet Zone) cho ITF-14 bằng Aspose.BarCode cho .NET](/barcode/english/net/itf-14-barcode-customization/itf-14-barcode-quiet-zone-configuration/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/vietnamese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md b/barcode/vietnamese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md new file mode 100644 index 000000000..d915918a2 --- /dev/null +++ b/barcode/vietnamese/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-12 +description: Tạo databar omnidirectional bằng Python và học cách tạo hình ảnh mã vạch + bằng Python sử dụng Aspose.BarCode. Thực hiện theo hướng dẫn từng bước để có giải + pháp hoàn chỉnh. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create omni directional databar +- create barcode image python +language: vi +lastmod: 2026-08-12 +og_description: Tạo databar đa hướng bằng Python và tạo hình ảnh mã vạch trong vài + phút. Hướng dẫn này trình bày một ví dụ đầy đủ, có thể chạy được. +og_image_alt: example of create omni directional databar barcode image in Python +og_title: Tạo thanh dữ liệu đa hướng – hướng dẫn Python đầy đủ +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: Create omni directional databar with Python and learn how to create + barcode image python using Aspose.BarCode. Follow the step‑by‑step guide for a + complete solution. + headline: Create omni directional databar and barcode image in Python + type: TechArticle +tags: +- barcode +- Python +- Aspose +- DataBar +title: Tạo hình ảnh databar và mã vạch đa hướng bằng Python +url: /vi/python-java/general/create-omni-directional-databar-and-barcode-image-in-python/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo omni directional databar và hình ảnh mã vạch trong Python + +Nếu bạn cần **tạo omni directional databar** trong một dự án Python, hướng dẫn này sẽ chỉ cho bạn cách thực hiện và cũng cách **tạo hình ảnh mã vạch python** bằng thư viện Aspose.BarCode. Bạn sẽ nhận được một script sẵn sàng chạy tạo ra hai tệp PNG với tỷ lệ khung hình khác nhau. + +Việc tạo DataBar tuân theo chuẩn Omni‑directional là yêu cầu phổ biến cho các ứng dụng bán lẻ và logistics. Bài học bao gồm cài đặt, cấu hình kích thước X, điều chỉnh tỷ lệ khung hình và lưu các hình ảnh cuối cùng. Không cần dịch vụ bên ngoài; mọi thứ chạy cục bộ. + +## Những gì bạn sẽ cần + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +* Python 3.8 trở lên đã được cài đặt trên máy của bạn. +* Truy cập tới terminal hoặc command prompt. +* Quyền ghi vào thư mục sẽ lưu các hình ảnh mã vạch. + +Phụ thuộc bên thứ ba duy nhất là **Aspose.BarCode for Python via .NET**, hỗ trợ loại DataBar Omni‑directional ngay từ đầu. + +## Bước 1: Cài đặt Aspose.BarCode cho Python + +Aspose.BarCode cung cấp lớp `BarcodeGenerator` được sử dụng trong mã mẫu. Cài đặt gói bằng `pip`: + +```bash +pip install aspose-barcode +``` + +Gói này bao gồm các binding runtime .NET cần thiết, vì vậy bạn không cần cài đặt .NET SDK riêng. + +## Bước 2: Nhập thư viện và tạo generator + +Dòng đầu tiên của script tạo một generator cho Omni‑directional DataBar dạng stacked. Giá trị GTIN‑14 `(01)12345678901231` được dùng làm dữ liệu mẫu. + +```python +# Step 2: Import classes and create the generator +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +# Create a generator for a stacked Omni‑directional DataBar with the required data +barcode_generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" +) +``` + +*Lý do bước này quan trọng*: Hằng số `EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL` cho thư viện biết mã hoá giá trị dưới dạng Omni‑directional DataBar, định dạng mà nhiều máy quét điểm bán hàng yêu cầu. + +## Bước 3: Đặt kích thước X (độ rộng mô-đun) + +Kích thước X xác định độ rộng của mô-đun thanh nhỏ nhất. Giá trị `2` pixel tạo ra mã vạch rõ ràng, dễ đọc mà không làm tệp quá lớn. + +```python +# Step 3: Set the basic X‑dimension (width of the smallest module) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 2 +``` + +*Lý do bước này quan trọng*: Điều chỉnh kích thước X giúp cân bằng giữa khả năng đọc và kích thước hình ảnh. Kích thước X quá nhỏ có thể hiển thị kém trên máy in độ phân giải thấp. + +## Bước 4: Cấu hình tỷ lệ khung hình và lưu hình ảnh đầu tiên + +Tỷ lệ khung hình ảnh hưởng đến chiều cao tổng thể của DataBar so với chiều rộng. Tỷ lệ `15` tạo phong cách trực quan gọn gàng. + +```python +# Step 4: Configure an aspect ratio of 15 and save the first image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 15 +barcode_generator.save("output/StackedAR15.png", BarCodeImageFormat.Png) +``` + +> **Mẹo chuyên nghiệp**: Sử dụng `pathlib.Path` để xây dựng đường dẫn đầu ra, nó sẽ tự động tạo các thư mục còn thiếu. + +```python +from pathlib import Path + +output_dir = Path("output") +output_dir.mkdir(parents=True, exist_ok=True) +barcode_generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) +``` + +## Bước 5: Thay đổi tỷ lệ khung hình cho phong cách trực quan thứ hai và lưu hình ảnh khác + +Chuyển tỷ lệ khung hình thành `30` tạo ra mã vạch cao hơn, có thể cần cho một số phần cứng máy quét cụ thể. + +```python +# Step 5: Change the aspect ratio to 30 and save the second image +barcode_generator.parameters.barcode.data_bar.aspect_ratio = 30 +barcode_generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) +``` + +*Lý do bước này quan trọng*: Các nhà bán lẻ và thiết bị quét có các ràng buộc kích thước khác nhau. Cung cấp cả hai tỷ lệ trong một script cho phép bạn tạo phong cách cần thiết mà không phải sao chép mã. + +## Script đầy đủ – tạo omni directional databar và barcode image python + +Dưới đây là ví dụ hoàn chỉnh, có thể chạy được, bao gồm tất cả các bước trước. Lưu lại dưới tên `generate_databar.py` và chạy bằng `python generate_databar.py`. + +```python +#!/usr/bin/env python3 +""" +Complete example that creates an omni directional databar +and demonstrates how to create barcode image python using Aspose.BarCode. +""" + +# Import required classes +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +from pathlib import Path + +def main(): + # Define output directory and ensure it exists + output_dir = Path("output") + output_dir.mkdir(parents=True, exist_ok=True) + + # Initialize the generator with Omni‑directional DataBar data + generator = BarcodeGenerator( + EncodeTypes.DATABAR_STACKED_OMNIDIRECTIONAL, + "(01)12345678901231" + ) + + # Set X‑dimension to 2 pixels for good readability + generator.parameters.barcode.x_dimension.pixels = 2 + + # First visual style – aspect ratio 15 + generator.parameters.barcode.data_bar.aspect_ratio = 15 + generator.save(output_dir / "StackedAR15.png", BarCodeImageFormat.Png) + + # Second visual style – aspect ratio 30 + generator.parameters.barcode.data_bar.aspect_ratio = 30 + generator.save(output_dir / "StackedAR30.png", BarCodeImageFormat.Png) + + print(f"Images saved to: {output_dir.resolve()}") + +if __name__ == "__main__": + main() +``` + +### Kết quả mong đợi + +Chạy script sẽ tạo ra các tệp sau: + +``` +output/StackedAR15.png # DataBar with aspect ratio 15 +output/StackedAR30.png # DataBar with aspect ratio 30 +``` + +Cả hai hình ảnh đều hiển thị một Omni‑directional DataBar hợp lệ, có thể quét được bằng thiết bị bán lẻ tiêu chuẩn. + +![ví dụ tạo omni directional databar barcode image trong Python](example_databar.png "tạo omni directional databar barcode image python") + +*Hình ảnh trên chỉ là placeholder minh họa hai tệp PNG đã lưu.* + +## Xử lý các vấn đề thường gặp + +| Vấn đề | Nguyên nhân | Cách khắc phục | +|-------|------------|----------------| +| `ImportError: No module named aspose` | Aspose.BarCode chưa được cài đặt hoặc được cài trong môi trường khác. | Kích hoạt môi trường ảo đúng và chạy `pip install aspose-barcode`. | +| `PermissionError` khi lưu | Script không có quyền ghi vào thư mục đích. | Chọn thư mục bạn sở hữu hoặc chạy script với quyền thích hợp. | +| Mã vạch không quét được | Kích thước X quá thấp hoặc tỷ lệ khung hình không phù hợp với máy quét. | Tăng `x_dimension.pixels` lên 3 hoặc 4, và thử các giá trị `aspect_ratio` khác (ví dụ: 20, 25). | +| Thiếu runtime .NET | Aspose.BarCode phụ thuộc vào runtime .NET trên Windows/Linux. | Cài đặt runtime .NET mới nhất từ trang Microsoft; tài liệu gói cung cấp hướng dẫn cho từng nền tảng. | + +## Mở rộng ví dụ + +Bạn có thể điều chỉnh script để tạo các biến thể DataBar khác (ví dụ: `DATABAR_STACKED`, `DATABAR_EXPANDED`). Thay đổi hằng số `EncodeTypes` cho phù hợp: + +```python +generator = BarcodeGenerator(EncodeTypes.DATABAR_EXPANDED, "(01)12345678901231") +``` + +Nếu cần nhúng mã vạch vào PDF, Aspose.PDF for Python có thể nhập trực tiếp tệp PNG hoặc bạn có thể dùng phương thức `save` với `BarCodeImageFormat.Pdf`. + +## Kết luận + +Bài hướng dẫn này đã chỉ cách **tạo omni directional databar** và cách **tạo barcode image python** bằng Aspose.BarCode. Giờ đây bạn đã có một script hoàn chỉnh, có thể tái tạo, tạo ra hai tệp PNG với tỷ lệ khung hình khác nhau, xử lý các vấn đề thường gặp và có thể mở rộng sang các định dạng mã vạch khác. + +Tiếp theo, hãy khám phá việc tạo QR code, thêm mã vạch vào hóa đơn PDF, hoặc tự động xử lý hàng loạt cho danh mục sản phẩm lớn. Mỗi chủ đề này đều dựa trên mẫu `BarcodeGenerator` đã được trình bày ở đây. Chúc bạn lập trình vui vẻ! + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong bài này. Mỗi tài nguyên bao gồm các ví dụ mã đầy đủ với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Generate barcode image – GS1 Coupon UPC-A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Create DotCode barcode image – rows & columns (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [How to create barcode image and render it in Java](/barcode/english/java/barcode-rendering-techniques/rendering-barcode-image-instance/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/barcode/vietnamese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md b/barcode/vietnamese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md new file mode 100644 index 000000000..8fc4a072d --- /dev/null +++ b/barcode/vietnamese/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-08-12 +description: Cách tạo mã vạch nhanh chóng bằng Python. Học cách tạo mã vạch từ dữ + liệu và xuất hình ảnh mã vạch chỉ với một thư viện duy nhất. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to generate barcode +- create barcode from data +- export barcode image +- Python barcode generation +- Aspose.BarCode tutorial +language: vi +lastmod: 2026-08-12 +og_description: Cách tạo mã vạch trong Python với Aspose.BarCode. Hãy làm theo hướng + dẫn này để tạo mã vạch từ dữ liệu và xuất hình ảnh mã vạch dưới dạng PNG. +og_image_alt: Screenshot showing how to generate barcode with Python code +og_title: Cách tạo mã vạch trong Python – hướng dẫn nhanh, đáng tin cậy +schemas: +- author: Aspose + dateModified: '2026-08-12' + description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + headline: How to generate barcode in Python – complete step‑by‑step guide + type: TechArticle +- description: How to generate barcode quickly using Python. Learn to create barcode + from data and export barcode image with a single library. + name: How to generate barcode in Python – complete step‑by‑step guide + steps: + - name: 1. Import the required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 2. Create barcode from data + text: The first step is to **create barcode from data**. The `BarcodeGenerator` + constructor takes the symbology and the raw string you want to encode. + - name: 3. Adjust the X‑dimension (module width) + text: The X‑dimension controls the width of each barcode module (the thin bar). + Setting it to 4 pixels gives a clear, readable image without making the file + too large. + - name: 4. Export barcode image (filled style) + text: Now you can **export barcode image** using the `save` method. The example + saves a PNG file, but you can choose JPEG, BMP, or TIFF by changing the `BarCodeImageFormat` + enum. + - name: 5. Create a second generator for an outline‑only barcode + text: If you need an outline version (empty bars), you must create a new generator + because the `filled_bars` flag cannot be toggled after the image is saved. + - name: 6. Apply the same X‑dimension setting + text: When you create a second generator, you must repeat any visual settings + you want to keep consistent. + - name: 7. Disable filled bars for an outline barcode + text: Setting `filled_bars` to `False` tells the renderer to draw only the outlines + of each module, producing a lighter image that can be useful for design purposes. + - name: 8. Export the outline barcode image + text: Finally, **export barcode image** again, this time storing the outline version. + - name: Next steps + text: '* Explore other symbologies such as QR, Code‑128, or DataMatrix by swapping + `EncodeTypes.Planet` with the desired value. * Integrate the generated PNG files + into PDF reports using libraries like `ReportLab` or `PyPDF2`. * Experiment + with dynamic X‑dimension values to adapt barcode size based on scre' + type: HowTo +tags: +- barcode +- Python +- image export +title: Cách tạo mã vạch trong Python – hướng dẫn chi tiết từng bước +url: /vi/python-java/general/how-to-generate-barcode-in-python-complete-step-by-step-guid/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách tạo mã vạch trong Python – hướng dẫn chi tiết từng bước + +Nếu bạn cần **cách tạo mã vạch** trong một ứng dụng Python, hướng dẫn này sẽ cho bạn đoạn mã chính xác cần thiết. Bạn sẽ học cách **tạo mã vạch từ dữ liệu**, điều chỉnh giao diện của nó, và **xuất hình ảnh mã vạch** dưới dạng tệp PNG — tất cả trong chưa đầy mười dòng mã. + +Việc tạo mã vạch có thể cảm thấy như một vấn đề riêng biệt so với phần còn lại của logic kinh doanh, nhưng với một thư viện duy nhất bạn có thể giữ quy trình này gọn trong mã hiện có. Trong các phần tiếp theo, bạn sẽ thấy một ví dụ đầy đủ, có thể chạy được, hiểu vì sao mỗi dòng lại quan trọng, và khám phá các biến thể phổ biến như thay đổi độ rộng mô-đun hoặc vẽ mã vạch chỉ khung viền. + +## Cách tạo mã vạch với thư viện Aspose.BarCode + +Thư viện Aspose.BarCode cho Python (qua .NET) cung cấp một API đơn giản cho nhiều loại symbology, bao gồm mã vạch Planet được sử dụng trong hướng dẫn này. Trước khi bắt đầu, hãy chắc chắn rằng bạn đã cài đặt gói: + +```bash +pip install aspose-barcode +``` + +> **Mẹo chuyên nghiệp:** Sử dụng môi trường ảo để tránh xung đột phiên bản với các dự án khác. + +### 1. Nhập các lớp cần thiết + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +Các import này cho phép bạn truy cập vào lớp tạo mã, liệt kê các loại barcode, và enum định dạng hình ảnh được sử dụng khi lưu kết quả. + +### 2. Tạo mã vạch từ dữ liệu + +Bước đầu tiên là **tạo mã vạch từ dữ liệu**. Hàm khởi tạo `BarcodeGenerator` nhận symbology và chuỗi thô bạn muốn mã hoá. + +```python +# Step 1: Create a barcode generator for the Planet symbology with data "123456" +barcode_filled = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +Giá trị `EncodeTypes.Planet` chọn mã vạch Planet, trong khi `"123456"` là dữ liệu sẽ xuất hiện trong hình ảnh cuối cùng. + +### 3. Điều chỉnh kích thước X (độ rộng mô-đun) + +Kích thước X kiểm soát độ rộng của mỗi mô-đun mã vạch (thanh mỏng). Đặt nó thành 4 pixel tạo ra hình ảnh rõ ràng, dễ đọc mà không làm tệp quá lớn. + +```python +# Step 2: Set the X‑dimension (module width) to 4 pixels +barcode_filled.parameters.barcode.x_dimension.pixels = 4 +``` + +> **Tại sao điều này quan trọng:** Kích thước X lớn hơn cải thiện độ tin cậy khi quét trên máy in độ phân giải thấp, trong khi giá trị nhỏ hơn giảm kích thước tệp cho việc sử dụng trên web. + +### 4. Xuất hình ảnh mã vạch (kiểu đầy) + +Bây giờ bạn có thể **xuất hình ảnh mã vạch** bằng phương thức `save`. Ví dụ lưu dưới dạng tệp PNG, nhưng bạn có thể chọn JPEG, BMP hoặc TIFF bằng cách thay đổi enum `BarCodeImageFormat`. + +```python +# Step 3: Save the barcode using the default filled‑bars style +barcode_filled.save("YOUR_DIRECTORY/PlanetFilled.png", BarCodeImageFormat.Png) +``` + +Tệp `PlanetFilled.png` chứa một mã vạch Planet đầy đủ, sẵn sàng để in hoặc nhúng vào PDF. + +### 5. Tạo một generator thứ hai cho mã vạch chỉ khung viền + +Nếu bạn cần phiên bản khung viền (các thanh trống), bạn phải tạo một generator mới vì cờ `filled_bars` không thể thay đổi sau khi hình ảnh đã được lưu. + +```python +# Step 4: Create a second generator for the same data to illustrate empty bars +barcode_empty = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +### 6. Áp dụng cùng cài đặt kích thước X + +Khi bạn tạo một generator thứ hai, bạn phải lặp lại mọi cài đặt hiển thị mà bạn muốn giữ nhất quán. + +```python +# Step 5: Apply the same X‑dimension setting +barcode_empty.parameters.barcode.x_dimension.pixels = 4 +``` + +### 7. Tắt thanh đầy cho mã vạch khung viền + +Đặt `filled_bars` thành `False` báo cho trình render chỉ vẽ khung viền của mỗi mô-đun, tạo ra một hình ảnh nhẹ hơn có thể hữu ích cho mục đích thiết kế. + +```python +# Step 6: Disable filled bars to produce an outline‑only barcode +barcode_empty.parameters.barcode.filled_bars = False +``` + +### 8. Xuất hình ảnh mã vạch khung viền + +Cuối cùng, **xuất hình ảnh mã vạch** một lần nữa, lần này lưu phiên bản khung viền. + +```python +# Step 7: Save the outline barcode +barcode_empty.save("YOUR_DIRECTORY/PlanetEmpty.png", BarCodeImageFormat.Png) +``` + +Bây giờ bạn có hai tệp PNG: một với các thanh đầy (`PlanetFilled.png`) và một chỉ có khung viền (`PlanetEmpty.png`). + +## Xuất hình ảnh mã vạch ở các định dạng khác (tùy chọn) + +Phương thức `save` hỗ trợ nhiều định dạng. Để xuất dưới dạng JPEG với chất lượng 90 %: + +```python +barcode_filled.save( + "YOUR_DIRECTORY/PlanetFilled.jpg", + BarCodeImageFormat.Jpeg, + quality=90 +) +``` + +Nếu bạn cần nền trong suốt cho việc sử dụng trên web, chọn PNG với kênh alpha: + +```python +barcode_filled.parameters.background_color = None # disables background fill +barcode_filled.save("YOUR_DIRECTORY/PlanetTransparent.png", BarCodeImageFormat.Png) +``` + +## Các biến thể phổ biến và trường hợp đặc biệt + +| Kịch bản | Thay đổi cần thiết | Đoạn mã | +|----------|-------------------|---------| +| **Symbology khác** (ví dụ, QR) | Sử dụng giá trị `EncodeTypes` khác | `BarcodeGenerator(EncodeTypes.QR, "https://example.com")` | +| **Màu nền trước tùy chỉnh** | Đặt `fore_color` | `barcode_filled.parameters.barcode.fore_color = Color.Blue` | +| **Độ phân giải cao hơn** | Tăng DPI bằng `image_width` và `image_height` | `barcode_filled.parameters.image_width = 300; barcode_filled.parameters.image_height = 150` | +| **Chuỗi dữ liệu lớn** | Đảm bảo độ dài dữ liệu phù hợp với quy chuẩn symbology | Xác thực độ dài trước khi tạo generator | + +> **Cảnh báo:** Cung cấp dữ liệu vượt quá độ dài tối đa cho symbology đã chọn sẽ gây ra ngoại lệ thời gian chạy. Luôn xác thực độ dài chuỗi hoặc bắt `ArgumentException`. + +## Ví dụ đầy đủ, có thể chạy + +Dưới đây là script hoàn chỉnh mà bạn có thể sao chép‑dán vào tệp có tên `generate_planet_barcode.py`. Điều chỉnh `YOUR_DIRECTORY` tới thư mục tồn tại trên máy của bạn. + +```python +# generate_planet_barcode.py +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + +def generate_barcodes(output_dir: str): + # Filled‑bars barcode + filled = BarcodeGenerator(EncodeTypes.Planet, "123456") + filled.parameters.barcode.x_dimension.pixels = 4 + filled.save(f"{output_dir}/PlanetFilled.png", BarCodeImageFormat.Png) + + # Outline‑only barcode + empty = BarcodeGenerator(EncodeTypes.Planet, "123456") + empty.parameters.barcode.x_dimension.pixels = 4 + empty.parameters.barcode.filled_bars = False + empty.save(f"{output_dir}/PlanetEmpty.png", BarCodeImageFormat.Png) + +if __name__ == "__main__": + import os + output_path = "YOUR_DIRECTORY" + os.makedirs(output_path, exist_ok=True) + generate_barcodes(output_path) + print("Barcodes generated successfully.") +``` + +Chạy script này sẽ tạo ra hai tệp PNG trong thư mục đã chỉ định. Kiểm tra kết quả bằng cách mở các hình ảnh trong bất kỳ trình xem ảnh nào; cả hai đều nên hiển thị mã vạch Planet mã hoá chuỗi `123456`. + +## Kết luận + +Bây giờ bạn đã biết **cách tạo mã vạch** trong Python bằng Aspose.BarCode, cách **tạo mã vạch từ dữ liệu**, và cách **xuất hình ảnh mã vạch** ở cả hai kiểu đầy và khung viền. Mẫu tương tự áp dụng cho các symbology khác, định dạng ảnh và tùy chỉnh hiển thị, cung cấp nền tảng linh hoạt cho bất kỳ tính năng liên quan đến mã vạch nào trong ứng dụng của bạn. + +### Các bước tiếp theo + +* Khám phá các symbology khác như QR, Code‑128, hoặc DataMatrix bằng cách thay thế `EncodeTypes.Planet` bằng giá trị mong muốn. +* Tích hợp các tệp PNG đã tạo vào báo cáo PDF bằng các thư viện như `ReportLab` hoặc `PyPDF2`. +* Thử nghiệm các giá trị X‑dimension động để điều chỉnh kích thước mã vạch dựa trên độ phân giải màn hình hoặc DPI của máy in. + +Chúc lập trình vui vẻ, và bạn có thể tự do điều chỉnh ví dụ để phù hợp với yêu cầu dự án của mình! + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã đầy đủ, hoạt động với giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Cách tạo hình ảnh mã vạch trong Java với Aspose.BarCode](/barcode/english/java/barcode-rendering-techniques/) +- [Cách tạo mã vạch Java – Hướng dẫn cấu hình đầy đủ](/barcode/english/java/barcode-configuration/) +- [Cách tạo hình ảnh mã code128 trong Java với Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/saving-barcode-images-different-formats/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file