diff --git a/barcode/arabic/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/arabic/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..4d015bff9 --- /dev/null +++ b/barcode/arabic/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-08-03 +description: دروس توليد الباركود بلغة C# توضح كيفية إنشاء باركود Planet باستخدام Aspose.BarCode، + وتعيين البُعد X، وحفظه كصور PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: ar +lastmod: 2026-08-03 +og_description: يُرشدك دليل توليد الباركود بلغة C# إلى إنشاء باركود Planet، وضبط البُعد + X، وحفظه كملف PNG باستخدام Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: مولد الباركود C# – إنشاء باركود Planet خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: مولد الباركود C# – إنشاء مثال لباركود Planet وRM4SCC +url: /ar/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# مولد الباركود C# – إنشاء مثال لباركود Planet و RM4SCC + +إذا كنت بحاجة إلى **barcode generator C#** يمكنه إنتاج رموز بريدية محددة، يوضح لك هذا الدليل بالضبط كيفية **إنشاء صور باركود Planet** باستخدام Aspose.BarCode. ستتعرف على كيفية ضبط البُعد X، وإنشاء باركود RM4SCC مطابق، وحفظ كليهما كملفات PNG—كل ذلك في بضع خطوات مختصرة. + +يغطي الدليل كل ما تحتاجه لتشغيل الكود على .NET 6 أو أحدث، يشرح لماذا كل إعداد مهم، ويشير إلى الأخطاء الشائعة مثل عرض الوحدة غير الصحيح أو نقص أذونات المجلد. في النهاية ستحصل على صورتين جاهزتين للطباعة تتوافقان مع معايير Planet و RM4SCC. + +## المتطلبات المسبقة + +* .NET 6 SDK (أو أي نسخة .NET يدعمها Aspose.BarCode) +* Visual Studio 2022 أو أي بيئة تطوير C# تفضلها +* مرجع NuGet إلى **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* إذن كتابة للمجلد الذي تخطط لتخزين ملفات PNG فيه + +لا توجد خدمات خارجية إضافية مطلوبة؛ المكتبة تتعامل مع جميع عمليات الترميز محليًا. + +## الخطوة 1: تهيئة كائن barcode generator C# + +المهمة الأولى هي إنشاء نسخة من `BarcodeGenerator`. يأخذ المُنشئ نوع الباركود (`EncodeTypes.Planet`) والبيانات التي تريد ترميزها. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*لماذا هذه الخطوة؟* +`BarcodeGenerator` هو نقطة الدخول لكل باركود تقوم بإنشائه. اختيار `EncodeTypes.Planet` يخبر المكتبة باتباع مواصفة ISO/IEC 24723 المستخدمة من قبل العديد من خدمات البريد. + +## الخطوة 2: ضبط البُعد X (عرض الوحدة) لباركود Planet + +يحدد البُعد X عرض وحدة الباركود الواحدة (أصغر شريط أو فراغ). قيمة **4 بكسل** تعمل جيدًا لمعظم طابعات الملصقات. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*لماذا هذا مهم* +إذا كانت الوحدة ضيقة جدًا، قد يصبح الباركود غير قابل للقراءة؛ وإذا كانت عريضة جدًا سيزداد حجم الملصق دون ضرورة. ضبط `Pixels` يتيح لك تحسين الباركود لدرجة دقة طابعتك المحددة. + +## الخطوة 3: حفظ باركود Planet كصورة PNG + +يقوم Aspose.BarCode بحساب ارتفاع الباركود تلقائيًا بناءً على نوع الرمز المحدد، لذا تحتاج فقط إلى تحديد مسار الملف والصيغة. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*نصيحة* +استبدل `YOUR_DIRECTORY` بمسار مطلق أو نسبي موجود على جهازك. إذا لم يكن المجلد موجودًا، فإن طريقة `Save` ستطرح استثناء `DirectoryNotFoundException`. + +**الناتج المتوقع** – ملف PNG يشبه الشكل الموضح أدناه (الصورة الفعلية غير معروضة هنا، لكنك سترى باركود Planet كلاسيكي مع حمولة رقمية `123456`). + +## الخطوة 4: تهيئة مولد ثانٍ لباركود RM4SCC + +تتطلب العديد من أنظمة البريد وجود رمزي Planet و RM4SCC على نفس القطعة البريدية. أنشئ نسخة جديدة من `BarcodeGenerator` لنوع الرمز RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*لماذا نسخة منفصلة؟* +كل نوع رمز له مجموعة إعدادات خاصة به. إعادة استخدام نفس المولد قد يؤدي إلى نقل إعدادات (مثل البُعد X) غير المثالية للباركود الثاني. + +## الخطوة 5: ضبط البُعد X لباركود RM4SCC + +RM4SCC يحترم أيضًا إعداد البُعد X، لذا نطبق نفس عرض البكسل لضمان التناسق البصري. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*نصيحة احترافية* +إذا كنت بحاجة إلى باركود أطول (مثلاً للملصقات الكبيرة)، يمكنك أيضًا ضبط `Height.Pixels`. تركه غير محدد يتيح للمكتبة حساب الارتفاع المثالي تلقائيًا. + +## الخطوة 6: حفظ باركود RM4SCC كصورة PNG + +أخيرًا، احفظ باركود RM4SCC على القرص. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +الآن لديك ملفا PNG—`PostalPlanetBarHeightNone.png` و `PostalRM4SCCBarHeightNone.png`—يمكنك تضمينهما في ملصقات البريد، طباعتهما على الأظرف، أو إرسالهما إلى خدمة طباعة طرف ثالث. + +## اختياري: تعديل الارتفاع أو استخدام صيغ صور أخرى + +إذا كان سير عملك يتطلب ارتفاعًا محددًا للباركود أو صيغة صورة مختلفة (مثل JPEG أو BMP)، يمكنك تعديل المعلمات قبل استدعاء `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**حالة حدية** – عند ضبط ارتفاع مخصص، تأكد من أن القيمة تحترم الحد الأدنى للارتفاع المطلوب وفقًا للمعيار ISO؛ وإلا قد يفشل الباركود في التحقق. + +## المشكلات الشائعة وكيفية تجنّبها + +| المشكلة | لماذا يحدث | الحل | +|---------|------------|------| +| `DirectoryNotFoundException` | المجلد الهدف غير موجود أو تم كتابة اسمه بشكل خاطئ. | أنشئ المجلد أولاً أو استخدم `Path.Combine` مع `Environment.CurrentDirectory`. | +| عدم قراءة الباركود على طابعات منخفضة الدقة | البُعد X صغير جدًا بالنسبة لدقة DPI للطابعة. | زد `XDimension.Pixels` إلى 5 – 6 لطابعات 203 dpi، أو اختبر على ملصق تجريبي. | +| استخدام نوع رمز خاطئ | تمرير `EncodeTypes.Code128` بدلاً من `EncodeTypes.Planet`. | تحقق من أن قيمة enum `EncodeTypes` تتطابق مع المعيار البريدي المطلوب. | +| مرجع فارغ على `Parameters` | استخدام نسخة أقدم من Aspose.BarCode حيث تختلف الواجهة البرمجية. | حدّث إلى أحدث حزمة NuGet (v23.12 أو أحدث). | + +## مثال كامل قابل للتنفيذ + +فيما يلي البرنامج الكامل الذي يمكنك نسخه ولصقه وتشغيله. يتضمن عبارات `using`، معالجة الأخطاء، وتعليقات تشرح كل سطر. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +تشغيل البرنامج ينشئ مجلد `Barcodes` بجوار الملف التنفيذي ويضع ملفي PNG داخلها. افتحهما بأي عارض صور للتحقق من النتيجة. + +## الخلاصة + +أصبح لديك الآن حل **barcode generator C#** يمكنه **إنشاء صور باركود Planet**، ضبط البُعد X للطباعة المثالية، وإنتاج باركود RM4SCC مطابق—كل ذلك بضع أسطر من الشيفرة. النهج يعمل مع .NET 6+، يتطلب حزمة NuGet Aspose.BarCode فقط، ويمكن توسيعه إلى رموز أخرى مثل Code128، QR، أو DataMatrix بتغيير قيمة `EncodeTypes`. + +### ما التالي؟ + +* جرّب قيمًا مختلفة لـ `XDimension.Pixels` لتتناسب مع DPI طابعتك. +* أنشئ باركود بصيغ أخرى (PDF، SVG) بتغيير enum `BarCodeImageFormat`. +* دمج ملفي PNG في ملصق واحد باستخدام مكتبة رسومية مثل **SkiaSharp**. +* استكشف كامل API الخاص بـ Aspose.BarCode للميزات المتقدمة مثل التحقق من checksum أو الخطوط المخصصة. + +لا تتردد في تعديل الشيفرة للمعالجة الدفعية أو دمجها في خدمة ويب ASP.NET Core تُعيد صور الباركود عند الطلب. برمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [إنشاء باركود PNG – نسبة أبعاد DataMatrix – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [كيفية حفظ PNG باستخدام DataMatrix C40 مع Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [دروس مولد الباركود C# – تخصيص نسب أبعاد Code 16K Barcode مع Aspose.BarCode لـ .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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/barcode-generator-c-generate-barcode-image/_index.md b/barcode/arabic/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..5e2be57bb --- /dev/null +++ b/barcode/arabic/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-03 +description: يُظهر درس توليد الباركود بلغة C# كيفية إنشاء صورة باركود باستخدام Aspose.BarCode، + وتحديد الأعمدة والصفوف، وحفظ ملفات PNG لباركود DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: ar +lastmod: 2026-08-03 +og_description: يشرح درس توليد الباركود بلغة C# كيفية إنشاء صورة باركود باستخدام Aspose.BarCode، + وتكوين أعمدة وصفوف DataBar Expanded Stacked، وحفظ ملفات PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: مولد الباركود C# – دليل خطوة بخطوة لإنشاء صورة الباركود +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: مولد الباركود C# – إنشاء صورة الباركود +url: /ar/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# مولد الباركود C# – إنشاء صورة باركود + +إذا كنت بحاجة إلى مولد باركود C# يمكنه إنشاء صورة باركود لنوع DataBar Expanded Stacked، فإن هذا الدليل سيرشدك خلال العملية بالكامل. ستتعلم كيفية ضبط إعدادات الأعمدة والصفوف، حفظ النتيجة كملف PNG، وتكييف الشيفرة للرموز الأخرى. + +إنشاء صور الباركود برمجيًا يزيل الخطوات اليدوية ويضمن التناسق عبر الفواتير، ملصقات الشحن، وأنظمة المخزون. يغطي هذا البرنامج التعليمي كل ما تحتاجه، من إعداد المشروع إلى الشيفرة المصدرية الكاملة، بحيث يمكنك تشغيل المثال فورًا. + +## المتطلبات المسبقة + +قبل أن تبدأ، تأكد من أن لديك: + +* .NET 6.0 أو أحدث مثبت +* بيئة تطوير متكاملة مثل Visual Studio 2022 (أي محرر يدعم C# يعمل) +* رخصة لـ **Aspose.BarCode for .NET** – النسخة التجريبية المجانية تعمل للاختبار +* إلمام أساسي بصياغة C# + +إذا كان أي من هذه العناصر مفقودًا، قم بتثبيت .NET SDK من dotnet.microsoft.com واحصل على حزمة Aspose.BarCode عبر NuGet باستخدام: + +```bash +dotnet add package Aspose.BarCode +``` + +## الخطوة 1: إنشاء مشروع مولد باركود C# + +أنشئ تطبيقًا جديدًا من نوع console وأضف توجيهات `using` المطلوبة: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +فئة `BarcodeGenerator` هي جوهر API مولد الباركود C#. تستقبل نوع الرمز والنص المراد ترميزه. + +## الخطوة 2: إنشاء باركود DataBar Expanded Stacked وتعيين الأعمدة + +المثال الأول ينشئ باركود بأربعة أعمدة. تعديل خاصية `Columns` يغيّر الكثافة البصرية لرمز DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**لماذا هذا مهم:** عدد الأعمدة يؤثر على كمية البيانات التي يمكن تخزينها في مساحة مضغوطة. ضبطه على 4 ينتج باركودًا أوسع يظل قابلًا للقراءة من قبل معظم الماسحات. + +## الخطوة 3: إنشاء باركود بعدد صفوف مخصص + +المثال الثاني يوضح كيفية التحكم في التخطيط العمودي عن طريق ضبط خاصية `Rows`. تكوين من ثلاثة صفوف مفيد عندما تحتاج إلى باركود أطول بسبب مساحة أفقية محدودة. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**لماذا هذا مهم:** تعديل الصفوف يتيح لك وضع الباركود في عمود ضيق مع الحفاظ على قابلية القراءة. مولد الباركود C# يعيد حساب حجم الوحدة تلقائيًا ليتوافق مع المواصفات. + +## الخطوة 4: مثال كامل قابل للتنفيذ + +فيما يلي برنامج مستقل يجمع الخطوات السابقة. انسخ الشيفرة إلى `Program.cs`، استبدل `YOUR_DIRECTORY` بمسار مجلد موجود، ثم شغّل التطبيق. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### النتيجة المتوقعة + +عند تشغيل البرنامج، سيظهر ملفان PNG في الدليل المستهدف: + +* **DatabarCols4.png** – باركود DataBar Expanded Stacked بأربعة أعمدة +* **DatabarRows3.png** – نفس البيانات مشفرة في ثلاثة صفوف + +افتح الصور بأي عارض صور؛ ستظهر باركودات حادة وقابلة للمسح جاهزة للطباعة أو الإدراج في ملفات PDF. + +## كيفية إنشاء صورة باركود بأبعاد مخصصة + +إذا كنت بحاجة إلى حجم صورة محدد، اضبط خصائص `ImageHeight` و `ImageWidth` قبل استدعاء `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +تغيير الأبعاد لا يؤثر على البيانات المشفرة؛ فهو يغير فقط تمثيل الصورة بصريًا. هذه التقنية مفيدة عند دمج الباركود في مكونات واجهة المستخدم ذات قيود تخطيط ثابتة. + +## الأخطاء الشائعة والنصائح الاحترافية + +* **فواصل المسار:** استخدم سلاسل حرفية (`@"C:\Path\file.png"`) أو `Path.Combine` لتجنب مشاكل أحرف الهروب على نظام Windows. +* **تطبيق الترخيص:** بدون ترخيص صالح، تحتوي الصور المولدة على علامة مائية. قم بتطبيق الترخيص مبكرًا في التطبيق: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **حدود الترميز:** يدعم DataBar Expanded Stacked حتى 74 حرفًا رقميًا. تجاوز هذا الحد يسبب استثناء. تحقق من طول الإدخال قبل إنشاء المولد. +* **الأداء:** إعادة استخدام كائن `BarcodeGenerator` واحد لعدة عمليات حفظ يقلل من تخصيص الذاكرة. غير خصائص `Rows` أو `Columns` فقط بين عمليات الحفظ إذا ظل النص المشفر نفسه. + +## الخطوات التالية + +الآن بعد أن أصبحت قادرًا على إنشاء صور باركود باستخدام مولد الباركود C#، فكر في استكشاف: + +* **رموز مختلفة** – جرّب `EncodeTypes.QR`، `EncodeTypes.Code128`، أو `EncodeTypes.Pdf417`. +* **تخصيص اللون** – اضبط `Parameters.Barcode.ForeColor` و `BackColor` لتتناسب مع هوية العلامة. +* **الإدراج في ملفات PDF** – دمج PNG المولدة مع Aspose.PDF لإنشاء مستندات قابلة للطباعة. + +تتيح لك هذه الإضافات بناء حل باركود متكامل للتطبيقات في المخزون، اللوجستيات، أو التجزئة. + +--- + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات 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/) +- [كيفية إنشاء باركود DataMatrix (ECC 200) باستخدام Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/arabic/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..b9841a568 --- /dev/null +++ b/barcode/arabic/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: مثال على مولد الباركود بلغة C# يوضح كيفية ضبط العرض، وكيفية تغيير الارتفاع، + وكيفية إنشاء صورة الباركود. اتبع التعليمات خطوة بخطوة. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: ar +lastmod: 2026-08-03 +og_description: مثال مولد الباركود يوضح ضبط عرض البُعد X، تغيير ارتفاع الشريط، وإنشاء + صورة باركود في C#. اتبع الخطوات لإنشاء ملفات PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: مثال على مولد الباركود – دليل العرض والارتفاع في C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: مثال على مولد الباركود في C# – تعيين العرض والارتفاع +url: /ar/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# مثال مولد الباركود بلغة C# – ضبط العرض والارتفاع + +إذا كنت بحاجة إلى **مثال مولد باركود** بلغة C#، يوضح لك هذا الدليل كيفية ضبط عرض البعد X، وكيفية تغيير ارتفاع الخط، وكيفية إنشاء ملف صورة للباركود. سترى برنامجًا كاملاً قابلاً للتنفيذ ينتج ملفي PNG بارتفاعات مختلفة. + +سيناريو شائع هو إنشاء ملصقات المنتجات حيث يجب أن يتوافق حجم الباركود مع مواصفات الماسح. بنهاية هذا الدرس ستتمكن من تعديل معلمات العرض والارتفاع برمجياً وحفظ النتيجة كصورة PNG. + +## المتطلبات المسبقة + +قبل أن تبدأ، تأكد من وجود ما يلي: + +* .NET 6 (أو أحدث) مثبت – الكود يستهدف .NET 6 SDK. +* مكتبة باركود تدعم `EncodeTypes.DatabarOmniDirectional`. يستخدم المثال **Aspose.BarCode for .NET**، لكن أي مكتبة توفر خصائص مشابهة تعمل بنفس الطريقة. +* بيئة تطوير أو محرر (Visual Studio، VS Code، Rider) لتجميع وتشغيل البرنامج. +* صلاحية كتابة في المجلد الذي سيتم حفظ ملفات PNG فيه. + +> **نصيحة احترافية:** أنشئ مجلدًا باسم `Barcodes` في جذر المشروع واستخدمه مع `Path.Combine` لتجنب كتابة مسارات مطلقة صريحة. + +## مثال مولد الباركود: التهيئة والضبط + +الخطوة الأولى هي إنشاء كائن `BarcodeGenerator` مع الترميز المطلوب وسلسلة البيانات. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +تختار قيمة التعداد `EncodeTypes.DatabarOmniDirectional` الترميز Databar Omni‑directional، وتمثل سلسلة البيانات بتنسيق GS1 `(01)12345678901231` قيمة GTIN‑14 نموذجية. تهيئة المولد مرة واحدة تسمح لك بإعادة استخدام نفس الكائن لإنشاء صور متعددة. + +## كيفية ضبط العرض (البعد X) + +يتحكم البعد X في عرض وحدة الباركود. ضبطه على 2 بكسل يجعل كل شريط ضيق بعرض 2 بكسل، وهو مطلب شائع للطباعة عالية الكثافة. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +لماذا هذا مهم: إذا كان العرض صغيرًا جدًا، قد لا يتمكن الماسح من تمييز الشرائط الفردية؛ وإذا كان كبيرًا جدًا، قد يتجاوز الباركود مساحة الملصق. اضبط قيمة البكسل لتتناسب مع DPI الطابعة وحجم الملصق المستهدف. + +## كيفية تغيير الارتفاع + +يحدد ارتفاع الشريط مدى طول ظهور الشرائط. ينشئ المثال صورتين: إحداهما بارتفاع 30 بكسل والأخرى بارتفاع 60 بكسل. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +تؤثر خاصية `BarHeight.Pixels` مباشرة على الارتفاع البصري للشرائط. تعديلها بين عمليات الحفظ يتيح لك إنشاء متغيرات متعددة من نفس البيانات دون إعادة إنشاء المولد. + +### النتيجة المتوقعة + +تشغيل البرنامج ينتج ملفي PNG في مجلد `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – الشرائط بارتفاع 30 بكسل. +* `DatabarBarHeight60Pixels.png` – الشرائط بارتفاع 60 بكسل. + +كلا الصورتين تشتركان في نفس العرض (المحدد بواسطة البعد X) وتشفّران نفس بيانات GTIN‑14. + +![Two barcode PNG files with different heights generated by C# code](barcode-example.png "Barcode generator example showing height variations") + +*نص بديل للصورة أعلاه يحتوي على الكلمة المفتاحية الأساسية لتحسين الوصول وتحسين محركات البحث.* + +## كيفية إنشاء صورة باركود في C# + +تتعامل طريقة `Save` مع تحويل بيانات الباركود إلى ملف صورة. يمكنك اختيار صيغ أخرى (JPEG، BMP، SVG) بتمرير قيمة مختلفة من تعداد `BarCodeImageFormat`. يستخدم المثال PNG لأنه يحافظ على جودة غير مضغوطة ويدعم على نطاق واسع. + +إذا كنت بحاجة إلى تضمين الباركود مباشرةً في PDF أو صفحة ويب، استرجع الصورة كـ `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +يُزيل هذا النهج الحاجة إلى ملفات مؤقتة وهو مفيد للخدمات ذات الإنتاجية العالية. + +## الاختلافات الشائعة وحالات الحافة + +| الحالة | التعديل | +|-----------|------------| +| **ترميز مختلف** | استبدل `EncodeTypes.DatabarOmniDirectional` بقيمة تعداد أخرى (مثال: `EncodeTypes.Code128`). | +| **ملصقات صغيرة جدًا** | قلل `XDimension.Pixels` إلى 1 بكسل، لكن تحقق من قابلية القراءة بالماسح. | +| **طباعة عالية الدقة** | زد كلًا من البعد X وارتفاع الشريط بنسب متناسبة (مثال: عرض 4 بكسل، ارتفاع 80 بكسل). | +| **بيانات ديناميكية** | مرّر سلسلة البيانات في وقت التشغيل، ربما من سجل قاعدة بيانات. | +| **إنشاء دفعي** | كرّر عبر مجموعة من سلاسل البيانات، مع إعادة استخدام نفس كائن `BarcodeGenerator` وتحديث `generator.Text`. | + +عند مواجهة استثناء مثل `ArgumentOutOfRangeException`، تحقق مرة أخرى من أن قيم البكسل أعداد صحيحة موجبة وأن دليل الإخراج موجود. + +## ملخص الكود الكامل + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +انسخ الكود إلى مشروع وحدة تحكم جديد، استعد حزمة NuGet الخاصة بـ Aspose.BarCode (`dotnet add package Aspose.BarCode`)، ثم نفّذ `dotnet run`. ستظهر رسائل في وحدة التحكم تؤكد حفظ الملفات. + +## الخلاصة + +يُظهر **مثال مولد الباركود** كيفية ضبط العرض، وكيفية تغيير الارتفاع، وكيفية إنشاء صورة باركود في C#. من خلال تعديل `XDimension.Pixels` و`BarHeight.Pixels` تتحكم في الحجم البصري للباركود، وتكتب طريقة `Save` النتيجة إلى ملفات PNG. جرّب ترميزات مختلفة، صيغ إخراج مختلفة، وسلاسل بيانات متنوعة لتلائم متطلبات تطبيقك. + +**الخطوات التالية** + +* استكشف **كيفية توليد باركود** بصيغ صور أخرى (SVG، JPEG) للاستخدام على الويب. +* تعلّم **إنشاء صورة باركود C#** لنقاط النهاية في ASP.NET Core التي تُعيد PNG مباشرةً إلى المتصفح. +* دمج هذا الكود مع مكتبة إنشاء PDF لتضمين الباركود في الفواتير أو ملصقات الشحن. + +لا تتردد في تعديل العينة، مشاركة نتائجك، أو طرح أسئلة في التعليقات. برمجة سعيدة! + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة شفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to Set Border for ITF-14 Barcode Customization](/barcode/english/net/itf-14-barcode-customization/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/arabic/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..8fc7d4f45 --- /dev/null +++ b/barcode/arabic/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-08-03 +description: إنشاء صورة باركود بصيغة PNG باستخدام C# وتعلم كيفية تغيير نسبة العرض + إلى الارتفاع لصور DataBar. اتبع هذا المثال الكامل مع الشيفرة والنصائح. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: ar +lastmod: 2026-08-03 +og_description: إنشاء صورة باركود PNG باستخدام C# وتعرّف على كيفية تغيير نسبة الأبعاد + لباركود DataBar. يقدم هذا الدليل كودًا جاهزًا للتنفيذ ونصائح عملية. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: إنشاء صورة باركود PNG في C# – مثال كامل مع التحكم في نسبة العرض إلى الارتفاع +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: إنشاء باركود PNG في C# – دليل خطوة بخطوة +url: /ar/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء صورة باركود PNG في C# – دليل خطوة‑بخطوة + +إذا كنت بحاجة إلى **إنشاء باركود PNG** في C#، فإن هذا الدليل يوضح لك بالضبط كيفية القيام بذلك. ستقوم بإنشاء باركود DataBar مكدس متعدد الاتجاهات، حفظه كملف PNG، وتعلم **كيفية تغيير نسبة العرض إلى الارتفاع** لتناسب بيئات المسح المختلفة. + +يغطي الدليل كل ما تحتاجه: الحزم المطلوبة، برنامج كامل قابل للتنفيذ، وتفسيرات لأسباب أهمية كل إعداد. في النهاية ستحصل على ملفي PNG—أحدهما بنسبة عرض إلى ارتفاع 15 والآخر بنسبة 30—جاهزين للاختبار أو الاستخدام الإنتاجي. + +## المتطلبات المسبقة + +قبل أن تبدأ، تأكد من وجود ما يلي: + +- .NET 6.0 SDK أو أحدث مثبت +- Visual Studio 2022 (أو أي بيئة تطوير C#) +- إشارة NuGet إلى **Aspose.BarCode** (المكتبة التي توفر `BarcodeGenerator`) +- صلاحية كتابة في الدليل الذي سيتم حفظ ملفات PNG فيه + +يمكنك إضافة حزمة Aspose.BarCode بالأمر التالي: + +```bash +dotnet add package Aspose.BarCode +``` + +## الخطوة 1: إعداد المشروع واستيراد المساحات الاسمية + +أنشئ تطبيقًا كونسول جديدًا واستورد المساحات الاسمية المطلوبة لتوليد الباركود وإجراء عمليات الإدخال/الإخراج للملفات. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**لماذا هذا مهم:** استيراد `Aspose.BarCode.Generation` يمنحك الوصول إلى `BarcodeGenerator`. إبقاء الكود داخل `Main` يجعل المثال مستقلاً وسهل التشغيل. + +## الخطوة 2: إنشاء مولد باركود للـ DataBar المكدس متعدد الاتجاهات + +أنشئ كائن `BarcodeGenerator` باستخدام النوع `EncodeTypes.DatabarStackedOmniDirectional` وسلسلة بيانات عينة من نوع GS1‑128. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**لماذا هذا مهم:** نوع الترميز المختار ينتج DataBar عالي الكثافة يمكن قراءته بواسطة معظم الماسحات الحديثة. تتبع سلسلة البيانات تنسيق معرف التطبيق GS1 (01)، وهو شائع لتحديد المنتجات. + +## الخطوة 3: تحديد بعد X (عرض الوحدة) بالبكسل + +حدد عرض الوحدة للتحكم في الحجم الكلي للباركود دون التأثير على قابلية قراءته. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**لماذا هذا مهم:** بعد X بقيمة 2 بكسل ينتج باركودًا ليس صغيرًا جدًا للماسحات ولا كبيرًا جدًا للمساحات المعتادة على الملصقات. + +## الخطوة 4: حفظ أول PNG بنسبة عرض إلى ارتفاع 15 + +قم بتعديل نسبة عرض إلى ارتفاع للـ DataBar، ثم احفظ الصورة كملف PNG. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**لماذا هذا مهم:** نسبة العرض إلى الارتفاع تتحكم في العلاقة بين الارتفاع والعرض للـ DataBar المكدس. النسبة 15 هي القيمة الافتراضية الشائعة التي توازن بين القابلية للقراءة وارتفاع الملصق. + +## الخطوة 5: تغيير نسبة العرض إلى الارتفاع إلى 30 وحفظ PNG ثاني + +عدّل نفس كائن المولد لاستخدام نسبة عرض إلى ارتفاع أكبر، ثم احفظ الصورة الثانية. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**لماذا هذا مهم:** زيادة نسبة العرض إلى الارتفاع تمتد الباركود عموديًا، مما قد يحسن موثوقية المسح على الأجهزة منخفضة الدقة أو عندما يُطبع الملصق على وسائط ضيقة. + +## النتيجة المتوقعة + +تشغيل البرنامج ينشئ ملفي PNG: + +| الملف | نسبة العرض إلى الارتفاع | الأبعاد التقريبية (بالبكسل) | +|------------------------------------|--------------------------|------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (width × height) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (width × height) | + +كلا الصورتين تحتويان على باركود DataBar واضح وقابل للقراءة يشفّر معرف GS1 `(01)12345678901231`. + +## الأسئلة الشائعة والحالات الخاصة + +### كيف يمكن تغيير خصائص بصرية أخرى؟ + +يمكنك تعديل لون المقدمة، لون الخلفية، أو إضافة نص قابل للقراءة البشرية عبر كائن `generator.Parameters.Barcode`. مثال: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### ماذا لو احتجت إلى تنسيق صورة مختلف؟ + +استبدل `BarCodeImageFormat.Png` بـ `Jpeg` أو `Bmp` أو `Gif` حسب الحاجة. يظل PNG هو الخيار الأفضل للصور الخالية من الفقدان للباركود. + +### هل تؤثر نسبة العرض إلى الارتفاع على سرعة المسح؟ + +نسب العرض إلى الارتفاع الأعلى تزيد من ارتفاع الباركود، ما قد يحسن موثوقية المسح على الأجهزة التي تواجه صعوبة مع الرموز المكدسة القصيرة. ومع ذلك، قد لا تتناسب الباركودات الطويلة جدًا مع الملصقات الصغيرة، لذا اختبرها مع الأجهزة المستهدفة. + +### هل يمكن توليد عدة باركودات داخل حلقة؟ + +نعم. أنشئ كائن `BarcodeGenerator` جديد لكل سلسلة بيانات أو أعد استخدام نفس الكائن مع تحديث `CodeText` و `DataBar.AspectRatio`. هذا يقلل من استهلاك الذاكرة عند إنشاء دفعات كبيرة. + +## نصائح احترافية + +- **إعادة استخدام المولد**: تغيير `CodeText` أو `AspectRatio` فقط دون إنشاء كائن جديد يسرّع معالجة الدفعات. +- **تحقق من المخرجات**: استخدم ماسحًا يدويًا أو تطبيقًا على الهاتف لتأكيد أن PNG المولد يُقرأ بشكل صحيح قبل النشر. +- **تسمية الملفات**: أدرج نسبة العرض إلى الارتفاع في اسم الملف (كما هو موضح) لتتبع الاختلافات أثناء الاختبار. + +## الخلاصة + +أصبحت الآن تعرف كيف **تنشئ ملفات باركود PNG** في C# وكيف **تغيّر نسبة العرض إلى الارتفاع** بدقة لرموز DataBar المكدسة متعددة الاتجاهات. يوضح المثال الكامل تهيئة المولد، ضبط بعد X، تعديل نسبة العرض إلى الارتفاع، وحفظ الصورة—كل ذلك في برنامج واحد قابل للتنفيذ. + +من هنا يمكنك استكشاف أنواع باركود إضافية، تجربة الألوان، أو دمج المولد في نظام تقارير أو جرد أكبر. برمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة شاملة مع شروحات خطوة‑بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/arabic/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..dd3cbf16e --- /dev/null +++ b/barcode/arabic/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-08-03 +description: أنشئ صورة باركود PNG بسرعة باستخدام هذا الدليل. تعلّم كيفية إنشاء صورة + باركود باستخدام Aspose.BarCode وإنشاء باركود كوكب. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: ar +lastmod: 2026-08-03 +og_description: إنشاء صورة باركود PNG فورًا. يوضح هذا الدرس كيفية إنشاء صورة باركود + وتوليد باركود كوكب باستخدام Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: إنشاء باركود PNG في بايثون – دليل برمجي كامل +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: إنشاء شيفرة باركود بصيغة PNG في بايثون – دليل خطوة بخطوة +url: /ar/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء صورة باركود PNG في بايثون – دليل خطوة بخطوة + +إذا كنت بحاجة إلى **إنشاء باركود PNG** من تطبيق بايثون الخاص بك، فإن هذا الدليل يوضح لك بالضبط كيفية ذلك. سنستعرض **كيفية إنشاء صورة باركود** باستخدام Aspose.BarCode وبشكل خاص **إنشاء باركود كوكب** بأبعاد مخصصة. + +سوف تتعلم كيفية تثبيت المكتبة، تكوين رموز Planet، ضبط معلمات الحجم، وحفظ النتيجة كملف PNG عالي الجودة. يفترض الدليل معرفة أساسية ببايثون وإصدار حديث من Python 3 (3.8 أو أحدث). لا يلزم أي خبرة سابقة بمعايير الباركود. + +--- + +## كيفية إنشاء باركود PNG باستخدام Aspose.BarCode + +يتضمن هذا القسم الخطوات الأساسية المطلوبة **لإنشاء باركود PNG**. كل خطوة تشمل مقتطف كود، شرح لأهميتها، ونصائح عملية يمكنك تطبيقها فورًا. + +### 1. تثبيت حزمة Aspose.BarCode + +توفر Aspose حزمة بايثون صافية تغلف محرك .NET الأساسي الخاص بها. قم بتثبيتها باستخدام `pip`: + +```bash +pip install aspose-barcode +``` + +*لماذا هذه الخطوة مهمة:* توفر الحزمة الفئة `BarcodeGenerator` المستخدمة طوال المثال. تثبيتها عالميًا يضمن أن المفسر يمكنه العثور على التجميع أثناء وقت التشغيل. + +### 2. استيراد الفئات المطلوبة + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*نصيحة:* استورد فقط الرموز التي تحتاجها؛ هذا يحافظ على نظافة مساحة الاسم ويسرّع تحميل الوحدة. + +### 3. إنشاء مولد باركود لرمز Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*لماذا هذا مهم:* `EncodeTypes.Planet` يخبر المحرك باستخدام معيار باركود Planet، بينما الوسيط الثاني يزود البيانات للترميز. تغيير الرمز (مثال، `EncodeTypes.Code128`) سينتج نمطًا بصريًا مختلفًا تمامًا. + +### 4. ضبط بعد X (عرض الوحدة) بالبكسل + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*شرح:* يتحكم بعد X في عرض الشريط الضيق. قيمة 4 بكسل تعطي باركود متوسط الكثافة يبقى قابلًا للمسح على معظم الأجهزة. + +### 5. تحديد ارتفاع الشريط يدويًا بالبكسل + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*لماذا قد تحتاج لتعديل هذا:* بعض طابعات التجزئة تتطلب أشرطة أطول للمسح الموثوق. الارتفاع الافتراضي عادةً 50 px؛ زيادة ذلك إلى 100 px يحسن القابلية للقراءة دون تكبير حجم الملف بشكل كبير. + +### 6. حفظ الباركود المُولد كصورة PNG + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*النتيجة:* يظهر ملف PNG باسم **PlanetBarHeight100.png** في مجلد `output`. PNG غير مضغوط، مما يجعله مثاليًا للطباعة وإدراجه في صفحات الويب. + +### 7. التحقق من النتيجة (اختياري) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*نصيحة:* عرض الصورة يؤكد أن الأبعاد تتطابق مع المعلمات التي ضبطتها. إذا ظهر الباركود مشوهًا، راجع إعدادات بعد X أو ارتفاع الشريط. + +--- + +## كيفية إنشاء صورة باركود بصيغة PNG (إعدادات بديلة) + +إذا كنت بحاجة إلى صيغة صورة مختلفة أو تريد إدراج الباركود في PDF لاحقًا، يمكنك تغيير تعداد `BarCodeImageFormat`: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*لماذا هذا مهم:* PNG يحافظ على كل بكسل، وهو أمر حاسم للباركود عالي التباين. JPEG يضيف تشوهات ضغط قد تعيق المسح، بينما BMP يوفر توافقًا مع الأدوات القديمة. + +--- + +## إنشاء باركود Planet بألوان مخصصة (متقدم) + +إلى جانب الحجم، يمكنك تخصيص ألوان المقدمة والخلفية: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*نصيحة عملية:* أزواج الألوان ذات التباين العالي (غامق على فاتح) تعظم موثوقية الماسح. تجنب استخدام درجات لون متشابهة للمقدمة والخلفية. + +--- + +## الأخطاء الشائعة وكيفية تجنبها + +| العَرَض | السبب | الحل | +|---------|-------|-----| +| الباركود لا يُمسح | بعد X صغير جدًا (≤ 2 px) | زيادة `x_dimension.pixels` إلى ما لا يقل عن 3 px | +| الصورة تظهر ضبابية | تم حفظ PNG بدقة DPI منخفضة | استخدم `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` لتحديد 300 DPI (إذا كان مدعومًا) | +| استثناء `ImportError` | لم يتم تثبيت Aspose.BarCode | نفّذ `pip install aspose-barcode` في نفس بيئة السكريبت الخاص بك | +| رمز غير صحيح | استخدمت `EncodeTypes.Code128` بدلاً من `EncodeTypes.Planet` | استبدل بـ `EncodeTypes.Planet` عند إنشاء المولد | + +--- + +## ملخص الحل الكامل + +فيما يلي السكريبت الكامل القابل للتنفيذ الذي **ينشئ باركود PNG** من البداية إلى النهاية: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +تشغيل هذا السكريبت ينتج **باركود Planet PNG** واضح يمكنك إدراجه في HTML، إرفاقه بالبريد الإلكتروني، أو طباعته على ملصقات المنتجات. + +--- + +## الخطوات التالية والمواضيع ذات الصلة + +* **التكامل مع Flask أو Django** – تقديم PNG المُولد مباشرةً من نقطة نهاية ويب. +* **إنشاء دفعي** – التكرار على قائمة معرفات المنتجات لإنشاء مجلد يحتوي على ملفات باركود PNG. +* **دمج مع إنشاء PDF** – استخدم `aspose-pdf` لوضع PNG في فاتورة أو ملصق شحن. +* **استكشاف رموز أخرى** – استبدل `EncodeTypes.Planet` بـ `EncodeTypes.QR` أو `EncodeTypes.DataMatrix` أو `EncodeTypes.Code128` لتلبية احتياجات تجارية مختلفة. + +من خلال إتقان الخطوات أعلاه، أصبحت الآن تعرف **كيفية إنشاء صورة باركود** برمجيًا ويمكنك توسيع النمط لأي معيار باركود مدعوم من قبل Aspose.BarCode. + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/arabic/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..29d5479c9 --- /dev/null +++ b/barcode/arabic/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-08-03 +description: إنشاء صورة باركود بريدي في C# بسرعة. تعلم كيفية توليد باركود بريدي، ضبط + أبعاد الباركود، وتوليد باركود Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: ar +lastmod: 2026-08-03 +og_description: إنشاء صورة باركود بريدي في C# مع هذا الدرس الكامل؛ تعلم كيفية ضبط + أبعاد الباركود، إنشاء باركود Planet، وإنتاج باركودات RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: إنشاء صورة باركود بريدي في C# – دليل برمجي كامل +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: إنشاء صورة باركود بريدي في C# – دليل خطوة بخطوة +url: /ar/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء صورة باركود بريدي في C# – دليل خطوة بخطوة + +إذا كنت بحاجة إلى **إنشاء صورة باركود بريدي** في C#، فإن هذا الدليل يوضح لك بالضبط كيفية القيام بذلك. سنغطي **كيفية توليد باركود بريدي**، **كيفية ضبط أبعاد الباركود**، وكيفية **توليد باركود Planet** للمعايير البريدية الشائعة. + +ستنتهي بملفين PNG جاهزين للاستخدام — أحدهما باركود Planet والآخر باركود RM4SCC — كل منهما بارتفاع 100 بكسل. لا تحتاج إلى أدوات إضافية بخلاف مكتبة Aspose.BarCode لـ .NET. + +## المتطلبات المسبقة + +* .NET 6 SDK أو أحدث (الكود يعمل أيضًا مع .NET Framework 4.7+) +* Visual Studio 2022 أو أي بيئة تطوير C# +* حزمة NuGet **Aspose.BarCode** (المكتبة التي توفر `BarcodeGenerator`) + +## الخطوة 1: تثبيت مكتبة الباركود + +افتح الطرفية في مجلد المشروع الخاص بك وشغّل: + +```bash +dotnet add package Aspose.BarCode +``` + +تضيف الحزمة مساحة الاسم `Aspose.BarCode`، التي تحتوي على `BarcodeGenerator` وتعداد `EncodeTypes` الضروري للباركودات البريدية. + +## الخطوة 2: تعريف مجلد الإخراج + +إنشاء مسار إخراج موثوق يمنع حدوث أخطاء وقت التشغيل عندما لا يكون المجلد موجودًا. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*لماذا هذا مهم*: `Directory.CreateDirectory` عملية لا تتغير—إنها تنشئ المجلد فقط إذا لم يكن موجودًا مسبقًا، مما يتجنب الاستثناءات في التشغيلات اللاحقة. + +## الخطوة 3: ضبط أبعاد الباركود الشائعة + +ضبط البُعد X (عرض الشريط الفردي) والارتفاع الكلي للشريط يتيح لك التحكم في الحجم البصري للصورة المُولدة. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**كيفية ضبط أبعاد الباركود**: الخاصية `Parameters.Barcode.XDimension.Pixels` تحدد عرض الشريط الضيق، بينما `Parameters.Barcode.BarHeight.Pixels` تحدد الارتفاع الكامل. عدّل هذه القيم لتتناسب مع مواصفات خدمة البريد الخاصة بك. + +## الخطوة 4: توليد باركود Planet + +Planet هو باركود بريدي يُستخدم على نطاق واسع في المملكة المتحدة. الشيفرة التالية تنشئ باركود Planet بارتفاع 100 بكسل وتحفظه كملف PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**لماذا هذا يعمل**: `EncodeTypes.Planet` يخبر المُولد باستخدام رموز Planet. طريقة `Save` تكتب ملف PNG إلى المسار المحدد، مع الحفاظ على الأبعاد التي ضبطناها مسبقًا. + +## الخطوة 5: توليد باركود RM4SCC + +RM4SCC هو المعيار الهولندي للباركود البريدي. الشيفرة أدناه تعكس مثال Planet، وتظهر **كيفية توليد باركود بريدي** من نوع مختلف بنفس الأبعاد. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +الملفان PNG الآن موجودان في مجلد `Barcodes`. فتحهما سيظهر باركودات نظيفة بارتفاع 100 بكسل جاهزة للطباعة أو الإدراج في المستندات. + +## الكود المصدر الكامل + +فيما يلي البرنامج الكامل القابل للتنفيذ الذي **ينشئ ملفات صورة باركود بريدي** لكل من معايير Planet و RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### النتيجة المتوقعة + +تشغيل البرنامج يطبع مسارات الملفات وينشئ ملفي PNG: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +كل صورة بارتفاع 100 بكسل، وعرض شريط ضيق 4 بكسل، متطابقة مع الأبعاد التي ضبطناها. + +## نصائح عملية ومشكلات شائعة + +* **أذونات المجلد** – إذا كان البرنامج يعمل تحت حساب مقيد، تأكد من أن المجلد الهدف قابل للكتابة. +* **أبعاد مختلفة** – لإنشاء باركود أعلى، زد قيمة `barHeightPixels`. للحصول على دقة أعلى، قلل قيمة `xDimensionPixels`، لكن حافظ على أن تكون ≥ 2 لتجنب عيوب العرض. +* **رموز بريدية أخرى** – Aspose.BarCode يدعم أيضًا `EncodeTypes.Postnet` و `EncodeTypes.AustralianPost`. استبدل قيمة `EncodeTypes` واحتفظ بنفس منطق الأبعاد. +* **تنسيق الصورة** – استخدم `BarCodeImageFormat.Jpeg` للحصول على حجم ملف أصغر عندما لا تكون الجودة غير الضائعة مطلوبة. + +## الخلاصة + +أنت الآن تعرف كيف **تنشئ ملفات صورة باركود بريدي** في C# عن طريق ضبط الأبعاد، اختيار الرمز المناسب، وحفظ النتيجة كملف PNG. غطى الدليل **كيفية توليد باركود بريدي**، وأظهر **توليد باركود Planet**، وشرح **كيفية ضبط أبعاد الباركود** للحصول على مخرجات متسقة. + +بعد ذلك، استكشف **تخصيص ألوان الباركود**، إضافة **نص قابل للقراءة البشرية**، أو دمج الصور في فواتير PDF. النمط نفسه ينطبق على أي نوع آخر من الباركود مدعوم من Aspose.BarCode، مما يتيح لك توسيع هذا الحل إلى سير عمل كامل لأتمتة البريد. + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية توليد الباركود - أنواع الباركود أحادية البعد](/barcode/english/net/one-dimensional-barcode-types/) +- [كيفية توليد باركود Aztec بنسبة عرض مخصصة باستخدام Aspose.BarCode لـ .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [كيفية توليد باركود Java – باركود أستراليا بوست باستخدام Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/arabic/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..451317cbc --- /dev/null +++ b/barcode/arabic/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-08-03 +description: كيفية حفظ الباركود في C# مع مثال مولد باركود خطوة بخطوة. تعلم إنشاء باركودات + Planet، وضبط الأبعاد، وتصدير صور PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: ar +lastmod: 2026-08-03 +og_description: كيفية حفظ الباركود في C# باستخدام مثال مولد الباركود. يوضح هذا الدرس + كيفية إنشاء باركودات Planet، وضبط البُعد X، وتصدير ملفات PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: كيفية حفظ الباركود في C# – دليل خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: كيفية حفظ الباركود في C# – دليل شامل لإنشاء الباركود +url: /ar/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية حفظ الباركود في C# – دليل شامل لإنشاء الباركود + +حفظ صور الباركود في C# هو طلب شائع عندما تحتاج إلى تضمين باركودات بريدية في الفواتير، ملصقات الشحن، أو بطاقات الجرد. يوضح هذا الدليل خطوة بخطوة سير عمل **c# barcode generator** العملي، بدءًا من إنشاء باركود Planet وحتى تصدير ملفات PNG للباركود المملوء والباركود الفارغ. + +سوف تتعلم كيفية ضبط عرض الشريط، تشغيل/إيقاف البارات المملوءة، والتعامل مع مجلدات الإخراج بشكل موثوق. بنهاية هذا الدرس ستحصل على مثال **barcode generator example** كامل الوظيفة يمكنك نسخه إلى أي مشروع .NET. + +## ما ستحتاجه + +قبل كتابة الكود، تأكد من وجود: + +- .NET 6.0 SDK أو أحدث (المثال يعمل مع .NET Core و .NET Framework) +- Visual Studio 2022 أو أي بيئة تطوير متكاملة متوافقة مع C# +- حزمة NuGet **Aspose.BarCode** (أو مكتبة أخرى تدعم `EncodeTypes.Planet`). قم بتثبيتها باستخدام: + +```bash +dotnet add package Aspose.BarCode +``` + +المكتبة توفر الفئة `BarcodeGenerator` المستخدمة طوال هذا الدرس. + +## إعداد بيئة التطوير + +أنشئ مشروع وحدة تحكم جديد وأضف مساحة الاسم المطلوبة: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +توفر مساحة الاسم `System.IO` الدالة `Directory.CreateDirectory`، التي تضمن وجود مجلد الإخراج قبل محاولة كتابة الملفات. + +## كيفية حفظ صور الباركود باستخدام مولد الباركود C# + +جوهر الحل هو مجموعة صغيرة من الخطوات التي تُكوّن **Planet barcode** ثم تُحفظ الصورة على القرص. الأقسام التالية تقسم العملية إلى أجزاء يمكن إدارتها. + +### الخطوة 1: تعريف مجلد الإخراج + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**لماذا؟** +تحديد مسار ثابت قد يسبب استثناء `DirectoryNotFoundException` على الأجهزة التي لا يوجد فيها المجلد. `CreateDirectory` عملية لا تتكرر—تنشئ المجلد فقط إذا كان غير موجود، مما يجعل الكود آمنًا للتنفيذ المتكرر. + +### الخطوة 2: إنشاء مولد باركود Planet (البارات المملوءة) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**لماذا؟** +`EncodeTypes.Planet` يخبر المكتبة بإنتاج باركود Planet البريدي، والذي يُستخدم على نطاق واسع من قبل خدمات البريد. السلسلة `"123456"` هي العينة؛ استبدلها بأي بيانات رقمية تحتاجها منطق عملك. + +### الخطوة 3: ضبط عرض الشريط (X‑dimension) والاحتفاظ بالبارات المملوءة الافتراضية + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**لماذا؟** +الـ X‑dimension يتحكم في العرض الفعلي لكل شريط. قيمة `4` بكسل تنتج باركودًا قابلًا للقراءة على طابعات 300 dpi القياسية. ترك `FilledBars` كـ `true` (الإعداد الافتراضي) ينتج مظهر الشريط الصلب الكلاسيكي. + +### الخطوة 4: حفظ صورة الباركود بالبارات المملوءة + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**لماذا؟** +الحفظ بصيغة PNG يحافظ على جودة الصورة غير المضغوطة، وهو أمر مهم لدقة المسح. طريقة `Save` تنشئ ملف الصورة تلقائيًا؛ كل ما عليك هو توفير المسار الكامل والصيغة المطلوبة. + +### الخطوة 5: إنشاء مولد ثانٍ لإصدار الباركود بالبارات الفارغة + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +إنشاء نسخة جديدة يضمن أن التغييرات التي تُجرى لإصدار البارات الفارغة لا تؤثر على صورة البارات المملوءة التي تم حفظها مسبقًا. + +### الخطوة 6: إلغاء تفعيل البارات المملوءة مع الحفاظ على نفس X‑dimension + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**لماذا؟** +ضبط `FilledBars = false` يُظهر الباركود فقط بإطار كل شريط، وهو ما تتطلبه بعض المعايير البريدية للتحقق البصري. + +### الخطوة 7: حفظ صورة الباركود بالبارات الفارغة + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +الآن لديك ملفا PNG—أحدهما بالبارات المملوءة والآخر بالبارات الفارغة—جاهزان للإدراج في ملفات PDF، رسائل البريد الإلكتروني HTML، أو الملصقات المطبوعة. + +## برنامج كامل قابل للتنفيذ + +فيما يلي الكود الكامل الذي يمكنك نسخه إلى `Program.cs`. يتجميع ويعمل دون تعديل (بافتراض تثبيت حزمة Aspose.BarCode). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### الناتج المتوقع + +تشغيل البرنامج يطبع سطرين مشابهين لـ: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +افتح مجلد `Barcodes` وسترى ملفي PNG. يمكن فتح كلا الصورتين في أي عارض صور أو تضمينهما مباشرةً في المستندات. + +![مثال على حفظ الباركود](barcode-example.png){: .align-center alt="مثال على حفظ الباركود"} + +## اختلافات شائعة وحالات حافة + +| السيناريو | التعديل | +|----------|------------| +| **تنسيق صورة مختلف** | غيّر `BarCodeImageFormat.Png` إلى `Jpeg` أو `Gif` أو `Bmp` حسب الحاجة. | +| **حجم إخراج مخصص** | استخدم `filled.Parameters.Image.Width` و `Height` لفرض أبعاد بكسل محددة. | +| **بيانات ديناميكية** | استبدل السلسلة الثابتة `"123456"` بمتغير يحتوي على أرقام الطلبات، معرفات التتبع، إلخ. | +| **مجلد غير موجود** | `Directory.CreateDirectory` يتعامل بالفعل مع المجلدات المفقودة؛ لا حاجة لكود إضافي. | +| **طباعة عالية الدقة** | زد `XDimension.Pixels` إلى 6–8 للطابعات 600 dpi، لكن تحقق من توافق الماسح. | + +**نصيحة احترافية:** إذا كنت بحاجة إلى إنشاء العديد من الباركودات داخل حلقة، أعد استخدام نسخة واحدة من كائن `BarcodeGenerator` وقم فقط بتغيير خاصية `CodeText` قبل كل عملية `Save`. هذا يقلل من عبء تخصيص الكائنات. + +## كيفية إنشاء باركود للمعايير الأخرى + +نفس النمط يعمل مع `EncodeTypes` أخرى مثل `Code128` أو `QR` أو `DataMatrix`. ببساطة استبدل `EncodeTypes.Planet` بالنوع المطلوب واضبط أي معلمات خاصة بالنوع (مثل `QRCodeVersion`). + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة تعمل مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية حفظ PNG باستخدام DataMatrix C40 مع Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [كيفية إنشاء باركودات DataMatrix (ECC 200) مع Aspose.BarCode لـ .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [كيفية إنشاء باركود – تكوين Code 39 مع Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/chinese/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..275b57e65 --- /dev/null +++ b/barcode/chinese/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-08-03 +description: 使用 Aspose.BarCode 的 C# 条形码生成器教程,演示如何创建 Planet 条码,设置 X 维度,并保存为 PNG 图像。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: zh +lastmod: 2026-08-03 +og_description: Barcode 生成器 C# 教程将带您一步步创建 Planet 条码、调整 X 维度,并使用 Aspose.BarCode 将其保存为 + PNG。 +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: 条形码生成器 C# – 逐步创建 Planet 条码 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: 条码生成器 C# – 创建 Planet 条码和 RM4SCC 示例 +url: /zh/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – 创建 Planet 条码和 RM4SCC 示例 + +如果您需要一个能够生成邮政专用符号的 **barcode generator C#**,本指南将准确展示如何使用 Aspose.BarCode **创建 Planet 条码** 图像。您将看到如何配置 X‑dimension、生成匹配的 RM4SCC 条码,并将两者保存为 PNG 文件——只需几个简明步骤。 + +本教程涵盖在 .NET 6 或更高版本上运行代码所需的全部内容,解释每个设置的意义,并指出常见的陷阱,如模块宽度不正确或缺少目录权限。完成后,您将拥有两张符合 Planet 和 RM4SCC 标准的可直接打印的条码图像。 + +## 前提条件 + +* .NET 6 SDK(或任何 Aspose.BarCode 支持的 .NET 版本) +* Visual Studio 2022 或您喜欢的任何 C# IDE +* 对 **Aspose.BarCode** 的 NuGet 引用(`Install-Package Aspose.BarCode`) +* 对计划存放 PNG 文件的文件夹的写入权限 + +无需额外的外部服务;该库在本地完成所有编码。 + +## 步骤 1:初始化 barcode generator C# 对象 + +第一步是创建 `BarcodeGenerator` 的实例。构造函数接受条码符号(`EncodeTypes.Planet`)和要编码的数据。 + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*为什么这一步?* +`BarcodeGenerator` 是您生成的每个条码的入口点。选择 `EncodeTypes.Planet` 告诉库遵循许多邮政服务使用的 ISO/IEC 24723 规范。 + +## 步骤 2:为 Planet 条码设置 X‑dimension(模块宽度) + +X‑dimension 定义单个条码模块(最小的条或空格)的宽度。**4 像素**的值对大多数标签打印机效果良好。 + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*为什么这很重要* +如果模块太窄,条码可能无法读取;如果太宽,标签尺寸会不必要地增大。调整 `Pixels` 可让您针对特定打印机分辨率微调条码。 + +## 步骤 3:将 Planet 条码保存为 PNG 图像 + +Aspose.BarCode 会根据所选符号自动计算条码高度,因此您只需指定文件路径和格式。 + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*提示* +将 `YOUR_DIRECTORY` 替换为您机器上存在的绝对或相对路径。如果目录不存在,`Save` 方法会抛出 `DirectoryNotFoundException`。 + +**预期输出** – 一个 PNG 文件,外观类似下图(此处未显示实际图像,但您会看到带有数值负载 `123456` 的经典 Planet 条码)。 + +## 步骤 4:为 RM4SCC 条码初始化第二个生成器 + +许多邮政系统要求在同一邮件上同时使用 Planet 和 RM4SCC 符号。为 RM4SCC 符号创建一个新的 `BarcodeGenerator` 实例。 + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*为什么需要单独的实例?* +每种符号都有自己的一套参数。重复使用同一个生成器可能会无意中保留设置(如 X‑dimension),这些设置对第二个条码并不理想。 + +## 步骤 5:为 RM4SCC 条码配置 X‑dimension + +RM4SCC 也遵循 X‑dimension 设置,因此我们使用相同的像素宽度以保持视觉一致性。 + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*专业提示* +如果需要更高的条码(例如用于更大的标签),您也可以设置 `Height.Pixels`。不设置则让库自动计算理想高度。 + +## 步骤 6:将 RM4SCC 条码保存为 PNG 图像 + +最后,将 RM4SCC 条码保存到磁盘。 + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +现在您拥有两个 PNG 文件——`PostalPlanetBarHeightNone.png` 和 `PostalRM4SCCBarHeightNone.png`——可嵌入邮件标签、打印在信封上,或发送给第三方打印服务。 + +## 可选:调整高度或使用其他图像格式 + +如果您的工作流需要特定的条码高度或不同的图像格式(例如 JPEG 或 BMP),可以在调用 `Save` 之前修改参数: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**边缘情况** – 当您设置自定义高度时,请确保该值符合 ISO 标准要求的最小高度;否则条码可能无法通过验证。 + +## 常见陷阱及其避免方法 + +| 陷阱 | 出现原因 | 解决办法 | +|---------|----------------|-----| +| `DirectoryNotFoundException` | 目标文件夹不存在或拼写错误。 | 先创建文件夹,或使用 `Path.Combine` 与 `Environment.CurrentDirectory`。 | +| 低分辨率打印机上条码不可读 | X‑dimension 对打印机 DPI 来说太小。 | 将 `XDimension.Pixels` 提升至 5 – 6(针对 203 dpi 打印机),或使用样本标签进行测试。 | +| 使用了错误的符号 | 传入 `EncodeTypes.Code128` 而非 `EncodeTypes.Planet`。 | 再次确认 `EncodeTypes` 枚举值与所需的邮政标准匹配。 | +| `Parameters` 空引用 | 使用了 Aspose.BarCode 的旧版本,API 不同。 | 升级到最新的 NuGet 包(v23.12 或更高)。 | + +## 完整可运行示例 + +下面是完整的程序,您可以复制、粘贴并运行。它包含 `using` 语句、错误处理以及解释每行代码的注释。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +运行程序后,会在可执行文件旁创建一个 `Barcodes` 文件夹,并将两个 PNG 文件放入其中。使用任意图像查看器打开以验证输出。 + +## 结论 + +您现在拥有一个 **barcode generator C#** 解决方案,能够 **创建 Planet 条码** 图像、调整 X‑dimension 以实现最佳打印,并生成匹配的 RM4SCC 条码——仅需少量代码。该方法适用于 .NET 6+,仅需 Aspose.BarCode NuGet 包,并可通过更改 `EncodeTypes` 值扩展到其他符号,如 Code128、QR 或 DataMatrix。 + +### 接下来做什么? + +* 尝试不同的 `XDimension.Pixels` 值,以匹配您打印机的 DPI。 +* 通过更改 `BarCodeImageFormat` 枚举,将条码生成其他格式(PDF、SVG)。 +* 使用如 **SkiaSharp** 的图形库将两个 PNG 文件合并为单个标签。 +* 探索完整的 Aspose.BarCode API,获取诸如校验和验证或自定义字体等高级功能。 + +欢迎将代码改编用于批处理,或集成到按需返回条码图像的 ASP.NET Core Web 服务中。祝编码愉快! + +## 接下来应该学习什么? + +以下教程涵盖与本指南技术密切相关的主题。每个资源都包含完整的可运行代码示例和逐步解释,帮助您掌握更多 API 功能并在项目中探索替代实现方法。 + +- [创建条码 PNG – DataMatrix 长宽比 – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [如何使用 DataMatrix C40 保存 PNG – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – 使用 Aspose.BarCode 为 .NET 定制 Code 16K 条码长宽比](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/chinese/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..5767a1bb0 --- /dev/null +++ b/barcode/chinese/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-03 +description: 条形码生成器 C# 教程展示了如何使用 Aspose.BarCode 生成条形码图像,设置列和行,并为 DataBar Expanded + Stacked 保存 PNG 文件。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: zh +lastmod: 2026-08-03 +og_description: 条形码生成器 C# 教程说明如何使用 Aspose.BarCode 生成条形码图像,配置 DataBar Expanded Stacked + 的列和行,并保存为 PNG 文件。 +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: C# 条形码生成器 – 生成条形码图像的分步指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: 条形码生成器 C# – 生成条形码图像 +url: /zh/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 条形码生成器 C# – 生成条形码图像 + +如果您需要一个能够为 DataBar Expanded Stacked 生成条形码图像的 C# 条形码生成器,本指南将带您完成整个过程。您将学习如何配置列和行设置,将结果保存为 PNG,并将代码适配到其他符号系统。 + +以编程方式生成条形码图像可以消除手动步骤,并确保发票、运输标签和库存系统的一致性。本教程涵盖了您所需的全部内容,从项目设置到完整源代码,让您可以立即运行示例。 + +## 先决条件 + +在开始之前,请确保您拥有: + +* 已安装 .NET 6.0 或更高版本 +* 如 Visual Studio 2022 等 IDE(任何支持 C# 的编辑器均可) +* **Aspose.BarCode for .NET** 的许可证 – 免费评估版可用于测试 +* 对 C# 语法有基本了解 + +如果缺少上述任意项,请从 dotnet.microsoft.com 安装 .NET SDK,并使用以下方式获取 Aspose.BarCode NuGet 包: + +```bash +dotnet add package Aspose.BarCode +``` + +## 步骤 1:创建条形码生成器 C# 项目 + +创建一个新的控制台应用程序并添加所需的 `using` 指令: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +`BarcodeGenerator` 类是条形码生成器 C# API 的核心。它接收符号类型和要编码的文本。 + +## 步骤 2:生成 DataBar Expanded Stacked 条形码并设置列数 + +第一个示例创建了一个具有四列的条形码。调整 `Columns` 属性会改变 DataBar Expanded Stacked 符号的视觉密度。 + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**为什么这很重要:** 列数会影响在紧凑空间中可存储的数据量。将其设置为 4 会生成更宽的条形码,且大多数扫描仪仍能读取。 + +## 步骤 3:生成具有自定义行数的条形码 + +第二个示例展示了如何通过设置 `Rows` 属性来控制垂直布局。当水平空间受限且需要更高的条形码时,三行配置非常有用。 + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**为什么这很重要:** 调整行数可以让条形码适配狭窄的列,同时保持可读性。条形码生成器 C# 会自动重新计算模块大小以符合规范。 + +## 步骤 4:完整、可运行的示例 + +下面是一个独立的程序,结合了前面的步骤。将代码复制到 `Program.cs`,将 `YOUR_DIRECTORY` 替换为现有文件夹路径,然后运行应用程序。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### 预期输出 + +运行程序后,目标目录中会出现两个 PNG 文件: + +* **DatabarCols4.png** – 具有四列的 DataBar Expanded Stacked 条形码 +* **DatabarRows3.png** – 相同数据以三行方式编码 + +使用任意图像查看器打开这些图片;它们显示出清晰、可扫描的条形码,已准备好用于打印或嵌入 PDF。 + +## 如何使用自定义尺寸生成条形码图像 + +如果需要特定的图像尺寸,请在调用 `Save` 之前调整 `ImageHeight` 和 `ImageWidth` 属性: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +更改尺寸不会影响编码数据;它仅对视觉表现进行缩放。当将条形码集成到具有固定布局约束的 UI 组件时,此技术非常有用。 + +## 常见陷阱与专业提示 + +* **路径分隔符:** 使用逐字字符串 (`@"C:\Path\file.png"`) 或 `Path.Combine` 来避免 Windows 上的转义字符问题。 +* **许可证强制:** 如果没有有效许可证,生成的图像会带有水印。请在应用程序中尽早应用许可证: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **编码限制:** DataBar Expanded Stacked 支持最多 74 个数字字符。超出此限制会抛出异常。请在创建生成器之前验证输入长度。 +* **性能:** 对多个保存操作复用同一个 `BarcodeGenerator` 实例可减少内存分配。如果编码文本保持不变,仅在保存之间更改 `Rows` 或 `Columns` 属性。 + +## 后续步骤 + +既然您已经可以使用条形码生成器 C# 生成条形码图像,接下来可以探索: + +* **不同的符号系统** – 尝试 `EncodeTypes.QR`、`EncodeTypes.Code128` 或 `EncodeTypes.Pdf417`。 +* **颜色自定义** – 设置 `Parameters.Barcode.ForeColor` 和 `BackColor` 以匹配品牌色彩。 +* **嵌入 PDF** – 将生成的 PNG 与 Aspose.PDF 结合,创建可打印文档。 + +这些扩展使您能够构建面向库存、物流或零售应用的完整条形码解决方案。 + +--- + +## 接下来您应该学习什么? + +以下教程涵盖与本指南演示的技术密切相关的主题。每个资源都包含完整的可运行代码示例和逐步说明,帮助您掌握更多 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 生成 DataMatrix 条码 (ECC 200)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/chinese/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..2b3a37644 --- /dev/null +++ b/barcode/chinese/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-08-03 +description: C# 条形码生成器示例,展示如何设置宽度、如何更改高度以及如何生成条形码图像。请按步骤操作。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: zh +lastmod: 2026-08-03 +og_description: 条形码生成器示例演示了设置 X 维度宽度、修改条码高度以及在 C# 中生成条形码图像。按照步骤创建 PNG 文件。 +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: 条形码生成器示例 – C# 宽度和高度指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: C# 条形码生成器示例 – 设置宽度和高度 +url: /zh/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# 条形码生成示例 – 设置宽度和高度 + +如果你需要一个 **条形码生成示例**(C#),本指南将向你展示如何设置 X 维度宽度、如何更改条码高度,以及如何生成条形码图像文件。你将看到一个完整、可运行的程序,它会生成两个不同高度的 PNG 文件。 + +典型的场景是创建产品标签,需要条形码尺寸符合扫描仪规格。完成本教程后,你将能够以编程方式调整宽度和高度参数,并将结果保存为 PNG 图像。 + +## 前置条件 + +在开始之前,请确保你已具备: + +* 已安装 .NET 6(或更高版本)——代码目标为 .NET 6 SDK。 +* 支持 `EncodeTypes.DatabarOmniDirectional` 的条形码库。示例使用 **Aspose.BarCode for .NET**,但任何提供类似属性的库都可以以相同方式使用。 +* 用于编译和运行程序的 IDE 或编辑器(Visual Studio、VS Code、Rider)。 +* 对将保存 PNG 文件的目录拥有写入权限。 + +> **专业提示:** 在项目根目录创建一个名为 `Barcodes` 的文件夹,并使用 `Path.Combine` 引用它,以避免硬编码绝对路径。 + +## 条形码生成示例:初始化和配置 + +第一步是使用所需的符号系统和数据字符串创建 `BarcodeGenerator` 实例。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +`EncodeTypes.DatabarOmniDirectional` 枚举选择 Databar Omni‑directional 符号系统,GS1 格式的数据字符串 `(01)12345678901231` 代表典型的 GTIN‑14 值。一次性初始化生成器后,你可以复用同一个对象来生成多张图像。 + +## 如何设置宽度(X‑维度) + +X‑维度控制条码的模块宽度。将其设为 2 像素意味着每根细条宽 2 像素,这是高密度打印的常见要求。 + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +为什么重要:如果宽度太小,扫描仪可能无法分辨单根条;如果宽度太大,条码可能超出标签空间。请根据打印机 DPI 和目标标签尺寸调整像素值。 + +## 如何更改高度 + +条码高度决定条的垂直长度。示例会创建两张图像:一张高度为 30 像素,另一张为 60 像素。 + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +`BarHeight.Pixels` 属性直接影响条的可视高度。在多次保存之间修改它,可在不重新创建生成器的情况下生成同一数据的多种变体。 + +### 预期输出 + +运行程序后,`Barcodes` 文件夹中会生成两个 PNG 文件: + +* `DatabarBarHeight30Pixels.png` – 条高为 30 像素。 +* `DatabarBarHeight60Pixels.png` – 条高为 60 像素。 + +两张图像的宽度相同(由 X‑维度决定),且编码的 GTIN‑14 数据一致。 + +![由 C# 代码生成的不同高度的两个条形码 PNG 文件](barcode-example.png "条形码生成器示例显示高度变化") + +*上面的图片 alt 文本包含了主要关键词,以提升可访问性和 SEO。* + +## 如何在 C# 中生成条形码图像 + +`Save` 方法负责将条码数据转换为图像文件。你可以通过传入不同的 `BarCodeImageFormat` 枚举值来选择其他格式(JPEG、BMP、SVG)。示例使用 PNG,因为它保持无损质量且兼容性广。 + +如果需要将条码直接嵌入 PDF 或网页,可将图像获取为 `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +此方式消除了临时文件的需求,适用于高吞吐量服务。 + +## 常见变体和边缘情况 + +| 情况 | 调整 | +|-----------|------------| +| **不同的符号系统** | 将 `EncodeTypes.DatabarOmniDirectional` 替换为其他枚举值(例如 `EncodeTypes.Code128`)。 | +| **非常小的标签** | 将 `XDimension.Pixels` 降至 1 像素,但需验证扫描可读性。 | +| **高分辨率打印** | 将 X‑维度和条高按比例同时增大(例如宽度 4 像素,高度 80 像素)。 | +| **动态数据** | 在运行时传入数据字符串,可能来源于数据库记录。 | +| **批量生成** | 对数据字符串集合进行循环,复用同一 `BarcodeGenerator` 实例并更新 `generator.Text`。 | + +当遇到 `ArgumentOutOfRangeException` 等异常时,请检查像素值是否为正整数且输出目录是否存在。 + +## 完整源码回顾 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +将代码复制到新的控制台项目中,恢复 Aspose.BarCode NuGet 包(`dotnet add package Aspose.BarCode`),然后运行 `dotnet run`。你会在控制台看到确认已保存文件的消息。 + +## 结论 + +本 **条形码生成示例** 演示了如何设置宽度、如何更改高度以及如何在 C# 中生成条形码图像。通过调整 `XDimension.Pixels` 和 `BarHeight.Pixels`,即可控制条码的视觉尺寸,而 `Save` 方法则将结果写入 PNG 文件。请尝试不同的符号系统、输出格式和数据字符串,以满足你的应用需求。 + +**后续步骤** + +* 探索 **如何在其他图像格式(SVG、JPEG)中生成条形码**,以供网页使用。 +* 学习 **在 ASP.NET Core 端点中创建条形码图像 C#**,直接将 PNG 返回给浏览器。 +* 将此代码与 PDF 生成库结合,在发票或运单中嵌入条形码。 + +欢迎自行改编示例、分享成果或在评论区提问。祝编码愉快! + + +## 接下来你应该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助你在项目中进一步掌握 API 功能并探索替代实现方式。 + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to Set Border for ITF-14 Barcode Customization](/barcode/english/net/itf-14-barcode-customization/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/chinese/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..8022a8245 --- /dev/null +++ b/barcode/chinese/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-03 +description: 在 C# 中创建条形码 PNG,并学习如何更改 DataBar 图像的宽高比。请参阅包含代码和技巧的完整示例。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: zh +lastmod: 2026-08-03 +og_description: 在 C# 中创建条形码 PNG,并了解如何更改 DataBar 条码的宽高比。本指南提供可直接运行的代码和实用技巧。 +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: 在 C# 中创建条形码 PNG – 完整示例,带宽高比控制 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: 使用 C# 创建条形码 PNG – 步骤指南 +url: /zh/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中创建条形码 PNG – 步骤指南 + +如果你需要在 C# 中**创建条形码 PNG**,本教程将一步步演示。你将生成一个堆叠全向 DataBar 条形码,将其保存为 PNG 文件,并学习**如何更改宽高比**以适应不同的扫描环境。 + +本指南涵盖了所有必需内容:所需的包、完整可运行的程序以及每个设置为何重要的解释。完成后,你将得到两个 PNG 文件——一个宽高比为 15,另一个为 30——可用于测试或生产环境。 + +## 前置条件 + +在开始之前,请确保你已经: + +- 安装了 .NET 6.0 SDK 或更高版本 +- 安装了 Visual Studio 2022(或任何 C# IDE) +- 在项目中引用了 **Aspose.BarCode**(提供 `BarcodeGenerator` 的库)的 NuGet 包 +- 对将保存 PNG 文件的目录拥有写入权限 + +你可以使用以下命令添加 Aspose.BarCode 包: + +```bash +dotnet add package Aspose.BarCode +``` + +## 第一步:创建项目并导入命名空间 + +创建一个新的控制台应用程序,并导入生成条形码和文件 I/O 所需的命名空间。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**原因说明:** 导入 `Aspose.BarCode.Generation` 可让你使用 `BarcodeGenerator`。将代码放在 `Main` 方法内部,使示例自包含且易于运行。 + +## 第二步:为堆叠全向 DataBar 创建条形码生成器 + +实例化 `BarcodeGenerator`,使用 `EncodeTypes.DatabarStackedOmniDirectional` 类型并提供示例 GS1‑128 数据字符串。 + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**原因说明:** 选用的编码类型会生成高密度 DataBar,能够被大多数现代扫描仪读取。数据字符串遵循 GS1 应用标识符 (01) 格式,常用于产品标识。 + +## 第三步:以像素为单位定义 X‑维度(模块宽度) + +设置模块宽度,以控制条形码的整体尺寸,同时不影响可读性。 + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**原因说明:** X‑维度设为 2 像素,可让条形码既不会对扫描仪太小,也不会对标签空间太大。 + +## 第四步:使用宽高比 15 保存第一张 PNG + +调整 DataBar 的宽高比,然后将图像保存为 PNG 文件。 + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**原因说明:** 宽高比决定堆叠 DataBar 的高宽关系。宽高比 15 是常见的默认值,能够在可读性和标签高度之间取得平衡。 + +## 第五步:将宽高比改为 30 并保存第二张 PNG + +修改同一生成器实例以使用更大的宽高比,然后保存第二张图像。 + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**原因说明:** 提高宽高比会在垂直方向上拉伸条形码,这可以在低分辨率设备或标签印在窄介质时提升扫描可靠性。 + +## 预期输出 + +运行程序后会生成两张 PNG 文件: + +| 文件 | 宽高比 | 大致尺寸(像素) | +|------------------------------------|--------|-----------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300(宽 × 高) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600(宽 × 高) | + +两张图像均包含清晰、可扫描的 DataBar 条形码,编码的 GS1 标识符为 `(01)12345678901231`。 + +## 常见问题与边缘情况 + +### 如何更改其他视觉属性? + +你可以通过 `generator.Parameters.Barcode` 对象调整前景色、背景色或添加可读文本。例如: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### 如果需要其他图像格式怎么办? + +将 `BarCodeImageFormat.Png` 替换为 `Jpeg`、`Bmp` 或 `Gif` 即可。PNG 仍是无损条形码图像的最佳选择。 + +### 宽高比会影响扫描速度吗? + +更高的宽高比会增加条形码的高度,这可以在对短堆叠符号处理不佳的设备上提升扫描可靠性。但极高的条形码可能无法适配小标签,需要在目标硬件上进行测试。 + +### 能否在循环中生成多个条形码? + +可以。为每个数据字符串创建新的 `BarcodeGenerator` 实例,或在更新 `CodeText` 和 `DataBar.AspectRatio` 时复用同一实例。这种方式可减少对象分配开销。 + +## 专业技巧 + +- **复用生成器**:仅更改 `CodeText` 或 `AspectRatio` 而不重新实例化对象,可加速批量处理。 +- **验证输出**:使用手持扫描仪或移动应用确认生成的 PNG 能正确读取后,再投入生产使用。 +- **文件命名**:在文件名中加入宽高比(如示例所示),便于在测试期间跟踪不同变体。 + +## 结论 + +现在你已经掌握了在 C# 中**创建条形码 PNG**文件的完整流程,并且能够**精确更改堆叠全向 DataBar 符号的宽高比**。完整示例展示了初始化、X‑维度设置、宽高比调节以及图像保存——全部在一个可运行的程序中实现。 + +接下来,你可以探索其他条形码类型、尝试颜色自定义,或将生成器集成到更大的报表或库存系统中。祝编码愉快! + +## 接下来你应该学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,帮助你在已有技巧的基础上进一步深入。每篇资源都提供完整的可运行代码示例和逐步解释,帮助你掌握更多 API 功能并在项目中尝试不同实现方式。 + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/chinese/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..3b0bf5256 --- /dev/null +++ b/barcode/chinese/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-08-03 +description: 使用本指南快速创建条形码 PNG。学习如何使用 Aspose.BarCode 生成条形码图像以及生成 Planet 条码。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: zh +lastmod: 2026-08-03 +og_description: 即时创建条形码 PNG。本教程展示如何生成条形码图像并使用 Aspose.BarCode 生成 Planet 条码。 +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: 在 Python 中创建条形码 PNG – 完整编程指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: 在 Python 中创建条形码 PNG – 步骤指南 +url: /zh/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中创建条形码 PNG – 步骤指南 + +如果您需要 **创建条形码 PNG** 文件并在 Python 应用中使用,本教程将手把手教您。我们将演示如何使用 Aspose.BarCode **生成条形码图像**,并特别展示 **生成自定义尺寸的 Planet 条形码**。 + +您将学习如何安装库、配置 Planet 符号、调整尺寸参数,并将结果保存为高质量 PNG。本文假设您具备基础的 Python 知识,并使用近期的 Python 3 版本(3.8 或更高)。无需具备条形码标准的先前经验。 + +--- + +## 使用 Aspose.BarCode 创建条形码 PNG 的方法 + +本节包含实现 **创建条形码 PNG** 所需的核心步骤。每一步都配有代码片段、重要性说明以及可直接应用的实用技巧。 + +### 1. 安装 Aspose.BarCode 包 + +Aspose 提供了一个纯 Python 包,封装了其 .NET 核心引擎。使用 `pip` 安装: + +```bash +pip install aspose-barcode +``` + +*此步骤的重要性:* 该包提供了示例中使用的 `BarcodeGenerator` 类。全局安装可确保解释器在运行时能够定位到相应的程序集。 + +### 2. 导入所需类 + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*提示:* 只导入需要的符号,可保持命名空间整洁并加快模块加载速度。 + +### 3. 为 Planet 符号创建条形码生成器 + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*此步骤的重要性:* `EncodeTypes.Planet` 告诉引擎使用 Planet 条形码标准,第二个参数提供待编码的数据。更换符号(例如 `EncodeTypes.Code128`)将产生完全不同的视觉图案。 + +### 4. 设置 X 维度(模块宽度),单位为像素 + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*说明:* X 维度控制窄条的宽度。设置为 4 像素可得到适度密集、在大多数设备上仍可扫描的条形码。 + +### 5. 手动定义条码高度,单位为像素 + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*为何需要调整:* 某些零售打印机要求更高的条码以确保可靠扫描。默认高度通常为 50 px;将其提升至 100 px 可在不显著增大文件体积的情况下提升可读性。 + +### 6. 将生成的条形码保存为 PNG 图像 + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*结果:* 名为 **PlanetBarHeight100.png** 的 PNG 文件将出现在 `output` 文件夹中。PNG 为无损格式,适合打印及网页嵌入。 + +### 7. 验证输出(可选) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*提示:* 查看图像可确认尺寸与您设置的参数相符。如果条形码出现失真,请重新检查 X 维度或条码高度的设置。 + +--- + +## 以 PNG 格式生成条形码图像的其他设置 + +如果您需要不同的图像格式或稍后将条形码嵌入 PDF,可更改 `BarCodeImageFormat` 枚举: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*此设置的重要性:* PNG 能完整保留每个像素,对高对比度条形码至关重要。JPEG 会引入压缩伪影,可能干扰扫描;而 BMP 则兼容较旧的工具。 + +--- + +## 使用自定义颜色生成 Planet 条形码(进阶) + +除了尺寸,您还可以自定义前景色和背景色: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*实用技巧:* 高对比度配色(深色在浅色背景上)可最大化扫描器的可靠性。避免前后景使用相近的色调。 + +--- + +## 常见陷阱及规避方法 + +| 症状 | 原因 | 解决方案 | +|---------|-------|-----| +| 条形码无法扫描 | X 维度过小(≤ 2 px) | 将 `x_dimension.pixels` 提升至至少 3 px | +| 图像模糊 | PNG 以低 DPI 保存 | 使用 `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` 指定 300 DPI(若支持) | +| 报错 `ImportError` | 未安装 Aspose.BarCode | 在脚本相同环境下运行 `pip install aspose-barcode` | +| 符号错误 | 使用了 `EncodeTypes.Code128` 而非 `EncodeTypes.Planet` | 创建生成器时改为 `EncodeTypes.Planet` | + +--- + +## 完整解决方案回顾 + +以下是完整、可直接运行的脚本,能够 **创建条形码 PNG** 从头到尾: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +运行此脚本后,将生成清晰的 **Planet 条形码 PNG**,您可以将其嵌入 HTML、作为邮件附件,或打印在产品标签上。 + +--- + +## 后续步骤与相关主题 + +* **与 Flask 或 Django 集成** – 直接从 Web 接口提供生成的 PNG。 +* **批量生成** – 遍历产品 ID 列表,创建一整套条形码 PNG 文件。 +* **与 PDF 生成结合** – 使用 `aspose-pdf` 将 PNG 放入发票或运单中。 +* **探索其他符号** – 将 `EncodeTypes.Planet` 替换为 `EncodeTypes.QR`、`EncodeTypes.DataMatrix` 或 `EncodeTypes.Code128`,满足不同业务需求。 + +掌握上述步骤后,您已经能够 **以编程方式生成条形码图像**,并可将该模式扩展到 Aspose.BarCode 支持的任何条形码标准。 + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/chinese/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..d4bf1537a --- /dev/null +++ b/barcode/chinese/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-08-03 +description: 快速在 C# 中创建邮政条形码图像。了解如何生成邮政条形码、设置条形码尺寸以及生成 Planet 条形码。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: zh +lastmod: 2026-08-03 +og_description: 使用本完整教程在 C# 中创建邮政条形码图像;了解如何设置条形码尺寸、生成 Planet 条形码以及生成 RM4SCC 条形码。 +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: 在 C# 中创建邮政条形码图像 – 完整编程指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: 在 C# 中创建邮政条形码图像 – 步骤指南 +url: /zh/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中创建邮政条形码图像 – 步骤指南 + +如果您需要在 C# 中**创建邮政条形码图像**,本指南将为您提供完整的操作步骤。我们将介绍**如何生成邮政条形码**、**如何设置条形码尺寸**,以及**如何生成 Planet 条形码**,覆盖常见的邮政标准。 + +完成后您将得到两个可直接使用的 PNG 文件——一个 Planet 条形码和一个 RM4SCC 条形码——每个高度为 100 px。除了 Aspose.BarCode for .NET 库外,无需其他工具。 + +## 前置条件 + +* .NET 6 SDK 或更高版本(代码同样适用于 .NET Framework 4.7+) +* Visual Studio 2022 或任意 C# IDE +* NuGet 包 **Aspose.BarCode**(提供 `BarcodeGenerator` 的库) + +## 第一步:安装条形码库 + +在项目文件夹的终端中运行: + +```bash +dotnet add package Aspose.BarCode +``` + +该包会添加 `Aspose.BarCode` 命名空间,其中包含生成邮政条形码所需的 `BarcodeGenerator` 和 `EncodeTypes` 枚举。 + +## 第二步:定义输出文件夹 + +创建可靠的输出路径可以防止在文件夹不存在时出现运行时错误。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*原因说明*:`Directory.CreateDirectory` 是幂等的——仅在文件夹不存在时创建,避免后续运行时抛出异常。 + +## 第三步:配置通用条形码尺寸 + +设置 X 维度(单根条的宽度)和整体条高可以控制生成图像的视觉大小。 + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**如何设置条形码尺寸**:`Parameters.Barcode.XDimension.Pixels` 属性定义窄条宽度,`Parameters.Barcode.BarHeight.Pixels` 属性定义完整高度。根据您的邮寄服务规范调整这些数值。 + +## 第四步:生成 Planet 条形码 + +Planet 是英国广泛使用的邮政条形码。以下代码创建一个高 100 px 的 Planet 条形码并保存为 PNG。 + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**为什么可行**:`EncodeTypes.Planet` 告诉生成器使用 Planet 符号。`Save` 方法将 PNG 文件写入指定路径,保持我们之前设置的尺寸。 + +## 第五步:生成 RM4SCC 条形码 + +RM4SCC 是荷兰的邮政条形码标准。下面的代码与 Planet 示例相同,演示**如何生成不同类型的邮政条形码**且尺寸保持一致。 + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +现在两个 PNG 文件都位于 `Barcodes` 文件夹中。打开它们即可看到高度为 100 px、可直接用于打印或嵌入文档的条形码。 + +## 完整源代码 + +以下是完整、可运行的程序,**创建邮政条形码图像**文件,支持 Planet 与 RM4SCC 两种标准。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### 预期输出 + +运行程序后会在控制台打印文件路径,并生成两个 PNG 文件: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +每张图片高度为 100 px,窄条宽度为 4 像素,符合我们设定的尺寸。 + +## 实用技巧与常见陷阱 + +* **文件夹权限** – 若程序在受限账户下运行,请确保目标文件夹可写。 +* **不同尺寸** – 若需更高的条形码,可增大 `barHeightPixels`。若需更细的分辨率,可减小 `xDimensionPixels`,但保持 ≥ 2 以避免渲染伪影。 +* **其他邮政符号** – Aspose.BarCode 还支持 `EncodeTypes.Postnet` 和 `EncodeTypes.AustralianPost`。只需替换 `EncodeTypes` 的取值,尺寸逻辑保持不变。 +* **图像格式** – 当对无损质量要求不高时,可使用 `BarCodeImageFormat.Jpeg` 以获得更小的文件体积。 + +## 结论 + +现在您已经掌握了在 C# 中**创建邮政条形码图像**文件的完整流程:配置尺寸、选择合适的符号并保存为 PNG。教程涵盖了**如何生成邮政条形码**、演示了**生成 Planet 条形码**,并解释了**如何设置条形码尺寸**以实现一致的输出。 + +接下来,您可以探索**自定义条形码颜色**、添加**可读文本**,或将图像集成到 PDF 发票中。同样的模式适用于 Aspose.BarCode 支持的任何其他条形码类型,帮助您将此方案扩展为完整的邮政自动化工作流。 + +## 接下来您可以学习什么? + +以下教程涵盖了与本指南技术密切相关的主题,提供完整的代码示例和逐步解释,帮助您掌握更多 API 功能并在项目中尝试不同实现方式。 + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to generate barcode java – Australia Post Barcode with Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/chinese/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..69700edf0 --- /dev/null +++ b/barcode/chinese/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-08-03 +description: 在 C# 中如何保存条码——一步步的条码生成器示例。学习生成 Planet 条码、设置尺寸并导出 PNG 图像。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: zh +lastmod: 2026-08-03 +og_description: 如何使用条码生成器示例在 C# 中保存条码。本教程展示了如何生成 Planet 条码、配置 X 维度以及导出 PNG 文件。 +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: 如何在 C# 中保存条形码 – 步骤指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: 如何在 C# 中保存条形码——完整的条形码生成器指南 +url: /zh/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中保存条形码 – 完整条形码生成器指南 + +在 C# 中保存条形码图像是一个常见需求,当您需要将邮政条形码嵌入发票、运单或库存标签时。本指南将带您完成实用的 **c# barcode generator** 工作流,从创建 Planet 条形码到导出填充条和空条的 PNG 文件。 + +您将学习如何设置条宽、切换填充条以及可靠地处理输出文件夹。教程结束时,您将拥有一个完整可用的 **barcode generator example**,可以复制到任何 .NET 项目中。 + +## 您需要的条件 + +在编写代码之前,请确保您拥有: + +- .NET 6.0 SDK 或更高版本(示例兼容 .NET Core 和 .NET Framework) +- Visual Studio 2022 或任何支持 C# 的 IDE +- **Aspose.BarCode** NuGet 包(或其他支持 `EncodeTypes.Planet` 的库)。使用以下方式安装: + +```bash +dotnet add package Aspose.BarCode +``` + +该库提供了在本教程中贯穿使用的 `BarcodeGenerator` 类。 + +## 设置开发环境 + +创建一个新的控制台项目并添加所需的命名空间: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +`System.IO` 命名空间为我们提供了 `Directory.CreateDirectory`,它可以在尝试写入文件之前确保输出文件夹已存在。 + +## 如何使用 C# 条形码生成器保存条形码图像 + +解决方案的核心是一系列小步骤,用于配置 **Planet 条形码** 并将图像持久化到磁盘。以下章节将把整个过程拆解为易于管理的部分。 + +### 步骤 1:定义输出文件夹 + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**为什么?** +硬编码路径可能在文件夹不存在的机器上导致 `DirectoryNotFoundException`。`CreateDirectory` 是幂等的——仅在目录缺失时创建它,使代码在重复运行时安全。 + +### 步骤 2:创建 Planet 条形码生成器(填充条) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**为什么?** +`EncodeTypes.Planet` 告诉库生成邮政 Planet 条形码,这在邮件服务中被广泛使用。字符串 `"123456"` 是示例负载;请根据业务逻辑替换为任意数字数据。 + +### 步骤 3:配置条宽(X 维度)并保持默认填充条 + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**为什么?** +X 维度控制每根条的物理宽度。`4` 像素的值在标准 300 dpi 打印机上可生成可读的条形码。保持 `FilledBars` 为 `true`(默认)会产生经典的实心条外观。 + +### 步骤 4:保存填充条条形码图像 + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**为什么?** +保存为 PNG 可保持无损图像质量,这对扫描精度至关重要。`Save` 方法会自动创建图像文件,只需提供完整路径和所需格式。 + +### 步骤 5:为空条版本创建第二个生成器 + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +创建新实例可确保对空条版本所做的更改不会影响已保存的填充条图像。 + +### 步骤 6:在保持相同 X 维度的情况下禁用填充条 + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**为什么?** +将 `FilledBars = false` 会仅渲染每根条的轮廓,某些邮政标准要求这样进行目视校验。 + +### 步骤 7:保存空条条形码图像 + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +现在您拥有两个 PNG 文件——一个带填充条,一个为空条——可直接用于 PDF、HTML 邮件或打印标签中。 + +## 完整可运行程序 + +下面是可以复制到 `Program.cs` 的完整代码。只要已安装 Aspose.BarCode 包,它即可编译运行,无需额外修改。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### 预期输出 + +运行程序后会打印两行类似的内容: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +打开 `Barcodes` 文件夹,您会看到这两个 PNG 文件。两张图片均可在任何图像查看器中打开,或直接嵌入文档。 + +![如何保存条形码示例](barcode-example.png){: .align-center alt="如何保存条形码示例"} + +## 常见变体和边缘情况 + +| 场景 | 调整 | +|----------|------------| +| **不同的图像格式** | 将 `BarCodeImageFormat.Png` 更改为 `Jpeg`、`Gif` 或 `Bmp`(视需求而定)。 | +| **自定义输出尺寸** | 使用 `filled.Parameters.Image.Width` 和 `Height` 强制指定像素尺寸。 | +| **动态数据** | 将静态的 `"123456"` 替换为包含订单号、跟踪 ID 等的变量。 | +| **不存在的文件夹** | `Directory.CreateDirectory` 已经处理缺失的目录,无需额外代码。 | +| **高分辨率打印** | 将 `XDimension.Pixels` 提升至 6–8,以适配 600 dpi 打印机,但需验证扫描仪兼容性。 | + +**专业提示:** 如果需要在循环中生成大量条形码,请复用同一个 `BarcodeGenerator` 实例,并在每次 `Save` 前仅更改 `CodeText` 属性。这样可减少对象分配开销。 + +## 如何为其他标准生成条形码 + +相同的模式同样适用于其他 `EncodeTypes`,如 `Code128`、`QR` 或 `DataMatrix`。只需将 `EncodeTypes.Planet` 替换为所需类型,并相应调整特定类型的参数(例如 `QRCodeVersion`)。 + +## 接下来您应该学习什么? + +以下教程涵盖与本指南技术紧密相关的主题,帮助您在项目中进一步掌握 API 功能并探索替代实现方式。每个资源都提供完整的可运行代码示例和逐步解释。 + +- [使用 Aspose.BarCode 将 DataMatrix C40 保存为 PNG](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [使用 Aspose.BarCode for .NET 生成 DataMatrix 条形码(ECC 200)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [生成条形码 – Code 39 配置 使用 Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/czech/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..f90c781c6 --- /dev/null +++ b/barcode/czech/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-08-03 +description: Návod na generování čárových kódů v C# ukazující, jak vytvořit Planet + čárový kód pomocí Aspose.BarCode, nastavit X‑rozměr a uložit jako PNG obrázky. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: cs +lastmod: 2026-08-03 +og_description: Návod na generátor čárových kódů v C# vás provede vytvořením Planet + čárového kódu, úpravou X‑dimenze a uložením jako PNG pomocí Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Generátor čárových kódů C# – vytvořte čárový kód Planet krok za krokem +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Generátor čárových kódů C# – vytvořte příklad čárového kódu Planet a RM4SCC +url: /cs/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generátor čárových kódů C# – vytvoření Planet čárového kódu a příklad RM4SCC + +Pokud potřebujete **barcode generator C#**, který dokáže vytvářet poštovní specifické symboly, tento návod vám ukáže, jak **vytvořit Planet čárový kód** pomocí Aspose.BarCode. Uvidíte, jak nastavit X‑dimenzi, vygenerovat odpovídající RM4SCC čárový kód a uložit oba jako PNG soubory – vše během několika stručných kroků. + +Návod pokrývá vše, co potřebujete ke spuštění kódu na .NET 6 nebo novějším, vysvětluje, proč je každé nastavení důležité, a upozorňuje na běžné úskalí, jako je nesprávná šířka modulu nebo chybějící oprávnění ke složce. Na konci budete mít dva připravené obrázky čárových kódů, které splňují standardy Planet a RM4SCC. + +## Požadavky + +Než začnete, ujistěte se, že máte: + +* .NET 6 SDK (nebo jakoukoli verzi .NET podporovanou Aspose.BarCode) +* Visual Studio 2022 nebo libovolné C# IDE dle vašeho výběru +* NuGet odkaz na **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Oprávnění k zápisu do složky, kam budete ukládat PNG soubory + +Žádné další externí služby nejsou potřeba; knihovna provádí veškeré kódování lokálně. + +## Krok 1: Inicializace objektu barcode generator C# + +Prvním úkolem je vytvořit instanci `BarcodeGenerator`. Konstruktor přijímá symbologii čárového kódu (`EncodeTypes.Planet`) a data, která mají být zakódována. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Proč tento krok?* +`BarcodeGenerator` je vstupním bodem pro každý čárový kód, který generujete. Výběrem `EncodeTypes.Planet` říkáte knihovně, aby se řídila specifikací ISO/IEC 24723 používanou mnoha poštovními službami. + +## Krok 2: Nastavení X‑dimenze (šířka modulu) pro Planet čárový kód + +X‑dimenze určuje šířku jednoho modulu čárového kódu (nejmenšího pruhu nebo mezery). Hodnota **4 pixely** funguje dobře pro většinu štítkových tiskáren. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Proč je to důležité* +Pokud je modul příliš úzký, čárový kód může být nečitelný; pokud je příliš široký, velikost štítku zbytečně roste. Úpravou `Pixels` můžete jemně doladit čárový kód pro konkrétní rozlišení tiskárny. + +## Krok 3: Uložení Planet čárového kódu jako PNG obrázku + +Aspose.BarCode automaticky vypočítá výšku čárového kódu na základě zvolené symbologie, takže stačí zadat cestu k souboru a formát. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tip* +Nahraďte `YOUR_DIRECTORY` absolutní nebo relativní cestou, která na vašem počítači existuje. Pokud složka neexistuje, metoda `Save` vyhodí `DirectoryNotFoundException`. + +**Očekávaný výstup** – PNG soubor, který vypadá podobně jako ilustrace níže (skutečný obrázek zde není zobrazen, ale uvidíte klasický Planet čárový kód s číselnou částí `123456`). + +## Krok 4: Inicializace druhého generátoru pro RM4SCC čárový kód + +Mnoho poštovních systémů vyžaduje na jednom dopise jak Planet, tak RM4SCC symboly. Vytvořte novou instanci `BarcodeGenerator` pro symbologii RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Proč samostatná instance?* +Každá symbologie má vlastní sadu parametrů. Použití stejného generátoru by mohlo neúmyslně přenést nastavení (např. X‑dimenzi), která nejsou pro druhý čárový kód optimální. + +## Krok 5: Konfigurace X‑dimenze pro RM4SCC čárový kód + +RM4SCC také respektuje nastavení X‑dimenze, takže použijeme stejnou šířku v pixelech pro vizuální konzistenci. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +Pokud potřebujete vyšší čárový kód (např. pro větší štítky), můžete také nastavit `Height.Pixels`. Pokud tuto hodnotu nenastavíte, knihovna automaticky vypočítá ideální výšku. + +## Krok 6: Uložení RM4SCC čárového kódu jako PNG obrázku + +Nakonec uložíme RM4SCC čárový kód na disk. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Nyní máte dva PNG soubory – `PostalPlanetBarHeightNone.png` a `PostalRM4SCCBarHeightNone.png` – které můžete vložit do poštovních štítků, vytisknout na obálky nebo poslat třetí straně pro tisk. + +## Volitelné: Úprava výšky nebo použití jiných formátů obrázků + +Pokud váš workflow vyžaduje konkrétní výšku čárového kódu nebo jiný formát obrázku (např. JPEG nebo BMP), můžete parametry upravit před voláním `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Hraniční případ** – Když nastavíte vlastní výšku, ujistěte se, že hodnota splňuje minimální výšku požadovanou ISO standardem; jinak může čárový kód selhat při validaci. + +## Časté úskalí a jak se jim vyhnout + +| Úskalí | Proč se to stane | Řešení | +|---------|----------------|-----| +| `DirectoryNotFoundException` | Cílová složka neexistuje nebo je špatně napsaná. | Nejprve vytvořte složku nebo použijte `Path.Combine` s `Environment.CurrentDirectory`. | +| Čárový kód nečitelný na tiskárnách s nízkým rozlišením | X‑dimenze je příliš malá pro DPI tiskárny. | Zvyšte `XDimension.Pixels` na 5 – 6 pro 203 dpi tiskárny, nebo otestujte na vzorovém štítku. | +| Špatná symbologie použita | Předání `EncodeTypes.Code128` místo `EncodeTypes.Planet`. | Zkontrolujte, že hodnota enumu `EncodeTypes` odpovídá požadovanému poštovnímu standardu. | +| Null reference na `Parameters` | Použití starší verze Aspose.BarCode, kde se API liší. | Aktualizujte na nejnovější NuGet balíček (v. 23.12 nebo novější). | + +## Kompletní spustitelný příklad + +Níže je celý program, který můžete zkopírovat, vložit a spustit. Obsahuje `using` direktivy, ošetření chyb a komentáře vysvětlující každý řádek. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Po spuštění program vytvoří složku `Barcodes` vedle spustitelného souboru a umístí do ní oba PNG soubory. Otevřete je libovolným prohlížečem obrázků a ověřte výstup. + +## Závěr + +Nyní máte **barcode generator C#** řešení, které dokáže **vytvořit Planet čárový kód**, nastavit X‑dimenzi pro optimální tisk a vygenerovat odpovídající RM4SCC čárový kód – vše během několika řádků kódu. Přístup funguje s .NET 6+, vyžaduje pouze NuGet balíček Aspose.BarCode a lze jej rozšířit na další symbologie jako Code128, QR nebo DataMatrix změnou hodnoty `EncodeTypes`. + +### Co dál? + +* Experimentujte s různými hodnotami `XDimension.Pixels`, aby odpovídaly DPI vaší tiskárny. +* Generujte čárové kódy v jiných formátech (PDF, SVG) změnou enumu `BarCodeImageFormat`. +* Spojte oba PNG soubory do jednoho štítku pomocí grafické knihovny jako **SkiaSharp**. +* Prozkoumejte kompletní Aspose.BarCode API pro pokročilé funkce, jako je validace kontrolního součtu nebo vlastní písma. + +Neváhejte kód přizpůsobit pro hromadné zpracování nebo jej integrovat do ASP.NET Core webové služby, která na vyžádání vrací obrázky čárových kódů. Šť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ými vysvětleními, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/czech/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..4522e16de --- /dev/null +++ b/barcode/czech/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-08-03 +description: Návod na generátor čárových kódů v C# ukazuje, jak vygenerovat obrázek + čárového kódu pomocí Aspose.BarCode, nastavit sloupce a řádky a uložit PNG soubory + pro DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: cs +lastmod: 2026-08-03 +og_description: Návod na generátor čárových kódů v C# vysvětluje, jak vytvořit obrázek + čárového kódu pomocí Aspose.BarCode, nakonfigurovat sloupce a řádky DataBar Expanded + Stacked a uložit soubory PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Generátor čárových kódů v C# – krok za krokem průvodce generováním obrázku + čárového kódu +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Generátor čárových kódů C# – vytvořit obrázek čárového kódu +url: /cs/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generátor čárových kódů C# – generování obrázku čárového kódu + +Pokud potřebujete generátor čárových kódů C#, který dokáže vytvořit obrázek čárového kódu pro DataBar Expanded Stacked, tento průvodce vás provede celým procesem. Naučíte se, jak nastavit sloupce a řádky, uložit výsledek jako PNG a přizpůsobit kód pro další symbologie. + +Programové generování obrázků čárových kódů odstraňuje ruční kroky a zajišťuje konzistenci napříč fakturami, štítky pro dopravu a skladovými systémy. Tento tutoriál pokrývá vše, co potřebujete, od nastavení projektu až po kompletní zdrojový kód, takže můžete příklad spustit okamžitě. + +## Požadavky + +Než začnete, ujistěte se, že máte: + +* .NET 6.0 nebo novější nainstalovaný +* IDE, například Visual Studio 2022 (funguje jakýkoli editor podporující C#) +* Licenci pro **Aspose.BarCode for .NET** – zdarma k vyzkoušení stačí pro testování +* Základní znalost syntaxe C# + +Pokud některá z těchto položek chybí, nainstalujte .NET SDK z dotnet.microsoft.com a získejte NuGet balíček Aspose.BarCode pomocí: + +```bash +dotnet add package Aspose.BarCode +``` + +## Krok 1: Vytvořte projekt generátoru čárových kódů C# + +Vytvořte novou konzolovou aplikaci a přidejte potřebné `using` direktivy: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +Třída `BarcodeGenerator` je jádrem API generátoru čárových kódů C#. Přijímá typ symbologie a text, který má být zakódován. + +## Krok 2: Vygenerujte DataBar Expanded Stacked čárový kód a nastavte sloupce + +První příklad vytváří čárový kód se čtyřmi sloupci. Úprava vlastnosti `Columns` mění vizuální hustotu symbologie DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Proč je to důležité:** Počet sloupců ovlivňuje množství dat, která lze uložit do kompaktního prostoru. Nastavení na 4 vytvoří širší čárový kód, který zůstává čitelný většinou skenerů. + +## Krok 3: Vygenerujte čárový kód s vlastním počtem řádků + +Druhý příklad ukazuje, jak ovládat vertikální rozložení nastavením vlastnosti `Rows`. Konfigurace se třemi řádky je užitečná, když potřebujete vyšší čárový kód při omezeném horizontálním prostoru. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Proč je to důležité:** Úprava řádků vám umožní umístit čárový kód do úzkého sloupce při zachování čitelnosti. Generátor čárových kódů C# automaticky přepočítá velikost modulu tak, aby splňoval specifikaci. + +## Krok 4: Kompletní, spustitelný příklad + +Níže je samostatný program, který kombinuje předchozí kroky. Zkopírujte kód do souboru `Program.cs`, nahraďte `YOUR_DIRECTORY` existující cestou ke složce a spusťte aplikaci. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Očekávaný výstup + +Po spuštění programu se v cílovém adresáři objeví dva PNG soubory: + +* **DatabarCols4.png** – DataBar Expanded Stacked čárový kód se čtyřmi sloupci +* **DatabarRows3.png** – stejná data zakódovaná ve třech řádcích + +Otevřete obrázky libovolným prohlížečem; zobrazí ostré, skenovatelné čárové kódy připravené k tisku nebo vložení do PDF. + +## Jak vygenerovat obrázek čárového kódu s vlastními rozměry + +Pokud potřebujete konkrétní velikost obrázku, upravte vlastnosti `ImageHeight` a `ImageWidth` před voláním `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Změna rozměrů neovlivní zakódovaná data; pouze škáluje vizuální reprezentaci. Tato technika je užitečná při integraci čárových kódů do UI komponent s pevnými rozloženími. + +## Časté problémy a tipy pro profesionály + +* **Oddělovače cest:** Používejte doslovné řetězce (`@"C:\Path\file.png"`) nebo `Path.Combine`, abyste se vyhnuli problémům s únikovými znaky ve Windows. +* **Vynucení licence:** Bez platné licence obsahují vygenerované obrázky vodoznak. Licenci aplikujte co nejdříve v aplikaci: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Limity kódování:** DataBar Expanded Stacked podporuje až 74 číselných znaků. Překročení tohoto limitu vyvolá výjimku. Ověřte délku vstupu před vytvořením generátoru. +* **Výkon:** Opakované použití jedné instance `BarcodeGenerator` pro více ukládání snižuje alokaci paměti. Měňte vlastnosti `Rows` nebo `Columns` mezi ukládáními jen pokud se zakódovaný text nemění. + +## Další kroky + +Nyní, když umíte generovat obrázky čárových kódů pomocí generátoru čárových kódů C#, můžete zkusit: + +* **Různé symbologie** – vyzkoušejte `EncodeTypes.QR`, `EncodeTypes.Code128` nebo `EncodeTypes.Pdf417`. +* **Přizpůsobení barev** – nastavte `Parameters.Barcode.ForeColor` a `BackColor` podle firemní identity. +* **Vkládání do PDF** – spojte vygenerované PNG s Aspose.PDF a vytvořte tisknutelné dokumenty. + +Tyto rozšíření vám umožní postavit plnohodnotné řešení čárových kódů pro skladové, logistické nebo maloobchodní aplikace. + +--- + + +## 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í 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 Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/czech/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..f5dae2a12 --- /dev/null +++ b/barcode/czech/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,228 @@ +--- +category: general +date: 2026-08-03 +description: Příklad generátoru čárových kódů v C# ukazující, jak nastavit šířku, + jak změnit výšku a jak vygenerovat obrázek čárového kódu. Postupujte podle krok‑za‑krokem + instrukcí. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: cs +lastmod: 2026-08-03 +og_description: Příklad generátoru čárových kódů demonstruje nastavení šířky X‑dimenze, + změnu výšky čáry a generování obrázku čárového kódu v C#. Postupujte podle kroků + k vytvoření souborů PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Příklad generátoru čárových kódů – průvodce šířkou a výškou v C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Příklad generátoru čárových kódů v C# – nastavení šířky a výšky +url: /cs/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< 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ů v C# – nastavení šířky a výšky + +Pokud potřebujete **příklad generátoru čárových kódů** v C#, tento návod vám ukáže, jak nastavit šířku X‑dimenze, jak změnit výšku čáry a jak vygenerovat soubor s obrázkem čárového kódu. Uvidíte kompletní, spustitelný program, který vytvoří dva PNG soubory s různou výškou. + +Typickým scénářem je tvorba štítků produktů, kde velikost čárového kódu musí splňovat specifikace skeneru. Na konci tohoto tutoriálu budete schopni programově upravit parametry šířky a výšky a výsledek uložit jako PNG obrázek. + +## Požadavky + +Než začnete, ujistěte se, že máte: + +* .NET 6 (nebo novější) nainstalovaný – kód cílí na .NET 6 SDK. +* Knihovnu čárových kódů, která podporuje `EncodeTypes.DatabarOmniDirectional`. Příklad používá **Aspose.BarCode for .NET**, ale jakákoli knihovna poskytující podobné vlastnosti funguje stejně. +* IDE nebo editor (Visual Studio, VS Code, Rider) pro kompilaci a spuštění programu. +* Oprávnění k zápisu do adresáře, kam budou PNG soubory uloženy. + +> **Tip:** Vytvořte složku pojmenovanou `Barcodes` v kořenovém adresáři projektu a odkazujte na ni pomocí `Path.Combine`, abyste se vyhnuli pevně zakódovaným absolutním cestám. + +## Příklad generátoru čárových kódů: inicializace a konfigurace + +Prvním krokem je vytvořit instanci `BarcodeGenerator` s požadovanou symbologií a řetězcem dat. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +Výčtový typ `EncodeTypes.DatabarOmniDirectional` vybírá symbologii Databar Omni‑directional a řetězec dat ve formátu GS1 `(01)12345678901231` představuje typickou hodnotu GTIN‑14. Inicializace generátoru jednou vám umožní znovu použít stejný objekt pro více obrázků. + +## Jak nastavit šířku (X‑dimenzi) + +X‑dimenze řídí šířku modulu čárového kódu. Nastavením na 2 pixely se každá úzká čára stane 2 pixely širokou, což je běžná požadavek pro tisk s vysokou hustotou. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Proč je to důležité: Pokud je šířka příliš malá, skenery nemusí rozpoznat jednotlivé čáry; pokud je příliš velká, čárový kód může přesáhnout prostor štítku. Upravit hodnotu pixelů tak, aby odpovídala DPI tiskárny a cílové velikosti štítku. + +## Jak změnit výšku + +Výška čáry určuje, jak vysoké čáry budou vypadat. Příklad vytváří dva obrázky: jeden s výškou 30 pixelů a druhý s výškou 60 pixelů. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Vlastnost `BarHeight.Pixels` přímo ovlivňuje vizuální výšku čar. Změnou mezi ukládáním můžete generovat více variant ze stejného datového payloadu, aniž byste museli znovu vytvářet generátor. + +### Očekávaný výstup + +Spuštěním programu se vygenerují dva PNG soubory ve složce `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – čáry jsou vysoké 30 pixelů. +* `DatabarBarHeight60Pixels.png` – čáry jsou vysoké 60 pixelů. + +Oba obrázky mají stejnou šířku (určenou X‑dimenzí) a kódují identická data GTIN‑14. + +![Dva PNG soubory čárových kódů s různou výškou vygenerované pomocí C# kódu](barcode-example.png "Příklad generátoru čárových kódů ukazující variace výšky") + +*Výše uvedený alternativní text obrázku obsahuje hlavní klíčové slovo pro přístupnost a SEO.* + +## Jak v C# vygenerovat obrázek čárového kódu + +Metoda `Save` provádí konverzi dat čárového kódu do souboru s obrázkem. Můžete zvolit jiné formáty (JPEG, BMP, SVG) předáním jiné hodnoty výčtu `BarCodeImageFormat`. Příklad používá PNG, protože zachovává bezztrátovou kvalitu a je široce podporován. + +Pokud potřebujete vložit čárový kód přímo do PDF nebo webové stránky, načtěte obrázek jako `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Tento přístup eliminuje potřebu dočasných souborů a je užitečný pro služby s vysokým průtokem. + +## Běžné variace a okrajové případy + +| Situace | Úprava | +|-----------|------------| +| **Jiná symbologie** | Nahraďte `EncodeTypes.DatabarOmniDirectional` jinou hodnotou výčtu (např. `EncodeTypes.Code128`). | +| **Velmi malé štítky** | Snižte `XDimension.Pixels` na 1 pixel, ale ověřte čitelnost skenerem. | +| **Tisk ve vysokém rozlišení** | Zvyšte jak X‑dimenzi, tak výšku čáry proporcionálně (např. 4 px šířka, 80 px výška). | +| **Dynamická data** | Předávejte řetězec dat za běhu, například z databázového záznamu. | +| **Dávkové generování** | Procházejte kolekci řetězců dat a opakovaně používejte stejnou instanci `BarcodeGenerator`, přičemž aktualizujete `generator.Text`. | + +Když narazíte na výjimku jako `ArgumentOutOfRangeException`, zkontrolujte, že hodnoty pixelů jsou kladná celá čísla a že výstupní adresář existuje. + +## Kompletní přehled zdrojového kódu + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Zkopírujte kód do nového konzolového projektu, obnovte NuGet balíček Aspose.BarCode (`dotnet add package Aspose.BarCode`) a spusťte `dotnet run`. V konzoli uvidíte zprávy potvrzující uložení souborů. + +## Závěr + +Tento **příklad generátoru čárových kódů** ukazuje, jak nastavit šířku, jak změnit výšku a jak vygenerovat obrázek čárového kódu v C#. Úpravou `XDimension.Pixels` a `BarHeight.Pixels` řídíte vizuální velikost čárového kódu a metoda `Save` zapíše výsledek do PNG souborů. Experimentujte s různými symbologiemi, výstupními formáty a řetězci dat, aby vyhovovaly požadavkům vaší aplikace. + +**Další kroky** + +* Prozkoumejte **jak generovat čárový kód** v jiných formátech obrázků (SVG, JPEG) pro webové použití. +* Naučte se **vytvořit obrázek čárového kódu c#** pro koncové body ASP.NET Core, které přímo vrací PNG prohlížeči. +* Kombinujte tento kód s knihovnou pro generování PDF, abyste vložili čárové kódy do faktur nebo přepravních štítků. + +Neváhejte upravit ukázku, sdílet své výsledky nebo klást otázky v komentářích. Šť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í příklady kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy ve vašich projektech. + +- [Jak generovat čárový kód – jednorozměrné typy čárových kódů](/barcode/english/net/one-dimensional-barcode-types/) +- [Jak nastavit okraj pro přizpůsobení ITF-14 čárového kódu](/barcode/english/net/itf-14-barcode-customization/) +- [Jak generovat DataMatrix čárové kódy (ECC 200) s Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/czech/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..08bda4fc9 --- /dev/null +++ b/barcode/czech/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-08-03 +description: Vytvořte PNG čárový kód v C# a naučte se, jak změnit poměr stran pro + obrázky DataBar. Sledujte tento kompletní příklad s kódem a tipy. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: cs +lastmod: 2026-08-03 +og_description: Vytvořte PNG čárový kód v C# a zjistěte, jak změnit poměr stran pro + DataBar čárové kódy. Tento průvodce vám poskytuje připravený kód k okamžitému spuštění + a praktické tipy. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Vytvořte PNG čárový kód v C# – kompletní příklad s řízením poměru stran +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Vytvořte PNG čárový kód v C# – krok za krokem +url: /cs/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření PNG čárového kódu v C# – krok za krokem + +Pokud potřebujete **create barcode PNG** v C#, tento tutoriál vám ukáže přesně jak. Vygenerujete vrstvený omnidirekcionální DataBar čárový kód, uložíte jej jako PNG soubor a naučíte se **jak změnit poměr stran** tak, aby vyhovoval různým skenovacím prostředím. + +Průvodce pokrývá vše, co potřebujete: požadované balíčky, kompletní spustitelný program a vysvětlení, proč má každé nastavení význam. Na konci budete mít dva PNG soubory — jeden s poměrem stran 15 a druhý s 30 — připravené k testování nebo produkčnímu použití. + +## Požadavky + +Než začnete, ujistěte se, že máte: + +- .NET 6.0 SDK nebo novější nainstalovaný +- Visual Studio 2022 (nebo jakékoli C# IDE) +- NuGet odkaz na **Aspose.BarCode** (knihovna, která poskytuje `BarcodeGenerator`) +- Oprávnění k zápisu do adresáře, kam budou PNG soubory uloženy + +Balíček Aspose.BarCode můžete přidat následujícím příkazem: + +```bash +dotnet add package Aspose.BarCode +``` + +## Krok 1: Nastavení projektu a import jmenných prostorů + +Vytvořte novou konzolovou aplikaci a importujte jmenné prostory potřebné pro generování čárových kódů a práci se soubory. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Proč je to důležité:** Import `Aspose.BarCode.Generation` vám poskytuje přístup k `BarcodeGenerator`. Umístění kódu uvnitř `Main` dělá příklad samostatným a snadno spustitelným. + +## Krok 2: Vytvoření generátoru čárového kódu pro vrstvený omnidirekcionální DataBar + +Instancujte `BarcodeGenerator` s typem `EncodeTypes.DatabarStackedOmniDirectional` a ukázkovým řetězcem dat GS1‑128. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Proč je to důležité:** Vybraný typ kódování vytváří vysoce hustý DataBar, který lze přečíst většinou moderních skenerů. Řetězec dat odpovídá formátu GS1 Application Identifier (01), který je běžný pro identifikátory produktů. + +## Krok 3: Definování X‑dimenze (šířky modulu) v pixelech + +Nastavte šířku modulu, aby se řídila celková velikost čárového kódu, aniž by to ovlivnilo jeho čitelnost. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Proč je to důležité:** X‑dimenze 2 pixely dává čárový kód, který není ani příliš malý pro skenery, ani příliš velký pro typické štítky. + +## Krok 4: Uložení prvního PNG s poměrem stran 15 + +Upravte poměr stran DataBar a poté uložte obrázek jako PNG soubor. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Proč je to důležité:** Poměr stran řídí vztah výšky k šířce vrstveného DataBar. Hodnota 15 je běžná výchozí hodnota, která vyvažuje čitelnost a výšku štítku. + +## Krok 5: Změna poměru stran na 30 a uložení druhého PNG + +Upravte stejnou instanci generátoru tak, aby používala větší poměr stran, a poté uložte druhý obrázek. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Proč je to důležité:** Zvýšení poměru stran prodlouží čárový kód vertikálně, což může zlepšit spolehlivost skenování na zařízeních s nízkým rozlišením nebo když je štítek tištěn na úzkém médiu. + +## Očekávaný výstup + +Po spuštění programu vzniknou dva PNG soubory: + +| File | Aspect Ratio | Approximate dimensions (pixels) | +|------------------------------------|--------------|---------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (width × height) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (width × height) | + +Oba obrázky obsahují jasný, skenovatelný DataBar čárový kód, který kóduje GS1 identifikátor `(01)12345678901231`. + +## Časté otázky a okrajové případy + +### Jak změnit další vizuální vlastnosti? + +Můžete upravit barvu popředí, barvu pozadí nebo přidat lidsky čitelný text pomocí objektu `generator.Parameters.Barcode`. Například: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Co když potřebuji jiný formát obrázku? + +Nahraďte `BarCodeImageFormat.Png` hodnotou `Jpeg`, `Bmp` nebo `Gif` podle potřeby. PNG zůstává nejvhodnější volbou pro bezztrátové obrázky čárových kódů. + +### Ovlivňuje poměr stran rychlost skenování? + +Vyšší poměr stran zvyšuje výšku čárového kódu, což může zlepšit spolehlivost skenování na zařízeních, která mají problémy se čtením krátkých vrstvených symbolů. Nicméně extrémně vysoké čárové kódy se nemusí vejít na malé štítky, proto testujte s vaším cílovým hardwarem. + +### Můžu generovat více čárových kódů ve smyčce? + +Ano. Vytvořte novou instanci `BarcodeGenerator` pro každý řetězec dat nebo znovu použijte stejnou instanci a aktualizujte `CodeText` a `DataBar.AspectRatio`. Tento přístup snižuje režii alokace objektů. + +## Profesionální tipy + +- **Znovupoužití generátoru**: Změna pouze `CodeText` nebo `AspectRatio` eliminuje nutnost znovu vytvářet objekt, což urychluje dávkové zpracování. +- **Validace výstupu**: Použijte ruční skener nebo mobilní aplikaci k potvrzení, že vygenerované PNG se načítá správně, před nasazením do produkce. +- **Pojmenování souborů**: Vložte poměr stran do názvu souboru (jak je ukázáno), abyste během testování snadno sledovali různé varianty. + +## Závěr + +Nyní víte, jak **create barcode PNG** soubory v C# a přesně **jak změnit poměr stran** pro vrstvené omnidirekcionální DataBar symboly. Kompletní příklad ukazuje inicializaci, nastavení X‑dimenze, manipulaci s poměrem stran a ukládání obrázku — vše v jednom spustitelném programu. + +Odtud můžete zkoumat další typy čárových kódů, experimentovat s barvami nebo integrovat generátor do většího reportovacího či inventárního systému. Šť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 krok‑za‑krokem vysvětleními, která vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy ve vašich projektech. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/czech/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..369fd08db --- /dev/null +++ b/barcode/czech/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-08-03 +description: Rychle vytvořte PNG čárový kód s tímto návodem. Naučte se, jak generovat + obrázek čárového kódu pomocí Aspose.BarCode a vytvořit planetární čárový kód. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: cs +lastmod: 2026-08-03 +og_description: Okamžitě vytvořte PNG čárový kód. Tento tutoriál ukazuje, jak vygenerovat + obrázek čárového kódu a vytvořit planetární čárový kód pomocí Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Vytvořte PNG čárový kód v Pythonu – kompletní programovací průvodce +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Vytvoření PNG čárového kódu v Pythonu – průvodce krok za krokem +url: /cs/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření barcode PNG v Pythonu – krok za krokem průvodce + +Pokud potřebujete **vytvořit barcode PNG** soubory z vaší Python aplikace, tento tutoriál vám přesně ukáže, jak na to. Provedeme vás **generováním barcode obrázku** pomocí Aspose.BarCode a konkrétně **vytvořením planet barcode** s vlastními rozměry. + +Naučíte se, jak nainstalovat knihovnu, nakonfigurovat symbologii Planet, upravit parametry velikosti a uložit výsledek jako PNG vysoké kvality. Průvodce předpokládá základní znalosti Pythonu a aktuální verzi Python 3 (3.8 nebo novější). Předchozí zkušenosti se standardy čárových kódů nejsou vyžadovány. + +--- + +## Jak vytvořit barcode PNG pomocí Aspose.BarCode + +Tato sekce obsahuje hlavní kroky potřebné k **vytvoření barcode PNG**. Každý krok zahrnuje úryvek kódu, vysvětlení, proč je důležitý, a praktické tipy, které můžete okamžitě použít. + +### 1. Instalace balíčku Aspose.BarCode + +Aspose poskytuje čistě Python balíček, který obaluje jeho .NET jádro. Nainstalujte jej pomocí `pip`: + +```bash +pip install aspose-barcode +``` + +*Proč je tento krok důležitý:* Balíček poskytuje třídu `BarcodeGenerator`, která je používána v celém příkladu. Instalace globálně zajišťuje, že interpreter dokáže za běhu najít sestavení. + +### 2. Import požadovaných tříd + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Tip:* Importujte pouze symboly, které potřebujete; tím udržíte jmenný prostor čistý a urychlíte načítání modulů. + +### 3. Vytvoření generátoru čárového kódu pro symbologii Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Proč je to důležité:* `EncodeTypes.Planet` říká enginu, aby použil standard Planet barcode, zatímco druhý argument poskytuje data k zakódování. Změna symbologie (např. `EncodeTypes.Code128`) by vytvořila zcela odlišný vizuální vzor. + +### 4. Nastavení X rozměru (šířka modulu) v pixelech + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Vysvětlení:* X rozměr řídí šířku úzkého pruhu. Hodnota 4 pixely poskytuje středně hustý čárový kód, který zůstává čitelný na většině zařízení. + +### 5. Definování ruční výšky pruhu v pixelech + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Proč byste to mohli upravit:* Některé maloobchodní tiskárny vyžadují vyšší pruhy pro spolehlivé skenování. Výchozí výška je obvykle 50 px; zvýšení na 100 px zlepšuje čitelnost, aniž by dramaticky zvětšilo velikost souboru. + +### 6. Uložení vygenerovaného čárového kódu jako PNG obrázek + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Výsledek:* PNG soubor s názvem **PlanetBarHeight100.png** se objeví ve složce `output`. PNG je bezztrátový, což ho činí ideálním pro tisk i vkládání do webových stránek. + +### 7. Ověření výstupu (volitelné) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Tip:* Zobrazení obrázku potvrzuje, že rozměry odpovídají nastaveným parametrům. Pokud čárový kód vypadá deformovaně, zkontrolujte nastavení X rozměru nebo výšky pruhu. + +--- + +## Jak generovat obrázek čárového kódu ve formátu PNG (alternativní nastavení) + +Pokud potřebujete jiný formát obrázku nebo chcete později vložit čárový kód do PDF, můžete změnit výčtový typ `BarCodeImageFormat`: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Proč je to důležité:* PNG zachovává každý pixel, což je klíčové pro vysoce kontrastní čárové kódy. JPEG zavádí kompresní artefakty, které mohou narušovat skenování, zatímco BMP nabízí kompatibilitu se staršími nástroji. + +--- + +## Vytvoření planet barcode s vlastními barvami (pokročilé) + +Kromě velikosti můžete přizpůsobit barvy popředí a pozadí: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Praktický tip:* Vysoce kontrastní páry barev (tmavé na světlém) maximalizují spolehlivost skeneru. Vyhněte se používání podobných odstínů pro popředí i pozadí. + +--- + +## Časté úskalí a jak se jim vyhnout + +| Symptom | Příčina | Oprava | +|---------|----------|--------| +| Čárový kód se nedaří načíst | X rozměr je příliš malý (≤ 2 px) | Zvyšte `x_dimension.pixels` alespoň na 3 px | +| Obrázek je rozmazaný | PNG uložený s nízkým DPI | Použijte `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` pro nastavení 300 DPI (pokud je podporováno) | +| Výjimka `ImportError` | Aspose.BarCode není nainstalován | Spusťte `pip install aspose-barcode` ve stejném prostředí jako váš skript | +| Špatná symbologie | Použito `EncodeTypes.Code128` místo `EncodeTypes.Planet` | Nahraďte `EncodeTypes.Planet` při vytváření generátoru | + +--- + +## Shrnutí kompletního řešení + +Níže je kompletní spustitelný skript, který **vytváří barcode PNG** od začátku až do konce: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Spuštěním tohoto skriptu získáte ostrý **Planet barcode PNG**, který můžete vložit do HTML, připojit k e‑mailům nebo vytisknout na produktové štítky. + +--- + +## Další kroky a související témata + +* **Integrace s Flask nebo Django** – poskytovat vygenerované PNG přímo z webového koncového bodu. +* **Dávková generace** – projít seznam produktových ID a vytvořit složku s PNG soubory čárových kódů. +* **Kombinace s generováním PDF** – použijte `aspose-pdf` k vložení PNG do faktury nebo přepravní štítky. +* **Prozkoumejte další symbologie** – nahraďte `EncodeTypes.Planet` za `EncodeTypes.QR`, `EncodeTypes.DataMatrix` nebo `EncodeTypes.Code128` podle různých obchodních potřeb. + +Osvojením výše uvedených kroků nyní víte, **jak programově generovat obrázek čárového kódu**, a můžete rozšířit tento postup na jakýkoli standard čárových kódů podporovaný Aspose.BarCode. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/czech/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..04a212ddf --- /dev/null +++ b/barcode/czech/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-08-03 +description: Rychle vytvořte obrázek poštovního čárového kódu v C#. Naučte se, jak + generovat poštovní čárový kód, nastavit rozměry čárového kódu a vytvořit Planet + čárový kód. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: cs +lastmod: 2026-08-03 +og_description: Vytvořte obrázek poštovního čárového kódu v C# s tímto kompletním + tutoriálem; naučte se, jak nastavit rozměry čárového kódu, vygenerovat Planet čárový + kód a vytvořit čárové kódy RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Vytvořte obrázek poštovního čárového kódu v C# – kompletní programovací + průvodce +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Vytvořte obrázek poštovního čárového kódu v C# – průvodce krok po kroku +url: /cs/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření obrázku poštovního čárového kódu v C# – krok za krokem + +Pokud potřebujete **vytvořit obrázek poštovního čárového kódu** v C#, tento návod vám přesně ukáže jak. Pokryjeme **jak generovat poštovní čárový kód**, **jak nastavit rozměry čárového kódu** a jak **vytvořit planet čárový kód** pro běžné poštovní standardy. + +Na konci budete mít dva připravené PNG soubory – jeden s Planet čárovým kódem a jeden s RM4SCC čárovým kódem – každý vysoký 100 px. Kromě knihovny Aspose.BarCode pro .NET nejsou potřeba žádné další nástroje. + +## Požadavky + +* .NET 6 SDK nebo novější (kód také funguje s .NET Framework 4.7+) +* Visual Studio 2022 nebo jakékoli C# IDE +* NuGet balíček **Aspose.BarCode** (knihovna, která poskytuje `BarcodeGenerator`) + +## Krok 1: Instalace knihovny čárových kódů + +Otevřete terminál ve složce projektu a spusťte: + +```bash +dotnet add package Aspose.BarCode +``` + +Balíček přidá jmenný prostor `Aspose.BarCode`, který obsahuje `BarcodeGenerator` a výčtový typ `EncodeTypes` potřebný pro poštovní čárové kódy. + +## Krok 2: Definování výstupní složky + +Vytvoření spolehlivé výstupní cesty zabraňuje chybám za běhu, pokud složka neexistuje. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Proč je to důležité*: `Directory.CreateDirectory` je idempotentní – vytvoří složku jen pokud ještě neexistuje, čímž se vyhneme výjimkám při dalších spuštěních. + +## Krok 3: Nastavení běžných rozměrů čárového kódu + +Nastavení X‑dimenze (šířka jedné čáry) a celkové výšky čáry vám umožní řídit vizuální velikost generovaného obrázku. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Jak nastavit rozměry čárového kódu**: Vlastnost `Parameters.Barcode.XDimension.Pixels` určuje šířku úzké čáry, zatímco `Parameters.Barcode.BarHeight.Pixels` určuje celkovou výšku. Přizpůsobte tyto hodnoty podle specifikací vaší poštovní služby. + +## Krok 4: Vytvoření Planet čárového kódu + +Planet je široce používaný poštovní čárový kód ve Spojeném království. Následující kód vytvoří Planet čárový kód vysoký 100 px a uloží jej jako PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Proč to funguje**: `EncodeTypes.Planet` říká generátoru, aby použil symbologii Planet. Metoda `Save` zapíše PNG soubor na zadanou cestu a zachová rozměry, které jsme nastavili dříve. + +## Krok 5: Vytvoření RM4SCC čárového kódu + +RM4SCC je nizozemský standard poštovních čárových kódů. Níže uvedený kód odráží příklad s Planet, demonstrující **jak generovat poštovní čárový kód** jiného typu se stejnými rozměry. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Oba PNG soubory se nyní nacházejí ve složce `Barcodes`. Po jejich otevření uvidíte čisté, 100 px vysoké čárové kódy připravené k tisku nebo vložení do dokumentů. + +## Kompletní zdrojový kód + +Níže je kompletní spustitelný program, který **vytváří soubory s obrázkem poštovního čárového kódu** pro standardy Planet i RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Očekávaný výstup + +Spuštěním programu se vypíšou cesty k souborům a vytvoří se dva PNG soubory: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Každý obrázek má výšku 100 px, s úzkou čárou širokou 4 pixely, což odpovídá nastaveným rozměrům. + +## Praktické tipy a běžné úskalí + +* **Oprávnění ke složce** – Pokud program běží pod omezeným účtem, ujistěte se, že cílová složka je zapisovatelná. +* **Různé rozměry** – Pro vytvoření vyššího čárového kódu zvyšte `barHeightPixels`. Pro jemnější rozlišení snižte `xDimensionPixels`, ale ponechte hodnotu ≥ 2, aby nedocházelo k artefaktům při vykreslování. +* **Další poštovní symbologie** – Aspose.BarCode také podporuje `EncodeTypes.Postnet` a `EncodeTypes.AustralianPost`. Vyměňte hodnotu `EncodeTypes` a zachovejte stejnou logiku rozměrů. +* **Formát obrázku** – Použijte `BarCodeImageFormat.Jpeg` pro menší velikost souboru, pokud není vyžadována bezztrátová kvalita. + +## Závěr + +Nyní víte, jak **vytvořit soubory s obrázkem poštovního čárového kódu** v C# nastavením rozměrů, výběrem správné symbologie a uložením výsledku jako PNG. Návod pokryl **jak generovat poštovní čárový kód**, předvedl **vytvoření Planet čárového kódu** a vysvětlil **jak nastavit rozměry čárového kódu** pro konzistentní výstup. + +Dále můžete prozkoumat **přizpůsobení barev čárových kódů**, přidání **čitelného textu** nebo integraci obrázků do PDF faktur. Stejný vzor platí pro jakýkoli jiný typ čárového kódu podporovaný knihovnou Aspose.BarCode, což vám umožní rozšířit toto řešení na kompletní workflow poštovní automatizace. + +## Co byste se měli naučit dál? + +Následující návody 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í příklady 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 čárový kód – jednorozměrné typy čárových kódů](/barcode/english/net/one-dimensional-barcode-types/) +- [Jak generovat Aztec čárový kód s vlastním poměrem stran pomocí Aspose.BarCode pro .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Jak generovat čárový kód v Java – Australia Post Barcode s Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/czech/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..b8ca32246 --- /dev/null +++ b/barcode/czech/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-08-03 +description: Jak uložit čárový kód v C# s krok‑za‑krokem příkladem generátoru čárových + kódů. Naučte se generovat čárové kódy Planet, nastavit rozměry a exportovat PNG + obrázky. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: cs +lastmod: 2026-08-03 +og_description: Jak uložit čárový kód v C# pomocí příkladu generátoru čárových kódů. + Tento tutoriál ukazuje, jak generovat čárové kódy Planet, nastavit X‑rozměr a exportovat + soubory PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Jak uložit čárový kód v C# – průvodce krok po kroku +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Jak uložit čárový kód v C# – kompletní průvodce generátorem čárových kódů +url: /cs/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak uložit čárový kód v C# – kompletní průvodce generátorem čárových kódů + +Ukládání obrázků čárových kódů v C# je běžný požadavek, když potřebujete vložit poštovní čárové kódy do faktur, přepravních štítků nebo inventárních značek. Tento průvodce vás provede praktickým **c# barcode generator** pracovním postupem, od vytvoření Planet čárového kódu až po export jak vyplněných, tak prázdných PNG souborů. + +Naučíte se, jak nastavit šířku čáry, přepínat vyplněné čáry a spolehlivě pracovat s výstupními složkami. Na konci tutoriálu budete mít plně funkční **barcode generator example**, který můžete zkopírovat do libovolného .NET projektu. + +## Co budete potřebovat + +- .NET 6.0 SDK nebo novější (příklad funguje s .NET Core a .NET Framework) +- Visual Studio 2022 nebo jakékoli C#‑kompatibilní IDE +- Balíček **Aspose.BarCode** NuGet (nebo jiná knihovna, která podporuje `EncodeTypes.Planet`). Nainstalujte jej pomocí: + +```bash +dotnet add package Aspose.BarCode +``` + +Knihovna poskytuje třídu `BarcodeGenerator`, která je používána v celém tomto tutoriálu. + +## Nastavení vývojového prostředí + +Vytvořte nový konzolový projekt a přidejte požadovaný namespace: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +Namespace `System.IO` nám poskytuje `Directory.CreateDirectory`, který zajistí, že výstupní složka existuje, než se pokusíme zapisovat soubory. + +## Jak uložit obrázky čárových kódů pomocí generátoru čárových kódů v C# + +Jádrem řešení je malá sada kroků, které nakonfigurují **Planet barcode** a poté uloží obrázek na disk. Následující sekce rozdělují proces na zvládnutelné části. + +### Krok 1: Definujte výstupní složku + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Proč?** +Pevně zakódovaná cesta může způsobit `DirectoryNotFoundException` na počítačích, kde složka neexistuje. `CreateDirectory` je idempotentní – vytvoří adresář pouze v případě, že chybí, což činí kód bezpečným při opakovaném spuštění. + +### Krok 2: Vytvořte generátor Planet čárového kódu (vyplněné čáry) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Proč?** +`EncodeTypes.Planet` říká knihovně, aby vytvořila poštovní Planet čárový kód, který je široce používán poštovními službami. Řetězec `"123456"` je ukázkový payload; nahraďte jej libovolnými číselnými daty požadovanými vaším obchodním logikou. + +### Krok 3: Nastavte šířku čáry (X‑dimenzí) a ponechte výchozí vyplněné čáry + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Proč?** +X‑dimenze řídí fyzickou šířku každé čáry. Hodnota `4` pixely poskytuje čitelný čárový kód na standardních 300 dpi tiskárnách. Ponechání `FilledBars` jako `true` (výchozí) vytváří klasický vzhled plných čar. + +### Krok 4: Uložte obrázek čárového kódu s vyplněnými čarami + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Proč?** +Ukládání jako PNG zachovává bezztrátovou kvalitu obrazu, což je důležité pro přesnost skenování. Metoda `Save` automaticky vytvoří soubor obrázku; stačí zadat úplnou cestu a požadovaný formát. + +### Krok 5: Vytvořte druhý generátor pro verzi s prázdnými čarami + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Vytvoření nové instance zajišťuje, že změny provedené pro verzi s prázdnými čarami neovlivní již uložený obrázek s vyplněnými čarami. + +### Krok 6: Zakázat vyplněné čáry při zachování stejné X‑dimenze + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Proč?** +Nastavení `FilledBars = false` vykreslí čárový kód pouze s obrysem každé čáry, což některé poštovní standardy vyžadují pro vizuální ověření. + +### Krok 7: Uložte obrázek čárového kódu s prázdnými čarami + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Nyní máte dva PNG soubory – jeden s vyplněnými čarami a jeden s prázdnými čarami – připravené k vložení do PDF, HTML e‑mailů nebo tištěných štítků. + +## Kompletní spustitelný program + +Níže je kompletní kód, který můžete zkopírovat do `Program.cs`. Kompiluje se a spouští bez úprav (za předpokladu, že je nainstalován balíček Aspose.BarCode). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Očekávaný výstup + +Spuštění programu vypíše dva řádky podobné: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Otevřete složku `Barcodes` a uvidíte dva PNG soubory. Oba obrázky lze otevřít v libovolném prohlížeči obrázků nebo je vložit přímo do dokumentů. + +![příklad uložení čárového kódu](barcode-example.png){: .align-center alt="příklad uložení čárového kódu"} + +## Běžné varianty a okrajové případy + +| Scénář | Úprava | +|----------|------------| +| **Různý formát obrázku** | Změňte `BarCodeImageFormat.Png` na `Jpeg`, `Gif` nebo `Bmp` podle potřeby. | +| **Vlastní výstupní velikost** | Použijte `filled.Parameters.Image.Width` a `Height` k vynucení konkrétní pixelové rozměru. | +| **Dynamická data** | Nahraďte statický `"123456"` proměnnou, která obsahuje čísla objednávek, sledovací ID atd. | +| **Neexistující složka** | `Directory.CreateDirectory` již řeší chybějící adresáře; není potřeba další kód. | +| **Vysoké rozlišení tisku** | Zvyšte `XDimension.Pixels` na 6–8 pro 600 dpi tiskárny, ale ověřte kompatibilitu se skenerem. | + +**Tip:** Pokud potřebujete generovat mnoho čárových kódů ve smyčce, znovu použijte jedinou instanci `BarcodeGenerator` a před každým `Save` změňte pouze vlastnost `CodeText`. Tím se sníží režie alokace objektů. + +## Jak generovat čárový kód pro jiné standardy + +Stejný vzor funguje pro jiné `EncodeTypes`, jako jsou `Code128`, `QR` nebo `DataMatrix`. Jednoduše nahraďte `EncodeTypes.Planet` požadovaným typem a upravte případné typově specifické parametry (např. `QRCodeVersion`). + +## 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 uložit PNG pomocí DataMatrix C40 s Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Jak generovat DataMatrix čárové kódy (ECC 200) s Aspose.BarCode pro .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Jak generovat čárový kód – konfigurace Code 39 s Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/dutch/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..4740f19b4 --- /dev/null +++ b/barcode/dutch/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-08-03 +description: Barcodegenerator C#‑tutorial die laat zien hoe je een Planet‑barcode + maakt met Aspose.BarCode, de X‑dimensie instelt en opslaat als PNG‑afbeeldingen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: nl +lastmod: 2026-08-03 +og_description: Barcode‑generator C#‑tutorial leidt je door het maken van een Planet‑barcode, + het aanpassen van de X‑dimensie en het opslaan als PNG met Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Barcode generator C# – maak Planet‑barcode stap‑voor‑stap +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Barcodegenerator C# – maak Planet‑barcode en RM4SCC‑voorbeeld +url: /nl/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – maak Planet barcode en RM4SCC voorbeeld + +Als je een **barcode generator C#** nodig hebt die post‑specifieke symbolen kan produceren, laat deze gids je precies zien hoe je **Planet barcode** afbeeldingen maakt met Aspose.BarCode. Je ziet hoe je de X‑dimension configureert, een bijpassende RM4SCC barcode genereert en beide opslaat als PNG‑bestanden—alles in een paar beknopte stappen. + +De tutorial behandelt alles wat je nodig hebt om de code uit te voeren op .NET 6 of later, legt uit waarom elke instelling belangrijk is, en wijst op veelvoorkomende valkuilen zoals een onjuiste modulebreedte of ontbrekende maprechten. Aan het einde heb je twee kant‑klaar barcode‑afbeeldingen die voldoen aan de Planet- en RM4SCC‑normen. + +## Vereisten + +* .NET 6 SDK (of een .NET‑versie die door Aspose.BarCode wordt ondersteund) +* Visual Studio 2022 of een andere C#‑IDE die je verkiest +* Een NuGet‑referentie naar **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Schrijfrechten voor de map waarin je de PNG‑bestanden wilt opslaan + +Er zijn geen extra externe services vereist; de bibliotheek verwerkt alle codering lokaal. + +## Stap 1: Initialiseer het barcode generator C# object + +De eerste taak is het maken van een instantie van `BarcodeGenerator`. De constructor neemt de barcode‑symbologie (`EncodeTypes.Planet`) en de te coderen gegevens. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Waarom deze stap?* +`BarcodeGenerator` is het toegangspunt voor elke barcode die je genereert. Het selecteren van `EncodeTypes.Planet` vertelt de bibliotheek de ISO/IEC 24723‑specificatie te volgen die door veel postdiensten wordt gebruikt. + +## Stap 2: Stel de X‑dimension (modulebreedte) in voor de Planet barcode + +De X‑dimension bepaalt de breedte van een enkel barcode‑module (de kleinste balk of spatie). Een waarde van **4 pixels** werkt goed voor de meeste labelprinters. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Waarom dit belangrijk is* +Als de module te smal is, kan de barcode onleesbaar worden; te breed en de labelgrootte groeit onnodig. Het aanpassen van `Pixels` stelt je in staat de barcode nauwkeurig af te stemmen op de resolutie van jouw printer. + +## Stap 3: Sla de Planet barcode op als PNG‑afbeelding + +Aspose.BarCode berekent automatisch de barcode‑hoogte op basis van de geselecteerde symbologie, dus je hoeft alleen het bestandspad en het formaat op te geven. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tip* +Vervang `YOUR_DIRECTORY` door een absoluut of relatief pad dat bestaat op jouw machine. Als de map niet bestaat, gooit de `Save`‑methode een `DirectoryNotFoundException`. + +**Verwachte output** – een PNG‑bestand dat er vergelijkbaar uitziet als de illustratie hieronder (de daadwerkelijke afbeelding wordt hier niet weergegeven, maar je zult een klassieke Planet barcode zien met een numerieke payload van `123456`). + +## Stap 4: Initialiseer een tweede generator voor de RM4SCC barcode + +Veel postsystemen vereisen zowel Planet‑ als RM4SCC‑symbolen op hetzelfde poststuk. Maak een nieuwe `BarcodeGenerator`‑instantie aan voor de RM4SCC‑symbologie. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Waarom een aparte instantie?* +Elke symbologie heeft zijn eigen set parameters. Het hergebruiken van dezelfde generator kan onbedoeld instellingen (zoals X‑dimension) meenemen die niet optimaal zijn voor de tweede barcode. + +## Stap 5: Configureer de X‑dimension voor de RM4SCC barcode + +RM4SCC respecteert ook de X‑dimension‑instelling, dus passen we dezelfde pixelbreedte toe voor visuele consistentie. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +Als je een hogere barcode nodig hebt (bijv. voor grotere labels), kun je ook `Height.Pixels` instellen. Het leeg laten zorgt ervoor dat de bibliotheek de ideale hoogte automatisch berekent. + +## Stap 6: Sla de RM4SCC barcode op als PNG‑afbeelding + +Sla tenslotte de RM4SCC barcode op op schijf. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Je hebt nu twee PNG‑bestanden—`PostalPlanetBarHeightNone.png` en `PostalRM4SCCBarHeightNone.png`—die je kunt insluiten in verzendetiketten, afdrukken op enveloppen, of sturen naar een externe drukservice. + +## Optioneel: Hoogte aanpassen of andere afbeeldingsformaten gebruiken + +Als je workflow een specifieke barcode‑hoogte of een ander afbeeldingsformaat vereist (bijv. JPEG of BMP), kun je de parameters aanpassen voordat je `Save` aanroept: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Randgeval** – Wanneer je een aangepaste hoogte instelt, zorg er dan voor dat de waarde voldoet aan de minimale hoogte die de ISO‑norm vereist; anders kan de barcode de validatie niet doorstaan. + +## Veelvoorkomende valkuilen en hoe ze te vermijden + +| Valkuil | Waarom het gebeurt | Oplossing | +|---------|--------------------|----------| +| `DirectoryNotFoundException` | De doelmap bestaat niet of is verkeerd gespeld. | Maak de map eerst aan of gebruik `Path.Combine` met `Environment.CurrentDirectory`. | +| Barcode onleesbaar op printers met lage resolutie | X‑dimension te klein voor de DPI van de printer. | Verhoog `XDimension.Pixels` naar 5 – 6 voor 203 dpi printers, of test met een voorbeeldlabel. | +| Verkeerde symbologie gebruikt | `EncodeTypes.Code128` doorgeven in plaats van `EncodeTypes.Planet`. | Controleer dubbel of de `EncodeTypes`‑enumwaarde overeenkomt met de vereiste poststandaard. | +| Null‑referentie op `Parameters` | Een oudere versie van Aspose.BarCode gebruiken waar de API verschilt. | Upgrade naar het nieuwste NuGet‑pakket (v23.12 of later). | + +## Volledig uitvoerbaar voorbeeld + +Hieronder staat het volledige programma dat je kunt kopiëren, plakken en uitvoeren. Het bevat `using`‑statements, foutafhandeling en commentaren die elke regel uitleggen. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Het uitvoeren van het programma maakt een `Barcodes`‑map naast het uitvoerbare bestand en plaatst de twee PNG‑bestanden daarin. Open ze met een willekeurige afbeeldingsviewer om de output te verifiëren. + +## Conclusie + +Je hebt nu een **barcode generator C#** oplossing die **Planet barcode** afbeeldingen kan maken, de X‑dimension kan aanpassen voor optimale afdruk, en een bijpassende RM4SCC barcode kan produceren—alles met een handvol code‑regels. De aanpak werkt met .NET 6+, vereist alleen het Aspose.BarCode NuGet‑pakket, en kan worden uitgebreid naar andere symbologieën zoals Code128, QR, of DataMatrix door de `EncodeTypes`‑waarde te wijzigen. + +### Wat is het volgende? + +* Experimenteer met verschillende `XDimension.Pixels`‑waarden om overeen te komen met de DPI van jouw printer. +* Genereer barcodes in andere formaten (PDF, SVG) door de `BarCodeImageFormat`‑enum te wijzigen. +* Combineer de twee PNG‑bestanden tot één label met behulp van een grafische bibliotheek zoals **SkiaSharp**. +* Verken de volledige Aspose.BarCode‑API voor geavanceerde functies zoals checksum‑validatie of aangepaste lettertypen. + +Voel je vrij om de code aan te passen voor batchverwerking of te integreren in een ASP.NET Core‑webservice die barcode‑afbeeldingen op aanvraag retourneert. Veel plezier met coderen! + +## 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 Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Hoe PNG opslaan met DataMatrix C40 met Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Pas Code 16K Barcode Aspect Ratios aan met Aspose.BarCode voor .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/dutch/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..ab2f0bdce --- /dev/null +++ b/barcode/dutch/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-08-03 +description: Barcode-generator C#-tutorial laat zien hoe je een barcode‑afbeelding + genereert met Aspose.BarCode, kolommen en rijen instelt en PNG‑bestanden opslaat + voor DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: nl +lastmod: 2026-08-03 +og_description: Barcode generator C#-tutorial legt uit hoe je een barcode‑afbeelding + genereert met Aspose.BarCode, DataBar Expanded Stacked‑kolommen en -rijen configureert + en PNG‑bestanden opslaat. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Barcodegenerator C# – stapsgewijze handleiding voor het genereren van een + barcode‑afbeelding +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Barcodegenerator C# – barcode‑afbeelding genereren +url: /nl/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – barcode‑afbeelding genereren + +Als je een barcode generator C# nodig hebt die een barcode‑afbeelding kan genereren voor DataBar Expanded Stacked, leidt deze gids je door het volledige proces. Je leert hoe je kolom‑ en rij‑instellingen configureert, het resultaat opslaat als PNG, en de code aanpast voor andere symbologieën. + +Barcode‑afbeeldingen programmatically genereren verwijdert handmatige stappen en zorgt voor consistentie in facturen, verzendetiketten en voorraad‑systemen. Deze tutorial behandelt alles wat je nodig hebt, van project‑opzet tot volledige broncode, zodat je het voorbeeld direct kunt uitvoeren. + +## Prerequisites + +Voordat je begint, zorg dat je het volgende hebt: + +* .NET 6.0 of later geïnstalleerd +* Een IDE zoals Visual Studio 2022 (elke editor die C# ondersteunt) +* Een licentie voor **Aspose.BarCode for .NET** – de gratis evaluatie werkt voor testen +* Basiskennis van C#‑syntaxis + +Als een van deze items ontbreekt, installeer dan de .NET SDK vanaf dotnet.microsoft.com en verkrijg het Aspose.BarCode NuGet‑pakket met: + +```bash +dotnet add package Aspose.BarCode +``` + +## Step 1: Create a barcode generator C# project + +Maak een nieuwe console‑applicatie aan en voeg de benodigde `using`‑directieven toe: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +De `BarcodeGenerator`‑klasse is de kern van de barcode generator C# API. Hij ontvangt het symbologie‑type en de te coderen tekst. + +## Step 2: Generate a DataBar Expanded Stacked barcode and set columns + +Het eerste voorbeeld maakt een barcode met vier kolommen. Het aanpassen van de `Columns`‑eigenschap verandert de visuele dichtheid van de DataBar Expanded Stacked‑symbologie. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Why this matters:** Het aantal kolommen beïnvloedt de hoeveelheid data die in een compacte ruimte kan worden opgeslagen. Een waarde van 4 produceert een bredere barcode die door de meeste scanners leesbaar blijft. + +## Step 3: Generate a barcode with custom row count + +Het tweede voorbeeld laat zien hoe je de verticale lay‑out kunt regelen door de `Rows`‑eigenschap in te stellen. Een configuratie met drie rijen is handig wanneer je een hogere barcode nodig hebt voor beperkte horizontale ruimte. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Why this matters:** Het aanpassen van rijen laat je de barcode in een smalle kolom passen terwijl de leesbaarheid behouden blijft. De barcode generator C# rekent automatisch de module‑grootte opnieuw uit om aan de specificatie te voldoen. + +## Step 4: Full, runnable example + +Hieronder staat een zelfstandig programma dat de vorige stappen combineert. Kopieer de code naar `Program.cs`, vervang `YOUR_DIRECTORY` door een bestaand map‑pad, en voer de applicatie uit. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Expected output + +Wanneer je het programma uitvoert, verschijnen er twee PNG‑bestanden in de doelmap: + +* **DatabarCols4.png** – een DataBar Expanded Stacked barcode met vier kolommen +* **DatabarRows3.png** – dezelfde data gecodeerd in drie rijen + +Open de afbeeldingen met een willekeurige beeldviewer; ze tonen scherpe, scanbare barcodes die klaar zijn om afgedrukt of in PDF’s ingebed te worden. + +## How to generate barcode image with custom dimensions + +Als je een specifieke afbeeldingsgrootte nodig hebt, pas dan de `ImageHeight`‑ en `ImageWidth`‑eigenschappen aan vóór het aanroepen van `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Het wijzigen van de afmetingen beïnvloedt de gecodeerde data niet; het schaalt alleen de visuele weergave. Deze techniek is nuttig bij het integreren van barcodes in UI‑componenten met vaste lay‑out‑beperkingen. + +## Common pitfalls and pro tips + +* **Path separators:** Gebruik verbatim‑strings (`@"C:\Path\file.png"`) of `Path.Combine` om escape‑character problemen op Windows te vermijden. +* **License enforcement:** Zonder een geldige licentie bevatten de gegenereerde afbeeldingen een watermerk. Pas je licentie vroeg in de applicatie toe: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Encoding limits:** DataBar Expanded Stacked ondersteunt tot 74 numerieke tekens. Het overschrijden van deze limiet veroorzaakt een uitzondering. Valideer de invoerlengte voordat je de generator maakt. +* **Performance:** Het hergebruiken van één `BarcodeGenerator`‑instantie voor meerdere saves vermindert geheugenallocatie. Verander alleen de `Rows`‑ of `Columns`‑eigenschappen tussen saves als de te coderen tekst gelijk blijft. + +## Next steps + +Nu je barcode‑afbeeldingen kunt genereren met de barcode generator C#, kun je het volgende verkennen: + +* **Different symbologies** – probeer `EncodeTypes.QR`, `EncodeTypes.Code128`, of `EncodeTypes.Pdf417`. +* **Color customization** – stel `Parameters.Barcode.ForeColor` en `BackColor` in om bij je huisstijl te passen. +* **Embedding in PDFs** – combineer de gegenereerde PNG met Aspose.PDF om afdrukbare documenten te maken. + +Deze uitbreidingen stellen je in staat een volledige barcode‑oplossing te bouwen voor voorraad, logistiek of detailhandel. + +--- + + +## What Should You Learn Next? + + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat complete 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. + +- [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 Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/dutch/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..ccd423f98 --- /dev/null +++ b/barcode/dutch/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: Barcode‑generatorvoorbeeld in C# dat laat zien hoe je de breedte instelt, + hoe je de hoogte wijzigt en hoe je een barcode‑afbeelding genereert. Volg stap‑voor‑stap + instructies. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: nl +lastmod: 2026-08-03 +og_description: Het barcode‑generatorvoorbeeld toont het instellen van de X‑dimensiebreedte, + het wijzigen van de balkhoogte en het genereren van een barcode‑afbeelding in C#. + Volg de stappen om PNG‑bestanden te maken. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Barcode generator voorbeeld – C# breedte- en hoogtegids +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Barcodegenerator‑voorbeeld in C# – stel breedte en hoogte in +url: /nl/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator voorbeeld in C# – breedte en hoogte instellen + +Als je een **barcode generator voorbeeld** in C# nodig hebt, laat deze gids zien hoe je de X‑dimension breedte instelt, hoe je de balkhoogte wijzigt, en hoe je een barcode‑afbeeldingsbestand genereert. Je ziet een compleet, uitvoerbaar programma dat twee PNG‑bestanden met verschillende hoogtes produceert. + +Een typisch scenario is het maken van productetiketten waarbij de barcode‑grootte moet voldoen aan de specificaties van scanners. Aan het einde van deze tutorial kun je breedte‑ en hoogte‑parameters programmatisch aanpassen en het resultaat opslaan als een PNG‑afbeelding. + +## Vereisten + +* .NET 6 (of later) geïnstalleerd – de code richt zich op .NET 6 SDK. +* Een barcode‑bibliotheek die `EncodeTypes.DatabarOmniDirectional` ondersteunt. Het voorbeeld gebruikt **Aspose.BarCode for .NET**, maar elke bibliotheek die vergelijkbare eigenschappen exposeert werkt op dezelfde manier. +* Een IDE of editor (Visual Studio, VS Code, Rider) om het programma te compileren en uit te voeren. +* Schrijfrechten voor een map waarin de PNG‑bestanden worden opgeslagen. + +> **Pro tip:** Maak een map genaamd `Barcodes` in de root van je project en verwijs ernaar met `Path.Combine` om absolute paden hard‑gecodeerd te vermijden. + +## Barcode generator voorbeeld: initialiseren en configureren + +De eerste stap is het maken van een `BarcodeGenerator`‑instantie met de gewenste symbologie en gegevensreeks. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +De `EncodeTypes.DatabarOmniDirectional`‑enum selecteert de Databar Omni‑directional symbologie, en de GS1‑geformatteerde gegevensreeks `(01)12345678901231` vertegenwoordigt een typische GTIN‑14‑waarde. Het eenmalig initialiseren van de generator maakt het mogelijk om hetzelfde object voor meerdere afbeeldingen te hergebruiken. + +## Hoe breedte (X‑dimension) in te stellen + +De X‑dimension bepaalt de module‑breedte van de barcode. Instellen op 2 pixels maakt elke smalle balk 2 pixels breed, wat een veelvoorkomende eis is voor high‑density afdrukken. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Waarom dit belangrijk is: Als de breedte te klein is, kunnen scanners individuele balken niet onderscheiden; als deze te groot is, kan de barcode de etiketruimte overschrijden. Pas de pixelwaarde aan om overeen te komen met de DPI van de printer en de gewenste etiketgrootte. + +## Hoe hoogte te wijzigen + +De balkhoogte bepaalt hoe hoog de balken verschijnen. Het voorbeeld maakt twee afbeeldingen: één met een hoogte van 30 pixels en een andere met een hoogte van 60 pixels. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +De eigenschap `BarHeight.Pixels` beïnvloedt direct de visuele hoogte van de balken. Het wijzigen ervan tussen opslagen stelt je in staat om meerdere varianten te genereren vanuit dezelfde gegevenspayload zonder de generator opnieuw te maken. + +### Verwachte output + +Het uitvoeren van het programma genereert twee PNG‑bestanden in de map `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – balken zijn 30 pixels hoog. +* `DatabarBarHeight60Pixels.png` – balken zijn 60 pixels hoog. + +Beide afbeeldingen hebben dezelfde breedte (bepaald door de X‑dimension) en coderen dezelfde GTIN‑14‑gegevens. + +![Twee barcode PNG‑bestanden met verschillende hoogtes gegenereerd door C#‑code](barcode-example.png "Barcode generator voorbeeld dat hoogtevariaties toont") + +*De alt‑tekst van de afbeelding hierboven bevat het belangrijkste trefwoord voor toegankelijkheid en SEO.* + +## Hoe barcode‑afbeelding te genereren in C# + +De `Save`‑methode verwerkt de conversie van barcode‑gegevens naar een afbeeldingsbestand. Je kunt andere formaten (JPEG, BMP, SVG) kiezen door een andere `BarCodeImageFormat`‑enumwaarde door te geven. Het voorbeeld gebruikt PNG omdat het verliesloze kwaliteit behoudt en breed ondersteund wordt. + +Als je de barcode direct in een PDF of een webpagina wilt insluiten, haal je de afbeelding op als een `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Deze aanpak elimineert de noodzaak voor tijdelijke bestanden en is nuttig voor high‑throughput services. + +## Veelvoorkomende variaties en randgevallen + +| Situatie | Aanpassing | +|-----------|------------| +| **Verschillende symbologie** | Vervang `EncodeTypes.DatabarOmniDirectional` door een andere enumwaarde (bijv. `EncodeTypes.Code128`). | +| **Zeer kleine etiketten** | Verlaag `XDimension.Pixels` naar 1 pixel, maar controleer de leesbaarheid door scanners. | +| **High‑resolution afdrukken** | Verhoog zowel X‑dimension als balkhoogte proportioneel (bijv. 4 px breedte, 80 px hoogte). | +| **Dynamische gegevens** | Geef de gegevensreeks door tijdens runtime, mogelijk uit een database‑record. | +| **Batchgeneratie** | Loop over een collectie gegevensreeksen, hergebruik dezelfde `BarcodeGenerator`‑instantie terwijl `generator.Text` wordt bijgewerkt. | + +Wanneer je een uitzondering tegenkomt, zoals `ArgumentOutOfRangeException`, controleer dan dubbel of de pixelwaarden positieve gehele getallen zijn en of de uitvoermap bestaat. + +## Volledige broncode samenvatting + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Kopieer de code naar een nieuw console‑project, herstel het Aspose.BarCode NuGet‑pakket (`dotnet add package Aspose.BarCode`), en voer `dotnet run` uit. Je ziet console‑berichten die bevestigen dat de bestanden zijn opgeslagen. + +## Conclusie + +Dit **barcode generator voorbeeld** laat zien hoe je de breedte instelt, hoe je de hoogte wijzigt, en hoe je een barcode‑afbeelding genereert in C#. Door `XDimension.Pixels` en `BarHeight.Pixels` aan te passen, beheer je de visuele grootte van de barcode, en de `Save`‑methode schrijft het resultaat naar PNG‑bestanden. Experimenteer met verschillende symbologieën, uitvoerformaten en gegevensreeksen om aan de eisen van je applicatie te voldoen. + +**Volgende stappen** + +* Verken **how to generate barcode** in andere afbeeldingsformaten (SVG, JPEG) voor webgebruik. +* Leer **create barcode image c#** voor ASP.NET Core‑endpoints die de PNG direct naar een browser retourneren. +* Combineer deze code met een PDF‑generatiebibliotheek om barcodes in facturen of verzendetiketten in te sluiten. + +Voel je vrij om het voorbeeld aan te passen, je resultaten te delen, of vragen te stellen in de reacties. Veel plezier met coderen! + +## 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 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 barcode te genereren - Eén-dimensionale barcode‑typen](/barcode/english/net/one-dimensional-barcode-types/) +- [Hoe rand in te stellen voor ITF-14 barcode‑aanpassing](/barcode/english/net/itf-14-barcode-customization/) +- [Hoe DataMatrix barcodes (ECC 200) te genereren met Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/dutch/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..d69325e39 --- /dev/null +++ b/barcode/dutch/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-08-03 +description: Maak een barcode‑PNG in C# en leer hoe je de beeldverhouding van DataBar‑afbeeldingen + kunt aanpassen. Volg dit volledige voorbeeld met code en tips. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: nl +lastmod: 2026-08-03 +og_description: Maak een barcode‑PNG in C# en zie hoe je de beeldverhouding voor DataBar‑barcodes + kunt aanpassen. Deze gids biedt kant‑klaar werkende code en praktische tips. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Barcode PNG maken in C# – volledig voorbeeld met aspect‑ratio‑controle +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Barcode PNG maken in C# – stapsgewijze handleiding +url: /nl/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode PNG maken in C# – stapsgewijze handleiding + +Als je een **barcode PNG** moet **maken** in C#, laat deze tutorial je precies zien hoe. Je genereert een gestapelde omnidirectionele DataBar‑barcode, slaat deze op als PNG‑bestand en leert **hoe je de beeldverhouding kunt aanpassen** aan verschillende scanomgevingen. + +De gids behandelt alles wat je nodig hebt: vereiste pakketten, een compleet, uitvoerbaar programma en uitleg waarom elke instelling belangrijk is. Aan het einde heb je twee PNG‑bestanden – één met een beeldverhouding van 15 en een andere met 30 – klaar voor testen of productie. + +## Vereisten + +Zorg er voordat je begint voor dat je het volgende hebt: + +- .NET 6.0 SDK of later geïnstalleerd +- Visual Studio 2022 (of een andere C#‑IDE) +- Een NuGet‑referentie naar **Aspose.BarCode** (de bibliotheek die `BarcodeGenerator` levert) +- Schrijfrechten in de map waar de PNG‑bestanden worden opgeslagen + +Je kunt het Aspose.BarCode‑pakket toevoegen met het volgende commando: + +```bash +dotnet add package Aspose.BarCode +``` + +## Stap 1: Het project opzetten en namespaces importeren + +Maak een nieuwe console‑applicatie aan en importeer de namespaces die nodig zijn voor barcode‑generatie en bestands‑I/O. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Waarom dit belangrijk is:** Het importeren van `Aspose.BarCode.Generation` geeft je toegang tot `BarcodeGenerator`. Het plaatsen van de code binnen `Main` maakt het voorbeeld zelf‑voorzienend en eenvoudig uit te voeren. + +## Stap 2: Een barcode‑generator maken voor een gestapelde omnidirectionele DataBar + +Instantieer `BarcodeGenerator` met het type `EncodeTypes.DatabarStackedOmniDirectional` en een voorbeeld‑GS1‑128‑datastreek. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Waarom dit belangrijk is:** Het gekozen encode‑type produceert een high‑density DataBar die door de meeste moderne scanners kan worden gelezen. De datastreek volgt het GS1 Application Identifier (01)‑formaat, dat veel wordt gebruikt voor product‑identifiers. + +## Stap 3: De X‑dimensie (module‑breedte) in pixels definiëren + +Stel de module‑breedte in om de totale grootte van de barcode te regelen zonder de leesbaarheid te beïnvloeden. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Waarom dit belangrijk is:** Een X‑dimensie van 2 pixels levert een barcode op die noch te klein is voor scanners, noch te groot voor typische labelruimtes. + +## Stap 4: Het eerste PNG opslaan met een beeldverhouding van 15 + +Pas de DataBar‑beeldverhouding aan en sla vervolgens de afbeelding op als PNG‑bestand. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Waarom dit belangrijk is:** De beeldverhouding bepaalt de hoogte‑tot‑breedte‑relatie van de gestapelde DataBar. Een verhouding van 15 is een veelgebruikt standaard dat leesbaarheid en labelhoogte in balans brengt. + +## Stap 5: De beeldverhouding wijzigen naar 30 en een tweede PNG opslaan + +Wijzig dezelfde generator‑instantie om een grotere beeldverhouding te gebruiken en sla daarna de tweede afbeelding op. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Waarom dit belangrijk is:** Een hogere beeldverhouding strekt de barcode verticaal uit, wat de scanbetrouwbaarheid kan verbeteren op apparaten met lage resolutie of wanneer het label op smal materiaal wordt afgedrukt. + +## Verwachte output + +Het uitvoeren van het programma maakt twee PNG‑bestanden aan: + +| Bestand | Beeldverhouding | Geschatte afmetingen (pixels) | +|--------------------------------------|-----------------|------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (breedte × hoogte) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (breedte × hoogte) | + +Beide afbeeldingen bevatten een duidelijke, scanbare DataBar‑barcode die de GS1‑identifier `(01)12345678901231` codeert. + +## Veelgestelde vragen en randgevallen + +### Hoe andere visuele eigenschappen wijzigen? + +Je kunt de voorgrondkleur, achtergrondkleur of menselijk leesbare tekst aanpassen via het object `generator.Parameters.Barcode`. Bijvoorbeeld: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Wat als ik een ander afbeeldingsformaat nodig heb? + +Vervang `BarCodeImageFormat.Png` door `Jpeg`, `Bmp` of `Gif` naar behoefte. PNG blijft de beste keuze voor verliesvrije barcode‑afbeeldingen. + +### Heeft de beeldverhouding invloed op de scansnelheid? + +Hogere beeldverhoudingen vergroten de hoogte van de barcode, wat de scanbetrouwbaarheid kan verbeteren op apparaten die moeite hebben met korte gestapelde symbolen. Zeer hoge barcodes passen echter mogelijk niet op kleine labels, dus test met je doelhardware. + +### Kan ik meerdere barcodes in een lus genereren? + +Ja. Maak een nieuwe `BarcodeGenerator`‑instantie voor elke datastreek of hergebruik dezelfde instantie terwijl je `CodeText` en `DataBar.AspectRatio` bijwerkt. Deze aanpak vermindert de overhead van objectallocatie. + +## Pro‑tips + +- **Herbruik de generator**: Alleen `CodeText` of `AspectRatio` wijzigen voorkomt het opnieuw instantieren van het object, wat batchverwerking versnelt. +- **Valideer de output**: Gebruik een handscanner of een mobiele app om te bevestigen dat de gegenereerde PNG correct wordt gelezen voordat je deze in productie neemt. +- **Bestandsnaamgeving**: Neem de beeldverhouding op in de bestandsnaam (zoals getoond) om variaties tijdens het testen bij te houden. + +## Conclusie + +Je weet nu hoe je **barcode PNG**‑bestanden kunt **maken** in C# en precies **de beeldverhouding kunt aanpassen** voor gestapelde omnidirectionele DataBar‑symbolen. Het volledige voorbeeld toont initialisatie, X‑dimensie‑instelling, beeldverhouding‑manipulatie en het opslaan van de afbeelding – alles in één enkel, uitvoerbaar programma. + +Vanaf hier kun je extra barcode‑typen verkennen, experimenteren met kleuren, of de generator integreren in een groter rapportage‑ of voorraadbeheersysteem. 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 stapsgewijze uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/dutch/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..cc819d8e6 --- /dev/null +++ b/barcode/dutch/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-08-03 +description: Maak snel een barcode‑PNG met deze gids. Leer hoe je een barcode‑afbeelding + genereert met Aspose.BarCode en een planet barcode maakt. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: nl +lastmod: 2026-08-03 +og_description: Maak direct een barcode‑PNG. Deze tutorial laat zien hoe je een barcode‑afbeelding + genereert en een planet‑barcode maakt met Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Barcode PNG maken in Python – volledige programmeergids +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Barcode PNG maken in Python – stapsgewijze handleiding +url: /nl/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak barcode PNG in Python – stapsgewijze handleiding + +Als je **barcode PNG**-bestanden wilt maken vanuit je Python‑applicatie, laat deze tutorial je precies zien hoe. We lopen stap voor stap door **hoe je een barcode‑afbeelding genereert** met Aspose.BarCode en specifiek **een planet‑barcode genereert** met aangepaste afmetingen. + +Je leert hoe je de bibliotheek installeert, de Planet‑symbologie configureert, de grootte‑parameters aanpast en het resultaat opslaat als een PNG van hoge kwaliteit. De gids gaat uit van basiskennis van Python en een recente versie van Python 3 (3.8 of nieuwer). Er is geen voorafgaande ervaring met barcode‑standaarden vereist. + +--- + +## Hoe maak je barcode PNG met Aspose.BarCode + +Deze sectie bevat de kernstappen die nodig zijn om **barcode PNG** te **maken**. Elke stap bevat een code‑fragment, een uitleg waarom het belangrijk is, en praktische tips die je direct kunt toepassen. + +### 1. Installeer het Aspose.BarCode‑pakket + +Aspose biedt een pure‑Python‑pakket dat zijn .NET‑core‑engine omsluit. Installeer het met `pip`: + +```bash +pip install aspose-barcode +``` + +*Waarom deze stap belangrijk is:* Het pakket levert de `BarcodeGenerator`‑klasse die door het hele voorbeeld wordt gebruikt. Het globaal installeren zorgt ervoor dat de interpreter de assembly tijdens runtime kan vinden. + +### 2. Importeer vereiste klassen + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Tip:* Importeer alleen de symbolen die je nodig hebt; dit houdt de namespace schoon en versnelt het laden van modules. + +### 3. Maak een barcode‑generator voor de Planet‑symbologie + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Waarom dit belangrijk is:* `EncodeTypes.Planet` vertelt de engine om de Planet‑barcode‑standaard te gebruiken, terwijl het tweede argument de te coderen data levert. Het wijzigen van de symbologie (bijv. `EncodeTypes.Code128`) zou een volledig ander visueel patroon opleveren. + +### 4. Stel de X‑dimensie (module‑breedte) in pixels in + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Uitleg:* De X‑dimensie bepaalt de breedte van de smalle balk. Een waarde van 4 pixels levert een matig dichte barcode op die op de meeste apparaten scanbaar blijft. + +### 5. Definieer een handmatige balkhoogte in pixels + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Waarom je dit zou kunnen aanpassen:* Sommige retail‑printers vereisen hogere balken voor betrouwbare scanning. De standaardhoogte is meestal 50 px; verhogen naar 100 px verbetert de leesbaarheid zonder de bestandsgrootte drastisch te vergroten. + +### 6. Sla de gegenereerde barcode op als een PNG‑afbeelding + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Resultaat:* Een PNG‑bestand met de naam **PlanetBarHeight100.png** verschijnt in de `output`‑map. PNG is verliesvrij, waardoor het ideaal is voor afdrukken en voor insluiten in webpagina's. + +### 7. Verifieer de output (optioneel) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Tip:* Het bekijken van de afbeelding bevestigt dat de afmetingen overeenkomen met de ingestelde parameters. Als de barcode vervormd lijkt, controleer dan opnieuw de X‑dimensie of de balkhoogte‑instellingen. + +--- + +## Hoe genereer je een barcode‑afbeelding in PNG‑formaat (alternatieve instellingen) + +Als je een ander afbeeldingsformaat nodig hebt of de barcode later in een PDF wilt insluiten, kun je de `BarCodeImageFormat`‑enum wijzigen: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Waarom dit belangrijk is:* PNG behoudt elk pixel, wat cruciaal is voor hoog‑contrast barcodes. JPEG introduceert compressie‑artefacten die scanning kunnen verstoren, terwijl BMP compatibiliteit biedt met oudere tools. + +--- + +## Genereer planet‑barcode met aangepaste kleuren (geavanceerd) + +Naast grootte kun je de voor‑ en achtergrondkleuren aanpassen: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Praktische tip:* Hoog‑contrast kleurparen (donker op licht) maximaliseren de betrouwbaarheid van de scanner. Vermijd het gebruik van vergelijkbare tinten voor voor‑ en achtergrond. + +--- + +## Veelvoorkomende valkuilen en hoe ze te vermijden + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Barcode wordt niet gescand | X‑dimensie te klein (≤ 2 px) | Verhoog `x_dimension.pixels` tot minimaal 3 px | +| Afbeelding is onscherp | PNG opgeslagen met lage DPI | Gebruik `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` om 300 DPI op te geven (indien ondersteund) | +| Exception `ImportError` | Aspose.BarCode niet geïnstalleerd | Voer `pip install aspose-barcode` uit in dezelfde omgeving als je script | +| Verkeerde symbologie | Gebruikt `EncodeTypes.Code128` in plaats van `EncodeTypes.Planet` | Vervang door `EncodeTypes.Planet` bij het aanmaken van de generator | + +--- + +## Samenvatting van de volledige oplossing + +Hieronder staat het volledige, uitvoerbare script dat **barcode PNG** van begin tot eind **maakt**: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Het uitvoeren van dit script levert een scherpe **Planet barcode PNG** op die je kunt insluiten in HTML, aan e‑mails kunt toevoegen, of kunt afdrukken op productetiketten. + +--- + +## Volgende stappen en gerelateerde onderwerpen + +* **Integreren met Flask of Django** – serveer de gegenereerde PNG direct vanaf een web‑endpoint. +* **Batch‑generatie** – loop over een lijst met product‑ID's om een map met barcode PNG‑bestanden te maken. +* **Combineren met PDF‑generatie** – gebruik `aspose-pdf` om de PNG in een factuur of verzendetiket te plaatsen. +* **Verken andere symbologieën** – vervang `EncodeTypes.Planet` door `EncodeTypes.QR`, `EncodeTypes.DataMatrix` of `EncodeTypes.Code128` om aan verschillende zakelijke behoeften te voldoen. + +Door de bovenstaande stappen onder de knie te krijgen, weet je nu **hoe je programmatically een barcode‑afbeelding genereert** en kun je het patroon uitbreiden naar elke barcode‑standaard die door Aspose.BarCode wordt ondersteund. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/dutch/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..58920405e --- /dev/null +++ b/barcode/dutch/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-08-03 +description: Maak snel een postbarcode-afbeelding in C#. Leer hoe je een postbarcode + genereert, barcode-afmetingen instelt en een Planet-barcode genereert. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: nl +lastmod: 2026-08-03 +og_description: Maak een postbarcode-afbeelding in C# met deze volledige tutorial; + leer hoe je barcode-afmetingen instelt, een Planet-barcode genereert en RM4SCC-barcodes + maakt. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Maak een postbarcode‑afbeelding in C# – volledige programmeergids +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Maak een postbarcode‑afbeelding in C# – stapsgewijze handleiding +url: /nl/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak een postbarcode‑afbeelding in C# – stap‑voor‑stap gids + +Als je een **postbarcode‑afbeelding wilt maken** in C#, laat deze gids je precies zien hoe. We behandelen **hoe je een postbarcode genereert**, **hoe je barcode‑afmetingen instelt**, en hoe je een **Planet‑barcode genereert** voor veelvoorkomende poststandaarden. + +Je eindigt met twee kant‑klaar PNG‑bestanden — één Planet‑barcode en één RM4SCC‑barcode — elk 100 px hoog. Er zijn geen extra tools nodig, behalve de Aspose.BarCode for .NET‑bibliotheek. + +## Vereisten + +* .NET 6 SDK of later (de code werkt ook met .NET Framework 4.7+) +* Visual Studio 2022 of een C#‑IDE +* NuGet‑pakket **Aspose.BarCode** (de bibliotheek die `BarcodeGenerator` levert) + +## Stap 1: Installeer de barcode‑bibliotheek + +Open een terminal in je projectmap en voer uit: + +```bash +dotnet add package Aspose.BarCode +``` + +Het pakket voegt de `Aspose.BarCode`‑namespace toe, die `BarcodeGenerator` en de `EncodeTypes`‑enumeratie bevat die nodig zijn voor postbarcodes. + +## Stap 2: Definieer de uitvoermap + +Het maken van een betrouwbaar uitvoerpad voorkomt runtime‑fouten wanneer de map niet bestaat. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Waarom dit belangrijk is*: `Directory.CreateDirectory` is idempotent — het maakt de map alleen aan als deze nog niet bestaat, waardoor uitzonderingen bij volgende uitvoeringen worden vermeden. + +## Stap 3: Configureer algemene barcode‑afmetingen + +Het instellen van de X‑dimensie (breedte van één enkele balk) en de totale balkhoogte stelt je in staat de visuele grootte van de gegenereerde afbeelding te beheersen. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Hoe je barcode‑afmetingen instelt**: De eigenschap `Parameters.Barcode.XDimension.Pixels` bepaalt de smalle balkbreedte, terwijl `Parameters.Barcode.BarHeight.Pixels` de volledige hoogte definieert. Pas deze waarden aan om te voldoen aan de specificaties van jouw postdienst. + +## Stap 4: Genereer een Planet‑barcode + +Planet is een veelgebruikte postbarcode in het Verenigd Koninkrijk. De onderstaande code maakt een 100 px‑hoge Planet‑barcode en slaat deze op als PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Waarom dit werkt**: `EncodeTypes.Planet` vertelt de generator om de Planet‑symbologie te gebruiken. De `Save`‑methode schrijft een PNG‑bestand naar het opgegeven pad, waarbij de eerder ingestelde afmetingen behouden blijven. + +## Stap 5: Genereer een RM4SCC‑barcode + +RM4SCC is de Nederlandse postbarcode‑standaard. De onderstaande code spiegelt het Planet‑voorbeeld en toont **hoe je een postbarcode genereert** van een ander type met identieke afmetingen. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Beide PNG‑bestanden staan nu in de `Barcodes`‑map. Als je ze opent zie je nette, 100 px‑hoge barcodes die klaar zijn om af te drukken of in documenten in te sluiten. + +## Volledige broncode + +Hieronder staat het volledige, uitvoerbare programma dat **postbarcode‑afbeeldingen maakt** voor zowel Planet‑ als RM4SCC‑standaarden. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Verwachte output + +Het uitvoeren van het programma geeft de bestandspaden weer en maakt twee PNG‑bestanden aan: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Elke afbeelding is 100 px hoog, met een smalle balkbreedte van 4 pixel, overeenkomstig de ingestelde afmetingen. + +## Praktische tips en veelvoorkomende valkuilen + +* **Maprechten** – Als het programma onder een beperkt account draait, zorg ervoor dat de doelmap schrijfbaar is. +* **Verschillende afmetingen** – Om een hogere barcode te maken, verhoog `barHeightPixels`. Voor een fijnere resolutie, verlaag `xDimensionPixels`, maar houd deze ≥ 2 om weergave‑artefacten te voorkomen. +* **Andere post‑symbologieën** – Aspose.BarCode ondersteunt ook `EncodeTypes.Postnet` en `EncodeTypes.AustralianPost`. Verwissel de `EncodeTypes`‑waarde en behoud dezelfde dimension‑logica. +* **Afbeeldingsformaat** – Gebruik `BarCodeImageFormat.Jpeg` voor een kleinere bestandsgrootte wanneer verliesvrije kwaliteit niet vereist is. + +## Conclusie + +Je weet nu hoe je **postbarcode‑afbeeldingen** maakt in C# door afmetingen te configureren, de juiste symbologie te selecteren en het resultaat op te slaan als PNG. De tutorial behandelde **hoe je een postbarcode genereert**, toonde **het genereren van een Planet‑barcode** en legde **uit hoe je barcode‑afmetingen instelt** voor consistente output. + +Vervolgens kun je **barcode‑kleuren aanpassen**, **menselijk leesbare tekst** toevoegen, of de afbeeldingen integreren in PDF‑facturen. Hetzelfde patroon geldt voor elk ander barcode‑type dat door Aspose.BarCode wordt ondersteund, zodat je deze oplossing kunt uitbreiden naar een volledige post‑automatiseringsworkflow. + +## 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. + +- [Hoe een barcode te genereren – één-dimensionale barcode‑typen](/barcode/english/net/one-dimensional-barcode-types/) +- [Hoe een Aztec‑barcode te genereren met aangepaste beeldverhouding met Aspose.BarCode voor .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Hoe een barcode te genereren in Java – Australia Post‑barcode met Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/dutch/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..10c4d2fc4 --- /dev/null +++ b/barcode/dutch/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-08-03 +description: Hoe je een barcode opslaat in C# met een stapsgewijs barcodegenerator‑voorbeeld. + Leer Planet‑barcodes te genereren, afmetingen in te stellen en PNG‑afbeeldingen + te exporteren. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: nl +lastmod: 2026-08-03 +og_description: Hoe een barcode op te slaan in C# met een barcode‑generator voorbeeld. + Deze tutorial laat zien hoe je Planet‑barcodes genereert, de X‑dimensie configureert + en PNG‑bestanden exporteert. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Hoe een barcode op te slaan in C# – stapsgewijze handleiding +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Hoe barcode op te slaan in C# – complete barcodegeneratorgids +url: /nl/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe barcode op te slaan in C# – volledige barcode generator gids + +Barcode‑afbeeldingen opslaan in C# is een veelvoorkomende vereiste wanneer je post‑barcodes moet insluiten in facturen, verzendetiketten of voorraadlabels. Deze gids leidt je door een praktische **c# barcode generator** workflow, van het maken van een Planet‑barcode tot het exporteren van zowel filled‑bars als empty‑bars PNG‑bestanden. + +Je leert hoe je de balkbreedte instelt, filled bars schakelt, en output‑mappen betrouwbaar afhandelt. Aan het einde van de tutorial heb je een volledig functioneel **barcode generator example** dat je in elk .NET‑project kunt kopiëren. + +## Wat je nodig hebt + +- .NET 6.0 SDK of later (het voorbeeld werkt met .NET Core en .NET Framework) +- Visual Studio 2022 of een C#‑compatibele IDE +- Het **Aspose.BarCode** NuGet‑pakket (of een andere bibliotheek die `EncodeTypes.Planet` ondersteunt). Installeer het met: + +```bash +dotnet add package Aspose.BarCode +``` + +De bibliotheek levert de `BarcodeGenerator`‑klasse die door de hele tutorial wordt gebruikt. + +## De ontwikkelomgeving instellen + +Maak een nieuw console‑project aan en voeg de vereiste namespace toe: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +De `System.IO`‑namespace biedt ons `Directory.CreateDirectory`, die ervoor zorgt dat de output‑map bestaat voordat we proberen bestanden te schrijven. + +## Hoe barcode‑afbeeldingen op te slaan met de C# barcode generator + +De kern van de oplossing bestaat uit een kleine reeks stappen die een **Planet barcode** configureren en vervolgens de afbeelding naar schijf opslaan. De volgende secties verdelen het proces in beheersbare stukken. + +### Stap 1: Definieer de output‑map + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Waarom?** +Hard‑coderen van een pad kan een `DirectoryNotFoundException` veroorzaken op machines waar de map niet bestaat. `CreateDirectory` is idempotent — hij maakt de map alleen aan als deze ontbreekt, waardoor de code veilig is voor herhaalde uitvoeringen. + +### Stap 2: Maak een Planet barcode generator (filled bars) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Waarom?** +`EncodeTypes.Planet` vertelt de bibliotheek om een post‑Planet barcode te produceren, die veel wordt gebruikt door postdiensten. De string `"123456"` is de voorbeeldpayload; vervang deze door elke numerieke data die vereist is door je bedrijfslogica. + +### Stap 3: Configureer de balkbreedte (X‑dimensie) en behoud de standaard filled bars + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Waarom?** +De X‑dimensie bepaalt de fysieke breedte van elke balk. Een waarde van `4` pixels levert een leesbare barcode op standaard 300 dpi printers. Het laten staan van `FilledBars` op `true` (de standaard) geeft het klassieke solid‑bar uiterlijk. + +### Stap 4: Sla de filled‑bars barcode‑afbeelding op + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Waarom?** +Opslaan als PNG behoudt verliesvrije beeldkwaliteit, wat belangrijk is voor scan‑nauwkeurigheid. De `Save`‑methode maakt automatisch het afbeeldingsbestand aan; je hoeft alleen het volledige pad en het gewenste formaat op te geven. + +### Stap 5: Maak een tweede generator voor de empty‑bars versie + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Het maken van een nieuwe instantie zorgt ervoor dat wijzigingen voor de empty‑bars versie de reeds opgeslagen filled‑bars afbeelding niet beïnvloeden. + +### Stap 6: Schakel filled bars uit terwijl je dezelfde X‑dimensie behoudt + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Waarom?** +Het instellen van `FilledBars = false` rendert de barcode alleen met de omtrek van elke balk, wat sommige post‑standaarden vereisen voor visuele verificatie. + +### Stap 7: Sla de empty‑bars barcode‑afbeelding op + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Nu heb je twee PNG‑bestanden — één met filled bars en één met empty bars — klaar voor opname in PDF’s, HTML‑e‑mails of afgedrukte labels. + +## Volledig uitvoerbaar programma + +Hieronder staat de volledige code die je kunt kopiëren naar `Program.cs`. Het compileert en draait zonder aanpassingen (ervan uitgaande dat het Aspose.BarCode‑pakket geïnstalleerd is). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Verwachte output + +Het uitvoeren van het programma drukt twee regels af die lijken op: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Open de `Barcodes`‑map en je ziet de twee PNG‑bestanden. Beide afbeeldingen kunnen in elke beeldviewer worden geopend of direct in documenten worden ingebed. + +![voorbeeld van barcode opslaan](barcode-example.png){: .align-center alt="voorbeeld van barcode opslaan"} + +## Veelvoorkomende variaties en randgevallen + +| Scenario | Aanpassing | +|----------|------------| +| **Anders afbeeldingformaat** | Verander `BarCodeImageFormat.Png` naar `Jpeg`, `Gif` of `Bmp` indien nodig. | +| **Aangepaste outputgrootte** | Gebruik `filled.Parameters.Image.Width` en `Height` om een specifieke pixelafmeting af te dwingen. | +| **Dynamische data** | Vervang de statische `"123456"` door een variabele die ordernummers, tracking‑ID’s, enz. bevat. | +| **Niet‑bestaande map** | `Directory.CreateDirectory` handelt ontbrekende mappen al af; geen extra code nodig. | +| **Hoge‑resolutie afdrukken** | Verhoog `XDimension.Pixels` naar 6–8 voor 600 dpi printers, maar controleer scanner‑compatibiliteit. | + +**Pro tip:** Als je veel barcodes in een lus moet genereren, hergebruik dan een enkele `BarcodeGenerator`‑instantie en wijzig alleen de `CodeText`‑eigenschap vóór elke `Save`. Dit vermindert de overhead van objectallocatie. + +## Hoe barcode te genereren voor andere standaarden + +Hetzelfde patroon werkt voor andere `EncodeTypes` zoals `Code128`, `QR` of `DataMatrix`. Vervang simpelweg `EncodeTypes.Planet` door het gewenste type en pas eventuele type‑specifieke parameters aan (bijv. `QRCodeVersion` + +## 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 PNG op te slaan met DataMatrix C40 met Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Hoe DataMatrix Barcodes (ECC 200) te genereren met Aspose.BarCode voor .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Hoe Barcode te genereren – Code 39 Configuratie met Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/english/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..0cd728c4c --- /dev/null +++ b/barcode/english/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-03 +description: Barcode generator C# tutorial showing how to create Planet barcode with + Aspose.BarCode, set X‑dimension, and save as PNG images. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: en +lastmod: 2026-08-03 +og_description: Barcode generator C# tutorial walks you through creating a Planet + barcode, adjusting X‑dimension, and saving as PNG using Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Barcode generator C# – create Planet barcode step‑by‑step +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Barcode generator C# – create Planet barcode and RM4SCC example +url: /python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – create Planet barcode and RM4SCC example + +If you need a **barcode generator C#** that can produce postal‑specific symbols, this guide shows you exactly how to **create Planet barcode** images with Aspose.BarCode. You’ll see how to configure the X‑dimension, generate a matching RM4SCC barcode, and save both as PNG files—all in a few concise steps. + +The tutorial covers everything you need to run the code on .NET 6 or later, explains why each setting matters, and points out common pitfalls such as incorrect module width or missing directory permissions. By the end you’ll have two ready‑to‑print barcode images that comply with the Planet and RM4SCC standards. + +## Prerequisites + +Before you start, make sure you have: + +* .NET 6 SDK (or any .NET version supported by Aspose.BarCode) +* Visual Studio 2022 or any C# IDE you prefer +* A NuGet reference to **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Write permission to the folder where you plan to store the PNG files + +No additional external services are required; the library handles all encoding locally. + +## Step 1: Initialise the barcode generator C# object + +The first task is to create an instance of `BarcodeGenerator`. The constructor takes the barcode symbology (`EncodeTypes.Planet`) and the data to encode. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Why this step?* +`BarcodeGenerator` is the entry point for every barcode you generate. Selecting `EncodeTypes.Planet` tells the library to follow the ISO/IEC 24723 specification used by many postal services. + +## Step 2: Set the X‑dimension (module width) for the Planet barcode + +The X‑dimension defines the width of a single barcode module (the smallest bar or space). A value of **4 pixels** works well for most label printers. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Why this matters* +If the module is too narrow, the barcode may become unreadable; too wide and the label size grows unnecessarily. Adjusting `Pixels` lets you fine‑tune the barcode for your specific printer resolution. + +## Step 3: Save the Planet barcode as a PNG image + +Aspose.BarCode automatically calculates the barcode height based on the selected symbology, so you only need to specify the file path and format. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tip* +Replace `YOUR_DIRECTORY` with an absolute or relative path that exists on your machine. If the directory does not exist, the `Save` method throws a `DirectoryNotFoundException`. + +**Expected output** – a PNG file that looks similar to the illustration below (the actual image is not displayed here, but you’ll see a classic Planet barcode with a numeric payload of `123456`). + +## Step 4: Initialise a second generator for the RM4SCC barcode + +Many postal systems require both Planet and RM4SCC symbols on the same mailpiece. Create a new `BarcodeGenerator` instance for the RM4SCC symbology. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Why a separate instance?* +Each symbology has its own set of parameters. Re‑using the same generator could unintentionally carry over settings (like X‑dimension) that are not optimal for the second barcode. + +## Step 5: Configure the X‑dimension for the RM4SCC barcode + +RM4SCC also respects the X‑dimension setting, so we apply the same pixel width for visual consistency. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +If you need a taller barcode (e.g., for larger labels), you can also set `Height.Pixels`. Leaving it unset lets the library compute the ideal height automatically. + +## Step 6: Save the RM4SCC barcode as a PNG image + +Finally, persist the RM4SCC barcode to disk. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +You now have two PNG files—`PostalPlanetBarHeightNone.png` and `PostalRM4SCCBarHeightNone.png`—that you can embed in mailing labels, print on envelopes, or send to a third‑party printing service. + +## Optional: Adjusting height or using other image formats + +If your workflow demands a specific barcode height or a different image format (e.g., JPEG or BMP), you can modify the parameters before calling `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Edge case** – When you set a custom height, make sure the value respects the minimum height required by the ISO standard; otherwise the barcode may fail validation. + +## Common pitfalls and how to avoid them + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| `DirectoryNotFoundException` | The target folder does not exist or is misspelled. | Create the folder first or use `Path.Combine` with `Environment.CurrentDirectory`. | +| Barcode unreadable on low‑resolution printers | X‑dimension too small for the printer’s DPI. | Increase `XDimension.Pixels` to 5 – 6 for 203 dpi printers, or test with a sample label. | +| Wrong symbology used | Passing `EncodeTypes.Code128` instead of `EncodeTypes.Planet`. | Double‑check the `EncodeTypes` enum value matches the required postal standard. | +| Null reference on `Parameters` | Using an older version of Aspose.BarCode where the API differs. | Upgrade to the latest NuGet package (v23.12 or later). | + +## Full runnable example + +Below is the complete program you can copy, paste, and run. It includes `using` statements, error handling, and comments that explain each line. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Running the program creates an `Barcodes` folder next to the executable and places the two PNG files inside. Open them with any image viewer to verify the output. + +## Conclusion + +You now have a **barcode generator C#** solution that can **create Planet barcode** images, adjust the X‑dimension for optimal printing, and produce a matching RM4SCC barcode—all with a handful of lines of code. The approach works with .NET 6+, requires only the Aspose.BarCode NuGet package, and can be extended to other symbologies such as Code128, QR, or DataMatrix by swapping the `EncodeTypes` value. + +### What’s next? + +* Experiment with different `XDimension.Pixels` values to match your printer’s DPI. +* Generate barcodes in other formats (PDF, SVG) by changing the `BarCodeImageFormat` enum. +* Combine the two PNG files into a single label using a graphics library like **SkiaSharp**. +* Explore the full Aspose.BarCode API for advanced features like checksum validation or custom fonts. + +Feel free to adapt the code for batch processing or integrate it into an ASP.NET Core web service that returns barcode images on demand. 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. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-create-planet-barcode-and-rm4scc-example/og-image.png b/barcode/english/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/og-image.png new file mode 100644 index 000000000..c3e83e71d Binary files /dev/null and b/barcode/english/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/og-image.png differ diff --git a/barcode/english/python-java/general/barcode-generator-c-generate-barcode-image/_index.md b/barcode/english/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..3bb1bf286 --- /dev/null +++ b/barcode/english/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-08-03 +description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: en +lastmod: 2026-08-03 +og_description: Barcode generator C# tutorial explains how to generate barcode image + using Aspose.BarCode, configure DataBar Expanded Stacked columns and rows, and save + PNG files. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Barcode generator C# – step-by-step guide to generate barcode image +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Barcode generator C# – generate barcode image +url: /python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – generate barcode image + +If you need a barcode generator C# that can generate barcode image for DataBar Expanded Stacked, this guide walks you through the complete process. You will learn how to configure column and row settings, save the result as PNG, and adapt the code for other symbologies. + +Generating barcode images programmatically removes manual steps and ensures consistency across invoices, shipping labels, and inventory systems. This tutorial covers everything you need, from project setup to full source code, so you can run the example immediately. + +## Prerequisites + +Before you start, make sure you have: + +* .NET 6.0 or later installed +* An IDE such as Visual Studio 2022 (any editor that supports C# works) +* A license for **Aspose.BarCode for .NET** – the free evaluation works for testing +* Basic familiarity with C# syntax + +If any of these items are missing, install the .NET SDK from dotnet.microsoft.com and obtain the Aspose.BarCode NuGet package with: + +```bash +dotnet add package Aspose.BarCode +``` + +## Step 1: Create a barcode generator C# project + +Create a new console application and add the required `using` directives: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +The `BarcodeGenerator` class is the core of the barcode generator C# API. It receives the symbology type and the text to encode. + +## Step 2: Generate a DataBar Expanded Stacked barcode and set columns + +The first example creates a barcode with four columns. Adjusting the `Columns` property changes the visual density of the DataBar Expanded Stacked symbology. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Why this matters:** The column count influences the amount of data that can be stored in a compact space. Setting it to 4 produces a wider barcode that remains readable by most scanners. + +## Step 3: Generate a barcode with custom row count + +The second example shows how to control the vertical layout by setting the `Rows` property. A three‑row configuration is useful when you need a taller barcode for limited horizontal space. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Why this matters:** Adjusting rows lets you fit the barcode into a narrow column while preserving readability. The barcode generator C# automatically recalculates the module size to meet the specification. + +## Step 4: Full, runnable example + +Below is a self‑contained program that combines the previous steps. Copy the code into `Program.cs`, replace `YOUR_DIRECTORY` with an existing folder path, and run the application. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Expected output + +When you run the program, two PNG files appear in the target directory: + +* **DatabarCols4.png** – a DataBar Expanded Stacked barcode with four columns +* **DatabarRows3.png** – the same data encoded in three rows + +Open the images with any image viewer; they display sharp, scannable barcodes ready for printing or embedding in PDFs. + +## How to generate barcode image with custom dimensions + +If you need a specific image size, adjust the `ImageHeight` and `ImageWidth` properties before calling `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Changing dimensions does not affect the encoded data; it only scales the visual representation. This technique is useful when integrating barcodes into UI components with fixed layout constraints. + +## Common pitfalls and pro tips + +* **Path separators:** Use verbatim strings (`@"C:\Path\file.png"`) or `Path.Combine` to avoid escape‑character issues on Windows. +* **License enforcement:** Without a valid license, the generated images contain a watermark. Apply your license early in the application: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Encoding limits:** DataBar Expanded Stacked supports up to 74 numeric characters. Exceeding this limit throws an exception. Validate input length before creating the generator. +* **Performance:** Reusing a single `BarcodeGenerator` instance for multiple saves reduces memory allocation. Only change the `Rows` or `Columns` properties between saves if the encoded text stays the same. + +## Next steps + +Now that you can generate barcode images with the barcode generator C#, consider exploring: + +* **Different symbologies** – try `EncodeTypes.QR`, `EncodeTypes.Code128`, or `EncodeTypes.Pdf417`. +* **Color customization** – set `Parameters.Barcode.ForeColor` and `BackColor` to match branding. +* **Embedding in PDFs** – combine the generated PNG with Aspose.PDF to create printable documents. + +These extensions let you build a full‑featured barcode solution for inventory, logistics, or retail applications. + +--- + + +## 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 Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-c-generate-barcode-image/og-image.png b/barcode/english/python-java/general/barcode-generator-c-generate-barcode-image/og-image.png new file mode 100644 index 000000000..f0e24c96c Binary files /dev/null and b/barcode/english/python-java/general/barcode-generator-c-generate-barcode-image/og-image.png differ diff --git a/barcode/english/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/english/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..9a3d4a3e6 --- /dev/null +++ b/barcode/english/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-08-03 +description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: en +lastmod: 2026-08-03 +og_description: Barcode generator example demonstrates setting the X‑dimension width, + changing bar height, and generating a barcode image in C#. Follow the steps to create + PNG files. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Barcode generator example – C# width and height guide +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Barcode generator example in C# – set width and height +url: /python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator example in C# – set width and height + +If you need a **barcode generator example** in C#, this guide shows you how to set the X‑dimension width, how to change the bar height, and how to generate a barcode image file. You’ll see a complete, runnable program that produces two PNG files with different heights. + +A typical scenario is creating product labels where the barcode size must meet scanner specifications. By the end of this tutorial you will be able to adjust width and height parameters programmatically and save the result as a PNG image. + +## Prerequisites + +Before you start, make sure you have: + +* .NET 6 (or later) installed – the code targets .NET 6 SDK. +* A barcode library that supports `EncodeTypes.DatabarOmniDirectional`. The example uses **Aspose.BarCode for .NET**, but any library exposing similar properties works the same way. +* An IDE or editor (Visual Studio, VS Code, Rider) to compile and run the program. +* Write permission to a directory where the PNG files will be saved. + +> **Pro tip:** Create a folder named `Barcodes` in your project root and reference it with `Path.Combine` to avoid hard‑coding absolute paths. + +## Barcode generator example: initialize and configure + +The first step is to create a `BarcodeGenerator` instance with the desired symbology and data string. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +The `EncodeTypes.DatabarOmniDirectional` enum selects the Databar Omni‑directional symbology, and the GS1‑formatted data string `(01)12345678901231` represents a typical GTIN‑14 value. Initializing the generator once allows you to reuse the same object for multiple images. + +## How to set width (X‑dimension) + +The X‑dimension controls the module width of the barcode. Setting it to 2 pixels makes each narrow bar 2 pixels wide, which is a common requirement for high‑density printing. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Why this matters: If the width is too small, scanners may not resolve individual bars; if it’s too large, the barcode may exceed label space. Adjust the pixel value to match the printer DPI and the target label size. + +## How to change height + +Bar height determines how tall the bars appear. The example creates two images: one with a 30‑pixel height and another with a 60‑pixel height. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +The `BarHeight.Pixels` property directly influences the visual height of the bars. Changing it between saves lets you generate multiple variants from the same data payload without recreating the generator. + +### Expected output + +Running the program produces two PNG files in the `Barcodes` folder: + +* `DatabarBarHeight30Pixels.png` – bars are 30 pixels tall. +* `DatabarBarHeight60Pixels.png` – bars are 60 pixels tall. + +Both images share the same width (determined by the X‑dimension) and encode the identical GTIN‑14 data. + +![Two barcode PNG files with different heights generated by C# code](barcode-example.png "Barcode generator example showing height variations") + +*The image alt text above contains the primary keyword for accessibility and SEO.* + +## How to generate barcode image in C# + +The `Save` method handles the conversion from barcode data to an image file. You can choose other formats (JPEG, BMP, SVG) by passing a different `BarCodeImageFormat` enum value. The example uses PNG because it preserves lossless quality and is widely supported. + +If you need to embed the barcode directly into a PDF or a web page, retrieve the image as a `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +This approach eliminates the need for temporary files and is useful for high‑throughput services. + +## Common variations and edge cases + +| Situation | Adjustment | +|-----------|------------| +| **Different symbology** | Replace `EncodeTypes.DatabarOmniDirectional` with another enum value (e.g., `EncodeTypes.Code128`). | +| **Very small labels** | Decrease `XDimension.Pixels` to 1 pixel, but verify scanner readability. | +| **High‑resolution printing** | Increase both X‑dimension and bar height proportionally (e.g., 4 px width, 80 px height). | +| **Dynamic data** | Pass the data string at runtime, perhaps from a database record. | +| **Batch generation** | Loop over a collection of data strings, reusing the same `BarcodeGenerator` instance while updating `generator.Text`. | + +When you encounter an exception such as `ArgumentOutOfRangeException`, double‑check that the pixel values are positive integers and that the output directory exists. + +## Full source code recap + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Copy the code into a new console project, restore the Aspose.BarCode NuGet package (`dotnet add package Aspose.BarCode`), and run `dotnet run`. You’ll see console messages confirming the saved files. + +## Conclusion + +This **barcode generator example** demonstrates how to set width, how to change height, and how to generate a barcode image in C#. By adjusting `XDimension.Pixels` and `BarHeight.Pixels` you control the visual size of the barcode, and the `Save` method writes the result to PNG files. Experiment with different symbologies, output formats, and data strings to fit your application’s requirements. + +**Next steps** + +* Explore **how to generate barcode** in other image formats (SVG, JPEG) for web use. +* Learn **create barcode image c#** for ASP.NET Core endpoints that return the PNG directly to a browser. +* Combine this code with a PDF generation library to embed barcodes into invoices or shipping labels. + +Feel free to adapt the sample, share your results, or ask questions in the comments. 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. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to Set Border for ITF-14 Barcode Customization](/barcode/english/net/itf-14-barcode-customization/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/og-image.png b/barcode/english/python-java/general/barcode-generator-example-in-c-set-width-and-height/og-image.png new file mode 100644 index 000000000..b396ca224 Binary files /dev/null and b/barcode/english/python-java/general/barcode-generator-example-in-c-set-width-and-height/og-image.png differ diff --git a/barcode/english/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/english/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..365a81155 --- /dev/null +++ b/barcode/english/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-08-03 +description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: en +lastmod: 2026-08-03 +og_description: Create barcode PNG in C# and see how to change aspect ratio for DataBar + barcodes. This guide gives you ready‑to‑run code and practical tips. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Create barcode PNG in C# – full example with aspect‑ratio control +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Create barcode PNG in C# – step‑by‑step guide +url: /python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create barcode PNG in C# – step‑by‑step guide + +If you need to **create barcode PNG** in C#, this tutorial shows you exactly how. You will generate a stacked omnidirectional DataBar barcode, save it as a PNG file, and learn **how to change aspect ratio** to suit different scanning environments. + +The guide covers everything you need: required packages, a complete, runnable program, and explanations of why each setting matters. By the end you will have two PNG files—one with an aspect ratio of 15 and another with 30—ready for testing or production use. + +## Prerequisites + +Before you start, ensure you have: + +- .NET 6.0 SDK or later installed +- Visual Studio 2022 (or any C# IDE) +- A NuGet reference to **Aspose.BarCode** (the library that provides `BarcodeGenerator`) +- Write permission to the directory where the PNG files will be saved + +You can add the Aspose.BarCode package with the following command: + +```bash +dotnet add package Aspose.BarCode +``` + +## Step 1: Set up the project and import namespaces + +Create a new console application and import the namespaces required for barcode generation and file I/O. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Why this matters:** Importing `Aspose.BarCode.Generation` gives you access to `BarcodeGenerator`. Keeping the code inside `Main` makes the example self‑contained and easy to run. + +## Step 2: Create a barcode generator for a stacked omnidirectional DataBar + +Instantiate `BarcodeGenerator` with the `EncodeTypes.DatabarStackedOmniDirectional` type and a sample GS1‑128 data string. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Why this matters:** The chosen encode type produces a high‑density DataBar that can be read by most modern scanners. The data string follows the GS1 Application Identifier (01) format, which is common for product identifiers. + +## Step 3: Define the X‑dimension (module width) in pixels + +Set the module width to control the barcode's overall size without affecting its readability. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Why this matters:** An X‑dimension of 2 pixels yields a barcode that is neither too small for scanners nor too large for typical label spaces. + +## Step 4: Save the first PNG with an aspect ratio of 15 + +Adjust the DataBar aspect ratio, then save the image as a PNG file. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Why this matters:** The aspect ratio controls the height‑to‑width relationship of the stacked DataBar. A ratio of 15 is a common default that balances readability and label height. + +## Step 5: Change the aspect ratio to 30 and save a second PNG + +Modify the same generator instance to use a larger aspect ratio, then save the second image. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Why this matters:** Increasing the aspect ratio stretches the barcode vertically, which can improve scan reliability on low‑resolution devices or when the label is printed on narrow media. + +## Expected output + +Running the program creates two PNG files: + +| File | Aspect Ratio | Approximate dimensions (pixels) | +|------------------------------------|--------------|---------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (width × height) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (width × height) | + +Both images contain a clear, scannable DataBar barcode that encodes the GS1 identifier `(01)12345678901231`. + +## Common questions and edge cases + +### How to change other visual properties? + +You can adjust foreground color, background color, or add human‑readable text through the `generator.Parameters.Barcode` object. For example: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### What if I need a different image format? + +Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. PNG remains the best choice for lossless barcode images. + +### Does the aspect ratio affect scanning speed? + +Higher aspect ratios increase the barcode’s height, which can improve scan reliability on devices that struggle with short stacked symbols. However, extremely tall barcodes may not fit on small labels, so test with your target hardware. + +### Can I generate multiple barcodes in a loop? + +Yes. Create a new `BarcodeGenerator` instance for each data string or reuse the same instance while updating `CodeText` and `DataBar.AspectRatio`. This approach reduces object allocation overhead. + +## Pro tips + +- **Reuse the generator**: Changing only the `CodeText` or `AspectRatio` avoids re‑instantiating the object, which speeds up batch processing. +- **Validate the output**: Use a handheld scanner or a mobile app to confirm the generated PNG reads correctly before deploying to production. +- **File naming**: Include the aspect ratio in the file name (as shown) to keep track of variations during testing. + +## Conclusion + +You now know how to **create barcode PNG** files in C# and precisely **how to change aspect ratio** for stacked omnidirectional DataBar symbols. The complete example demonstrates initialization, X‑dimension setting, aspect‑ratio manipulation, and image saving—all in a single, runnable program. + +From here you can explore additional barcode types, experiment with colors, or integrate the generator into a larger reporting or inventory system. 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. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-c-step-by-step-guide/og-image.png b/barcode/english/python-java/general/create-barcode-png-in-c-step-by-step-guide/og-image.png new file mode 100644 index 000000000..085bedfd1 Binary files /dev/null and b/barcode/english/python-java/general/create-barcode-png-in-c-step-by-step-guide/og-image.png differ diff --git a/barcode/english/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md b/barcode/english/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..f628a92b7 --- /dev/null +++ b/barcode/english/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-08-03 +description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: en +lastmod: 2026-08-03 +og_description: Create barcode PNG instantly. This tutorial shows how to generate + barcode image and generate planet barcode with Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Create barcode PNG in Python – complete programming guide +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Create barcode PNG in Python – step‑by‑step guide +url: /python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create barcode PNG in Python – step‑by‑step guide + +If you need to **create barcode PNG** files from your Python application, this tutorial shows you exactly how. We’ll walk through **how to generate barcode image** using Aspose.BarCode and specifically **generate planet barcode** with custom dimensions. + +You’ll learn how to install the library, configure the Planet symbology, adjust size parameters, and save the result as a high‑quality PNG. The guide assumes basic Python knowledge and a recent version of Python 3 (3.8 or newer). No prior experience with barcode standards is required. + +--- + +## How to create barcode PNG with Aspose.BarCode + +This section contains the core steps required to **create barcode PNG**. Each step includes a code snippet, an explanation of why it matters, and practical tips you can apply immediately. + +### 1. Install the Aspose.BarCode package + +Aspose provides a pure‑Python package that wraps its .NET core engine. Install it with `pip`: + +```bash +pip install aspose-barcode +``` + +*Why this step matters:* The package supplies the `BarcodeGenerator` class used throughout the example. Installing it globally ensures the interpreter can locate the assembly at runtime. + +### 2. Import required classes + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Tip:* Import only the symbols you need; this keeps the namespace clean and speeds up module loading. + +### 3. Create a barcode generator for the Planet symbology + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Why this matters:* `EncodeTypes.Planet` tells the engine to use the Planet barcode standard, while the second argument supplies the data to encode. Changing the symbology (e.g., `EncodeTypes.Code128`) would produce a completely different visual pattern. + +### 4. Set the X dimension (module width) in pixels + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Explanation:* The X dimension controls the narrow bar width. A value of 4 pixels yields a moderately dense barcode that remains scannable on most devices. + +### 5. Define a manual bar height in pixels + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Why you might adjust this:* Some retail printers require taller bars for reliable scanning. The default height is usually 50 px; increasing it to 100 px improves readability without enlarging the file size dramatically. + +### 6. Save the generated barcode as a PNG image + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Result:* A PNG file named **PlanetBarHeight100.png** appears in the `output` folder. PNG is loss‑less, making it ideal for printing and for embedding in web pages. + +### 7. Verify the output (optional) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Tip:* Viewing the image confirms that the dimensions match the parameters you set. If the barcode looks distorted, revisit the X dimension or bar height settings. + +--- + +## How to generate barcode image in PNG format (alternative settings) + +If you need a different image format or want to embed the barcode in a PDF later, you can change the `BarCodeImageFormat` enum: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Why this matters:* PNG preserves every pixel, which is crucial for high‑contrast barcodes. JPEG introduces compression artifacts that can interfere with scanning, while BMP offers compatibility with older tools. + +--- + +## Generate planet barcode with custom colors (advanced) + +Beyond size, you can customize foreground and background colors: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Practical tip:* High‑contrast color pairs (dark on light) maximize scanner reliability. Avoid using similar hues for foreground and background. + +--- + +## Common pitfalls and how to avoid them + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Barcode does not scan | X dimension too small (≤ 2 px) | Increase `x_dimension.pixels` to at least 3 px | +| Image appears blurry | PNG saved at low DPI | Use `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` to specify 300 DPI (if supported) | +| Exception `ImportError` | Aspose.BarCode not installed | Run `pip install aspose-barcode` in the same environment as your script | +| Wrong symbology | Used `EncodeTypes.Code128` instead of `EncodeTypes.Planet` | Replace with `EncodeTypes.Planet` when creating the generator | + +--- + +## Recap of the complete solution + +Below is the full, runnable script that **creates barcode PNG** from start to finish: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Running this script produces a crisp **Planet barcode PNG** that you can embed in HTML, attach to emails, or print on product labels. + +--- + +## Next steps and related topics + +* **Integrate with Flask or Django** – serve the generated PNG directly from a web endpoint. +* **Batch generation** – loop over a list of product IDs to create a folder of barcode PNG files. +* **Combine with PDF generation** – use `aspose-pdf` to place the PNG into an invoice or shipping label. +* **Explore other symbologies** – replace `EncodeTypes.Planet` with `EncodeTypes.QR`, `EncodeTypes.DataMatrix`, or `EncodeTypes.Code128` to meet different business needs. + +By mastering the steps above, you now know **how to generate barcode image** programmatically and can extend the pattern to any barcode standard supported by Aspose.BarCode. + +--- + +### + +{{< /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-png-in-python-step-by-step-guide/og-image.png b/barcode/english/python-java/general/create-barcode-png-in-python-step-by-step-guide/og-image.png new file mode 100644 index 000000000..b1c4a719f Binary files /dev/null and b/barcode/english/python-java/general/create-barcode-png-in-python-step-by-step-guide/og-image.png differ diff --git a/barcode/english/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/english/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..16cbeb1a6 --- /dev/null +++ b/barcode/english/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-08-03 +description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: en +lastmod: 2026-08-03 +og_description: Create postal barcode image in C# with this complete tutorial; learn + how to set barcode dimensions, generate a Planet barcode, and produce RM4SCC barcodes. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Create postal barcode image in C# – full programming guide +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Create postal barcode image in C# – step‑by‑step guide +url: /python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create postal barcode image in C# – step‑by‑step guide + +If you need to **create postal barcode image** in C#, this guide shows you exactly how. We'll cover **how to generate postal barcode**, **how to set barcode dimensions**, and how to **generate planet barcode** for common postal standards. + +You’ll finish with two ready‑to‑use PNG files—one Planet barcode and one RM4SCC barcode—each 100 px tall. No additional tools are required beyond the Aspose.BarCode for .NET library. + +## Prerequisites + +* .NET 6 SDK or later (the code also works with .NET Framework 4.7+) +* Visual Studio 2022 or any C# IDE +* NuGet package **Aspose.BarCode** (the library that provides `BarcodeGenerator`) + +## Step 1: Install the barcode library + +Open a terminal in your project folder and run: + +```bash +dotnet add package Aspose.BarCode +``` + +The package adds the `Aspose.BarCode` namespace, which contains `BarcodeGenerator` and the `EncodeTypes` enumeration needed for postal barcodes. + +## Step 2: Define the output folder + +Creating a reliable output path prevents runtime errors when the folder does not exist. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Why this matters*: `Directory.CreateDirectory` is idempotent—it creates the folder only if it isn’t already present, avoiding exceptions on subsequent runs. + +## Step 3: Configure common barcode dimensions + +Setting the X‑dimension (width of a single bar) and the overall bar height lets you control the visual size of the generated image. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**How to set barcode dimensions**: The `Parameters.Barcode.XDimension.Pixels` property defines the narrow bar width, while `Parameters.Barcode.BarHeight.Pixels` defines the full height. Adjust these values to meet the specifications of your mailing service. + +## Step 4: Generate a Planet barcode + +Planet is a widely used postal barcode in the United Kingdom. The following code creates a 100 px‑high Planet barcode and saves it as PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Why this works**: `EncodeTypes.Planet` tells the generator to use the Planet symbology. The `Save` method writes a PNG file to the specified path, preserving the dimensions we set earlier. + +## Step 5: Generate an RM4SCC barcode + +RM4SCC is the Dutch postal barcode standard. The code below mirrors the Planet example, demonstrating **how to generate postal barcode** of a different type with identical dimensions. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Both PNG files now reside in the `Barcodes` folder. Opening them will show clean, 100 px‑high barcodes ready for printing or embedding in documents. + +## Full source code + +Below is the complete, runnable program that **creates postal barcode image** files for both Planet and RM4SCC standards. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Expected output + +Running the program prints the file paths and creates two PNG files: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Each image is 100 px tall, with a 4‑pixel narrow bar width, matching the dimensions we set. + +## Practical tips and common pitfalls + +* **Folder permissions** – If the program runs under a restricted account, ensure the target folder is writable. +* **Different dimensions** – To create a taller barcode, increase `barHeightPixels`. For finer resolution, lower `xDimensionPixels`, but keep it ≥ 2 to avoid rendering artifacts. +* **Other postal symbologies** – Aspose.BarCode also supports `EncodeTypes.Postnet` and `EncodeTypes.AustralianPost`. Swap the `EncodeTypes` value and keep the same dimension logic. +* **Image format** – Use `BarCodeImageFormat.Jpeg` for smaller file size when lossless quality isn’t required. + +## Conclusion + +You now know how to **create postal barcode image** files in C# by configuring dimensions, selecting the proper symbology, and saving the result as PNG. The tutorial covered **how to generate postal barcode**, demonstrated **generate planet barcode**, and explained **how to set barcode dimensions** for consistent output. + +Next, explore **customizing barcode colors**, adding **human‑readable text**, or integrating the images into PDF invoices. The same pattern applies to any other barcode type supported by Aspose.BarCode, letting you extend this solution to a full postal automation workflow. + + +## 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 - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to generate barcode java – Australia Post Barcode with Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/og-image.png b/barcode/english/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/og-image.png new file mode 100644 index 000000000..073c1a75c Binary files /dev/null and b/barcode/english/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/og-image.png differ diff --git a/barcode/english/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/english/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..9c3d441fc --- /dev/null +++ b/barcode/english/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-08-03 +description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: en +lastmod: 2026-08-03 +og_description: How to save barcode in C# using a barcode generator example. This + tutorial shows how to generate Planet barcodes, configure X‑dimension, and export + PNG files. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: How to save barcode in C# – step‑by‑step guide +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: How to save barcode in C# – complete barcode generator guide +url: /python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to save barcode in C# – complete barcode generator guide + +How to save barcode images in C# is a common requirement when you need to embed postal barcodes into invoices, shipping labels, or inventory tags. This guide walks you through a practical **c# barcode generator** workflow, from creating a Planet barcode to exporting both filled‑bars and empty‑bars PNG files. + +You’ll learn how to set the bar width, toggle filled bars, and handle output folders reliably. By the end of the tutorial you will have a fully functional **barcode generator example** that you can copy into any .NET project. + +## What you’ll need + +Before writing code, make sure you have: + +- .NET 6.0 SDK or later (the example works with .NET Core and .NET Framework) +- Visual Studio 2022 or any C#‑compatible IDE +- The **Aspose.BarCode** NuGet package (or another library that supports `EncodeTypes.Planet`). Install it with: + +```bash +dotnet add package Aspose.BarCode +``` + +The library provides the `BarcodeGenerator` class used throughout this tutorial. + +## Setting up the development environment + +Create a new console project and add the required namespace: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +The `System.IO` namespace gives us `Directory.CreateDirectory`, which ensures the output folder exists before we attempt to write files. + +## How to save barcode images with the C# barcode generator + +The core of the solution is a small set of steps that configure a **Planet barcode** and then persist the image to disk. The following sections break the process into manageable pieces. + +### Step 1: Define the output folder + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Why?** +Hard‑coding a path can cause `DirectoryNotFoundException` on machines where the folder does not exist. `CreateDirectory` is idempotent—it creates the directory only if it’s missing, making the code safe for repeated runs. + +### Step 2: Create a Planet barcode generator (filled bars) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Why?** +`EncodeTypes.Planet` tells the library to produce a postal Planet barcode, which is widely used by mail services. The string `"123456"` is the sample payload; replace it with any numeric data required by your business logic. + +### Step 3: Configure bar width (X‑dimension) and keep default filled bars + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Why?** +The X‑dimension controls the physical width of each bar. A value of `4` pixels yields a readable barcode on standard 300 dpi printers. Leaving `FilledBars` as `true` (the default) produces the classic solid‑bar appearance. + +### Step 4: Save the filled‑bars barcode image + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Why?** +Saving as PNG preserves lossless image quality, which is important for scanning accuracy. The `Save` method automatically creates the image file; you only need to supply the full path and desired format. + +### Step 5: Create a second generator for the empty‑bars version + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Creating a new instance ensures that changes made for the empty‑bars version do not affect the already‑saved filled‑bars image. + +### Step 6: Disable filled bars while keeping the same X‑dimension + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Why?** +Setting `FilledBars = false` renders the barcode with only the outline of each bar, which some postal standards require for visual verification. + +### Step 7: Save the empty‑bars barcode image + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Now you have two PNG files—one with filled bars and one with empty bars—ready for inclusion in PDFs, HTML emails, or printed labels. + +## Full runnable program + +Below is the complete code you can copy into `Program.cs`. It compiles and runs without modification (assuming the Aspose.BarCode package is installed). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Expected output + +Running the program prints two lines similar to: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Open the `Barcodes` folder and you’ll see the two PNG files. Both images can be opened in any image viewer or embedded directly into documents. + +![how to save barcode example](barcode-example.png){: .align-center alt="how to save barcode example"} + +## Common variations and edge cases + +| Scenario | Adjustment | +|----------|------------| +| **Different image format** | Change `BarCodeImageFormat.Png` to `Jpeg`, `Gif`, or `Bmp` as needed. | +| **Custom output size** | Use `filled.Parameters.Image.Width` and `Height` to force a specific pixel dimension. | +| **Dynamic data** | Replace the static `"123456"` with a variable that holds order numbers, tracking IDs, etc. | +| **Non‑existent folder** | `Directory.CreateDirectory` already handles missing directories; no extra code required. | +| **High‑resolution printing** | Increase `XDimension.Pixels` to 6–8 for 600 dpi printers, but verify scanner compatibility. | + +**Pro tip:** If you need to generate many barcodes in a loop, reuse a single `BarcodeGenerator` instance and only change the `CodeText` property before each `Save`. This reduces object allocation overhead. + +## How to generate barcode for other standards + +The same pattern works for other `EncodeTypes` such as `Code128`, `QR`, or `DataMatrix`. Simply replace `EncodeTypes.Planet` with the desired type and adjust any type‑specific parameters (e.g., `QRCodeVersion` + + +## 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 Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/how-to-save-barcode-in-c-complete-barcode-generator-guide/og-image.png b/barcode/english/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/og-image.png new file mode 100644 index 000000000..5371702f5 Binary files /dev/null and b/barcode/english/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/og-image.png differ diff --git a/barcode/french/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/french/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..ca0c649ca --- /dev/null +++ b/barcode/french/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-03 +description: Tutoriel C# sur le générateur de codes-barres montrant comment créer + un code-barres Planet avec Aspose.BarCode, définir la dimension X et enregistrer + en images PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: fr +lastmod: 2026-08-03 +og_description: Le tutoriel du générateur de codes‑barres C# vous guide dans la création + d’un code‑barres Planet, l’ajustement de la dimension X et l’enregistrement au format + PNG à l’aide d’Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Générateur de code‑barres C# – créer un code‑barres Planet étape par étape +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Générateur de codes-barres C# – créer un code-barres Planet et un exemple RM4SCC +url: /fr/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Générateur de code-barres C# – créer un code-barres Planet et un exemple RM4SCC + +Si vous avez besoin d’un **générateur de code-barres C#** capable de produire des symboles postaux spécifiques, ce guide vous montre exactement comment **créer des images de code-barres Planet** avec Aspose.BarCode. Vous verrez comment configurer la dimension X, générer un code‑barres RM4SCC correspondant, et enregistrer les deux au format PNG — le tout en quelques étapes concises. + +Le tutoriel couvre tout ce dont vous avez besoin pour exécuter le code sur .NET 6 ou version ultérieure, explique pourquoi chaque paramètre est important, et signale les pièges courants tels qu’une largeur de module incorrecte ou des permissions de répertoire manquantes. À la fin, vous disposerez de deux images de code‑barres prêtes à imprimer, conformes aux normes Planet et RM4SCC. + +## Prérequis + +Avant de commencer, assurez‑vous d’avoir : + +* SDK .NET 6 (ou toute version .NET prise en charge par Aspose.BarCode) +* Visual Studio 2022 ou tout IDE C# de votre choix +* Une référence NuGet à **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Le droit d’écriture sur le dossier où vous prévoyez d’enregistrer les fichiers PNG + +Aucun service externe supplémentaire n’est requis ; la bibliothèque gère tout le codage en local. + +## Étape 1 : Initialiser l’objet générateur de code‑barres C# + +La première tâche consiste à créer une instance de `BarcodeGenerator`. Le constructeur prend la symbologie du code‑barres (`EncodeTypes.Planet`) et les données à encoder. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Pourquoi cette étape ?* +`BarcodeGenerator` est le point d’entrée pour chaque code‑barres que vous générez. Sélectionner `EncodeTypes.Planet` indique à la bibliothèque de suivre la spécification ISO/IEC 24723 utilisée par de nombreux services postaux. + +## Étape 2 : Définir la dimension X (largeur du module) pour le code‑barres Planet + +La dimension X définit la largeur d’un seul module de code‑barres (la plus petite barre ou espace). Une valeur de **4 pixels** fonctionne bien pour la plupart des imprimantes d’étiquettes. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pourquoi c’est important* +Si le module est trop étroit, le code‑barres peut devenir illisible ; s’il est trop large, la taille de l’étiquette augmente inutilement. Ajuster `Pixels` vous permet d’affiner le code‑barres en fonction de la résolution de votre imprimante. + +## Étape 3 : Enregistrer le code‑barres Planet en image PNG + +Aspose.BarCode calcule automatiquement la hauteur du code‑barres en fonction de la symbologie sélectionnée, vous n’avez donc qu’à spécifier le chemin du fichier et le format. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Astuce* +Remplacez `YOUR_DIRECTORY` par un chemin absolu ou relatif existant sur votre machine. Si le répertoire n’existe pas, la méthode `Save` lève une `DirectoryNotFoundException`. + +**Résultat attendu** – un fichier PNG similaire à l’illustration ci‑dessous (l’image réelle n’est pas affichée ici, mais vous verrez un code‑barres Planet classique avec une charge numérique `123456`). + +## Étape 4 : Initialiser un second générateur pour le code‑barres RM4SCC + +De nombreux systèmes postaux exigent à la fois les symboles Planet et RM4SCC sur le même envoi. Créez une nouvelle instance de `BarcodeGenerator` pour la symbologie RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Pourquoi une instance séparée ?* +Chaque symbologie possède son propre jeu de paramètres. Réutiliser le même générateur pourrait transférer involontairement des réglages (comme la dimension X) qui ne sont pas optimaux pour le second code‑barres. + +## Étape 5 : Configurer la dimension X pour le code‑barres RM4SCC + +RM4SCC respecte également le réglage de la dimension X, nous appliquons donc la même largeur en pixels pour garantir une cohérence visuelle. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +Si vous avez besoin d’un code‑barres plus haut (par ex., pour des étiquettes plus grandes), vous pouvez également définir `Height.Pixels`. Le laisser non défini permet à la bibliothèque de calculer automatiquement la hauteur idéale. + +## Étape 6 : Enregistrer le code‑barres RM4SCC en image PNG + +Enfin, persistez le code‑barres RM4SCC sur le disque. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Vous disposez maintenant de deux fichiers PNG — `PostalPlanetBarHeightNone.png` et `PostalRM4SCCBarHeightNone.png` — que vous pouvez intégrer dans des étiquettes postales, imprimer sur des enveloppes, ou envoyer à un service d’impression tiers. + +## Optionnel : Ajuster la hauteur ou utiliser d’autres formats d’image + +Si votre flux de travail nécessite une hauteur de code‑barres spécifique ou un format d’image différent (par ex., JPEG ou BMP), vous pouvez modifier les paramètres avant d’appeler `Save` : + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Cas limite** – Lorsque vous définissez une hauteur personnalisée, assurez‑vous que la valeur respecte la hauteur minimale requise par la norme ISO ; sinon le code‑barres risque d’échouer à la validation. + +## Pièges courants et comment les éviter + +| Piège | Pourquoi cela se produit | Solution | +|-------|--------------------------|----------| +| `DirectoryNotFoundException` | Le dossier cible n’existe pas ou est mal orthographié. | Créez le dossier au préalable ou utilisez `Path.Combine` avec `Environment.CurrentDirectory`. | +| Code‑barres illisible sur imprimantes basse résolution | Dimension X trop petite pour le DPI de l’imprimante. | Augmentez `XDimension.Pixels` à 5 – 6 pour les imprimantes 203 dpi, ou testez avec une étiquette d’échantillon. | +| Mauvaise symbologie utilisée | Passage de `EncodeTypes.Code128` au lieu de `EncodeTypes.Planet`. | Vérifiez que la valeur de l’énumération `EncodeTypes` correspond à la norme postale requise. | +| Référence nulle sur `Parameters` | Utilisation d’une version plus ancienne d’Aspose.BarCode où l’API diffère. | Mettez à jour vers le dernier package NuGet (v23.12 ou ultérieur). | + +## Exemple complet exécutable + +Voici le programme complet que vous pouvez copier, coller et exécuter. Il inclut les instructions `using`, la gestion des erreurs, et des commentaires expliquant chaque ligne. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +L’exécution du programme crée un dossier `Barcodes` à côté de l’exécutable et y place les deux fichiers PNG. Ouvrez‑les avec n’importe quel visualiseur d’image pour vérifier le résultat. + +## Conclusion + +Vous disposez maintenant d’une solution **générateur de code‑barres C#** capable de **créer des images de code‑barres Planet**, d’ajuster la dimension X pour une impression optimale, et de produire un code‑barres RM4SCC correspondant — le tout en quelques lignes de code. Cette approche fonctionne avec .NET 6+, ne nécessite que le package NuGet Aspose.BarCode, et peut être étendue à d’autres symbologies telles que Code128, QR ou DataMatrix en changeant la valeur `EncodeTypes`. + +### Et après ? + +* Expérimentez avec différentes valeurs `XDimension.Pixels` pour correspondre au DPI de votre imprimante. +* Générez des code‑barres dans d’autres formats (PDF, SVG) en modifiant l’énumération `BarCodeImageFormat`. +* Combinez les deux fichiers PNG en une seule étiquette à l’aide d’une bibliothèque graphique comme **SkiaSharp**. +* Explorez l’API complète d’Aspose.BarCode pour des fonctionnalités avancées comme la validation de checksum ou les polices personnalisées. + +N’hésitez pas à adapter le code pour du traitement par lots ou à l’intégrer dans un service web ASP.NET Core qui renvoie des images de code‑barres à la demande. Bon codage ! + +## Que devez‑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 fonctionnels complets avec des explications pas à pas pour vous aider à maîtriser d’autres fonctionnalités de l’API et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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/barcode-generator-c-generate-barcode-image/_index.md b/barcode/french/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..f35bdf60f --- /dev/null +++ b/barcode/french/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: Le tutoriel de génération de code‑barres en C# montre comment créer une + image de code‑barres avec Aspose.BarCode, définir les colonnes et les lignes, et + enregistrer des fichiers PNG pour DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: fr +lastmod: 2026-08-03 +og_description: Le tutoriel du générateur de code‑barres C# explique comment créer + une image de code‑barres avec Aspose.BarCode, configurer les colonnes et lignes + DataBar Expanded Stacked, puis enregistrer des fichiers PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Générateur de code-barres C# – guide étape par étape pour générer une image + de code-barres +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Générateur de code-barres C# – générer une image de code-barres +url: /fr/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Générateur de code-barres C# – générer une image de code-barres + +Si vous avez besoin d'un générateur de code-barres C# capable de créer une image de code-barres pour DataBar Expanded Stacked, ce guide vous accompagne tout au long du processus complet. Vous apprendrez comment configurer les paramètres de colonnes et de lignes, enregistrer le résultat au format PNG, et adapter le code à d'autres symbologies. + +Générer des images de code-barres par programme élimine les étapes manuelles et garantit la cohérence sur les factures, les étiquettes d'expédition et les systèmes d'inventaire. Ce tutoriel couvre tout ce dont vous avez besoin, de la configuration du projet au code source complet, afin que vous puissiez exécuter l'exemple immédiatement. + +## Prérequis + +Avant de commencer, assurez-vous d'avoir : + +* .NET 6.0 ou version ultérieure installé +* Un IDE tel que Visual Studio 2022 (tout éditeur supportant C# fonctionne) +* Une licence pour **Aspose.BarCode for .NET** – l'évaluation gratuite fonctionne pour les tests +* Familiarité de base avec la syntaxe C# + +Si l'un de ces éléments manque, installez le SDK .NET depuis dotnet.microsoft.com et obtenez le package NuGet Aspose.BarCode avec : + +```bash +dotnet add package Aspose.BarCode +``` + +## Étape 1 : Créer un projet de générateur de code-barres C# + +Créez une nouvelle application console et ajoutez les directives `using` requises : + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +La classe `BarcodeGenerator` est le cœur de l'API du générateur de code-barres C#. Elle reçoit le type de symbologie et le texte à encoder. + +## Étape 2 : Générer un code-barres DataBar Expanded Stacked et définir les colonnes + +Le premier exemple crée un code-barres avec quatre colonnes. Modifier la propriété `Columns` change la densité visuelle de la symbologie DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Pourquoi c'est important :** Le nombre de colonnes influence la quantité de données pouvant être stockées dans un espace compact. Le régler à 4 produit un code-barres plus large qui reste lisible par la plupart des scanners. + +## Étape 3 : Générer un code-barres avec un nombre de lignes personnalisé + +Le deuxième exemple montre comment contrôler la disposition verticale en définissant la propriété `Rows`. Une configuration à trois lignes est utile lorsque vous avez besoin d'un code-barres plus haut pour un espace horizontal limité. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Pourquoi c'est important :** Ajuster les lignes vous permet d'adapter le code-barres à une colonne étroite tout en préservant la lisibilité. Le générateur de code-barres C# recalcule automatiquement la taille du module pour respecter la spécification. + +## Étape 4 : Exemple complet et exécutable + +Ci-dessous se trouve un programme autonome qui combine les étapes précédentes. Copiez le code dans `Program.cs`, remplacez `YOUR_DIRECTORY` par un chemin de dossier existant, puis exécutez l'application. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Sortie attendue + +Lorsque vous exécutez le programme, deux fichiers PNG apparaissent dans le répertoire cible : + +* **DatabarCols4.png** – un code-barres DataBar Expanded Stacked avec quatre colonnes +* **DatabarRows3.png** – les mêmes données encodées sur trois lignes + +Ouvrez les images avec n'importe quel visualiseur d'images ; elles affichent des codes-barres nets et scannables, prêts à être imprimés ou intégrés dans des PDF. + +## Comment générer une image de code-barres avec des dimensions personnalisées + +Si vous avez besoin d'une taille d'image spécifique, ajustez les propriétés `ImageHeight` et `ImageWidth` avant d'appeler `Save` : + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Modifier les dimensions n'affecte pas les données encodées ; cela ne fait que mettre à l'échelle la représentation visuelle. Cette technique est utile lors de l'intégration de codes-barres dans des composants UI avec des contraintes de mise en page fixes. + +## Écueils courants et astuces professionnelles + +* **Séparateurs de chemin :** Utilisez des chaînes verbatim (`@"C:\Path\file.png"`) ou `Path.Combine` pour éviter les problèmes de caractères d'échappement sous Windows. +* **Application de la licence :** Sans licence valide, les images générées contiennent un filigrane. Appliquez votre licence tôt dans l'application : + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Limites d'encodage :** DataBar Expanded Stacked prend en charge jusqu'à 74 caractères numériques. Dépasser cette limite génère une exception. Validez la longueur de l'entrée avant de créer le générateur. +* **Performance :** Réutiliser une seule instance de `BarcodeGenerator` pour plusieurs sauvegardes réduit l'allocation mémoire. Ne modifiez les propriétés `Rows` ou `Columns` entre les sauvegardes que si le texte encodé reste identique. + +## Étapes suivantes + +Maintenant que vous pouvez générer des images de code-barres avec le générateur de code-barres C#, envisagez d'explorer : + +* **Différentes symbologies** – essayez `EncodeTypes.QR`, `EncodeTypes.Code128` ou `EncodeTypes.Pdf417`. +* **Personnalisation des couleurs** – définissez `Parameters.Barcode.ForeColor` et `BackColor` pour correspondre à votre identité visuelle. +* **Intégration dans les PDF** – combinez le PNG généré avec Aspose.PDF pour créer des documents imprimables. + +Ces extensions vous permettent de créer une solution de code-barres complète pour les applications d'inventaire, de logistique ou de vente au détail. + +--- + + +## 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 générer des codes-barres DataMatrix (ECC 200) avec Aspose.BarCode pour .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/french/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..5e8cc28e4 --- /dev/null +++ b/barcode/french/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-08-03 +description: Exemple de générateur de code‑barres en C# montrant comment définir la + largeur, comment modifier la hauteur et comment générer l’image du code‑barres. + Suivez les instructions étape par étape. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: fr +lastmod: 2026-08-03 +og_description: L'exemple de générateur de code‑barres montre comment définir la largeur + de la dimension X, modifier la hauteur des barres et générer une image de code‑barres + en C#. Suivez les étapes pour créer des fichiers PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Exemple de générateur de code‑barres – Guide de la largeur et de la hauteur + en C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Exemple de générateur de code‑barres en C# – définir la largeur et la hauteur +url: /fr/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< 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 en C# – définir la largeur et la hauteur + +Si vous avez besoin d'un **exemple de générateur de code-barres** en C#, ce guide vous montre comment définir la largeur de la dimension X, comment modifier la hauteur des barres, et comment générer un fichier image de code-barres. Vous verrez un programme complet et exécutable qui produit deux fichiers PNG avec des hauteurs différentes. + +Un scénario typique consiste à créer des étiquettes produit où la taille du code-barres doit répondre aux spécifications du lecteur. À la fin de ce tutoriel, vous serez capable d'ajuster les paramètres de largeur et de hauteur par programme et d'enregistrer le résultat sous forme d'image PNG. + +## Prérequis + +Avant de commencer, assurez‑vous d'avoir : + +* .NET 6 (ou version ultérieure) installé – le code cible le SDK .NET 6. +* Une bibliothèque de code-barres qui prend en charge `EncodeTypes.DatabarOmniDirectional`. L'exemple utilise **Aspose.BarCode for .NET**, mais toute bibliothèque exposant des propriétés similaires fonctionne de la même manière. +* Un IDE ou éditeur (Visual Studio, VS Code, Rider) pour compiler et exécuter le programme. +* Permission d'écriture sur un répertoire où les fichiers PNG seront enregistrés. + +> **Astuce :** Créez un dossier nommé `Barcodes` à la racine de votre projet et référencez‑le avec `Path.Combine` pour éviter de coder en dur des chemins absolus. + +## Exemple de générateur de code-barres : initialisation et configuration + +La première étape consiste à créer une instance de `BarcodeGenerator` avec la symbologie et la chaîne de données souhaitées. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +L'énumération `EncodeTypes.DatabarOmniDirectional` sélectionne la symbologie Databar Omni‑directional, et la chaîne de données formatée GS1 `(01)12345678901231` représente une valeur GTIN‑14 typique. Initialiser le générateur une fois vous permet de réutiliser le même objet pour plusieurs images. + +## Comment définir la largeur (dimension X) + +La dimension X contrôle la largeur du module du code-barres. La régler à 2 pixels rend chaque barre étroite de 2 pixels de large, ce qui est une exigence courante pour l'impression haute densité. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Pourquoi c’est important : si la largeur est trop petite, les lecteurs peuvent ne pas distinguer les barres individuelles ; si elle est trop grande, le code-barres peut dépasser l'espace de l'étiquette. Ajustez la valeur en pixels pour correspondre au DPI de l'imprimante et à la taille cible de l'étiquette. + +## Comment modifier la hauteur + +La hauteur des barres détermine la taille verticale des barres. L'exemple crée deux images : une avec une hauteur de 30 pixels et une autre avec une hauteur de 60 pixels. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +La propriété `BarHeight.Pixels` influence directement la hauteur visuelle des barres. La modifier entre deux sauvegardes vous permet de générer plusieurs variantes à partir des mêmes données sans recréer le générateur. + +### Résultat attendu + +L'exécution du programme produit deux fichiers PNG dans le dossier `Barcodes` : + +* `DatabarBarHeight30Pixels.png` – les barres mesurent 30 pixels de hauteur. +* `DatabarBarHeight60Pixels.png` – les barres mesurent 60 pixels de hauteur. + +Les deux images partagent la même largeur (déterminée par la dimension X) et codent les mêmes données GTIN‑14. + +![Deux fichiers PNG de code-barres avec des hauteurs différentes générés par du code C#](barcode-example.png "Exemple de générateur de code-barres montrant les variations de hauteur") + +*Le texte alternatif de l'image ci‑dessus contient le mot‑clé principal pour l'accessibilité et le SEO.* + +## Comment générer une image de code-barres en C# + +La méthode `Save` gère la conversion des données du code-barres en fichier image. Vous pouvez choisir d'autres formats (JPEG, BMP, SVG) en passant une valeur différente de l'énumération `BarCodeImageFormat`. L'exemple utilise le PNG car il conserve une qualité sans perte et est largement supporté. + +Si vous devez intégrer le code-barres directement dans un PDF ou une page web, récupérez l'image sous forme de `byte[]` : + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Cette approche élimine le besoin de fichiers temporaires et est utile pour les services à haut débit. + +## Variantes courantes et cas limites + +| Situation | Ajustement | +|-----------|------------| +| **Symbologie différente** | Remplacez `EncodeTypes.DatabarOmniDirectional` par une autre valeur d'énumération (par ex., `EncodeTypes.Code128`). | +| **Étiquettes très petites** | Diminuez `XDimension.Pixels` à 1 pixel, mais vérifiez la lisibilité par le lecteur. | +| **Impression haute résolution** | Augmentez à la fois la dimension X et la hauteur des barres proportionnellement (par ex., largeur de 4 px, hauteur de 80 px). | +| **Données dynamiques** | Passez la chaîne de données à l'exécution, éventuellement depuis un enregistrement de base de données. | +| **Génération par lots** | Parcourez une collection de chaînes de données, en réutilisant la même instance `BarcodeGenerator` tout en mettant à jour `generator.Text`. | + +Lorsque vous rencontrez une exception telle que `ArgumentOutOfRangeException`, vérifiez que les valeurs en pixels sont des entiers positifs et que le répertoire de sortie existe. + +## Récapitulatif du code source complet + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Copiez le code dans un nouveau projet console, restaurez le package NuGet Aspose.BarCode (`dotnet add package Aspose.BarCode`), et exécutez `dotnet run`. Vous verrez des messages console confirmant les fichiers enregistrés. + +## Conclusion + +Cet **exemple de générateur de code-barres** montre comment définir la largeur, comment modifier la hauteur, et comment générer une image de code-barres en C#. En ajustant `XDimension.Pixels` et `BarHeight.Pixels`, vous contrôlez la taille visuelle du code-barres, et la méthode `Save` écrit le résultat dans des fichiers PNG. Expérimentez avec différentes symbologies, formats de sortie et chaînes de données pour répondre aux exigences de votre application. + +**Prochaines étapes** + +* Explorez **comment générer un code-barres** dans d'autres formats d'image (SVG, JPEG) pour le web. +* Apprenez **create barcode image c#** pour les points de terminaison ASP.NET Core qui renvoient le PNG directement à un navigateur. +* Combinez ce code avec une bibliothèque de génération de PDF pour intégrer des codes-barres dans les factures ou les étiquettes d'expédition. + +N'hésitez pas à adapter l'exemple, partager vos résultats, ou poser des questions dans les commentaires. 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 API supplémentaires et explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Comment générer un code-barres - Types de codes-barres unidimensionnels](/barcode/english/net/one-dimensional-barcode-types/) +- [Comment définir la bordure pour la personnalisation du code-barres ITF-14](/barcode/english/net/itf-14-barcode-customization/) +- [Comment générer des codes-barres DataMatrix (ECC 200) avec Aspose.BarCode pour .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/french/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..e726cb01e --- /dev/null +++ b/barcode/french/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-08-03 +description: Créez un PNG de code‑barres en C# et apprenez à modifier le rapport d’aspect + des images DataBar. Suivez cet exemple complet avec le code et des conseils. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: fr +lastmod: 2026-08-03 +og_description: Créez un PNG de code‑barres en C# et découvrez comment modifier le + rapport d’aspect des codes‑barres DataBar. Ce guide vous fournit du code prêt à + l’emploi et des conseils pratiques. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Créer un PNG de code‑barres en C# – exemple complet avec contrôle du rapport + d’aspect +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Créer un PNG de code‑barres en C# – guide étape par étape +url: /fr/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un PNG de code‑barres en C# – guide étape par étape + +Si vous devez **créer un PNG de code‑barres** en C#, ce tutoriel vous montre exactement comment faire. Vous générerez un code‑barres DataBar omnidirectionnel empilé, l’enregistrerez sous forme de fichier PNG, et apprendrez **comment modifier le ratio d’aspect** pour l’adapter à différents environnements de numérisation. + +Le guide couvre tout ce dont vous avez besoin : les packages requis, un programme complet et exécutable, ainsi que des explications sur l’importance de chaque paramètre. À la fin, vous disposerez de deux fichiers PNG — l’un avec un ratio d’aspect de 15 et l’autre de 30 — prêts pour les tests ou la production. + +## Prérequis + +Avant de commencer, assurez‑vous d’avoir : + +- le SDK .NET 6.0 ou une version ultérieure installé +- Visual Studio 2022 (ou tout autre IDE C#) +- une référence NuGet à **Aspose.BarCode** (la bibliothèque qui fournit `BarcodeGenerator`) +- les droits d’écriture sur le répertoire où les fichiers PNG seront enregistrés + +Vous pouvez ajouter le package Aspose.BarCode avec la commande suivante : + +```bash +dotnet add package Aspose.BarCode +``` + +## Étape 1 : Configurer le projet et importer les espaces de noms + +Créez une nouvelle application console et importez les espaces de noms nécessaires à la génération de code‑barres et aux opérations d’E/S de fichiers. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Pourquoi c’est important :** L’importation de `Aspose.BarCode.Generation` vous donne accès à `BarcodeGenerator`. Garder le code à l’intérieur de `Main` rend l’exemple autonome et facile à exécuter. + +## Étape 2 : Créer un générateur de code‑barres pour un DataBar omnidirectionnel empilé + +Instanciez `BarcodeGenerator` avec le type `EncodeTypes.DatabarStackedOmniDirectional` et une chaîne de données GS1‑128 d’exemple. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Pourquoi c’est important :** Le type d’encodage choisi produit un DataBar à haute densité qui peut être lu par la plupart des scanners modernes. La chaîne de données suit le format de l’Identifiant d’Application GS1 (01), couramment utilisé pour les identifiants de produit. + +## Étape 3 : Définir la dimension X (largeur du module) en pixels + +Définissez la largeur du module pour contrôler la taille globale du code‑barres sans affecter sa lisibilité. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Pourquoi c’est important :** Une dimension X de 2 pixels donne un code‑barres ni trop petit pour les scanners, ni trop grand pour les espaces d’étiquetage habituels. + +## Étape 4 : Enregistrer le premier PNG avec un ratio d’aspect de 15 + +Ajustez le ratio d’aspect du DataBar, puis enregistrez l’image au format PNG. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Pourquoi c’est important :** Le ratio d’aspect contrôle la relation hauteur‑largeur du DataBar empilé. Un ratio de 15 est une valeur par défaut courante qui équilibre lisibilité et hauteur d’étiquette. + +## Étape 5 : Modifier le ratio d’aspect à 30 et enregistrer un deuxième PNG + +Modifiez la même instance du générateur pour utiliser un ratio d’aspect plus grand, puis enregistrez la seconde image. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Pourquoi c’est important :** Augmenter le ratio d’aspect étire le code‑barres verticalement, ce qui peut améliorer la fiabilité de la lecture sur des appareils à faible résolution ou lorsque l’étiquette est imprimée sur un support étroit. + +## Résultat attendu + +L’exécution du programme crée deux fichiers PNG : + +| Fichier | Ratio d’aspect | Dimensions approximatives (pixels) | +|--------------------------------------|----------------|------------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (largeur × hauteur) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (largeur × hauteur) | + +Les deux images contiennent un code‑barres DataBar clair et lisible qui encode l’identifiant GS1 `(01)12345678901231`. + +## Questions courantes et cas limites + +### Comment changer d’autres propriétés visuelles ? + +Vous pouvez ajuster la couleur de premier plan, la couleur d’arrière‑plan ou ajouter du texte lisible par l’homme via l’objet `generator.Parameters.Barcode`. Par exemple : + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Et si j’ai besoin d’un autre format d’image ? + +Remplacez `BarCodeImageFormat.Png` par `Jpeg`, `Bmp` ou `Gif` selon vos besoins. Le PNG reste le meilleur choix pour des images de code‑barres sans perte. + +### Le ratio d’aspect affecte‑il la vitesse de numérisation ? + +Des ratios d’aspect plus élevés augmentent la hauteur du code‑barres, ce qui peut améliorer la fiabilité de la lecture sur des appareils qui ont du mal avec des symboles empilés courts. Cependant, des codes‑barres très hauts peuvent ne pas tenir sur de petites étiquettes, il faut donc tester avec le matériel cible. + +### Puis‑je générer plusieurs codes‑barres dans une boucle ? + +Oui. Créez une nouvelle instance de `BarcodeGenerator` pour chaque chaîne de données ou réutilisez la même instance en mettant à jour `CodeText` et `DataBar.AspectRatio`. Cette approche réduit la surcharge d’allocation d’objets. + +## Conseils pro + +- **Réutiliser le générateur** : Modifier uniquement le `CodeText` ou le `AspectRatio` évite de réinstancier l’objet, ce qui accélère le traitement par lots. +- **Valider la sortie** : Utilisez un scanner portable ou une application mobile pour confirmer que le PNG généré se lit correctement avant de le déployer en production. +- **Nommer les fichiers** : Incluez le ratio d’aspect dans le nom du fichier (comme indiqué) pour suivre les variantes lors des tests. + +## Conclusion + +Vous savez maintenant comment **créer des PNG de code‑barres** en C# et précisément **modifier le ratio d’aspect** pour les symboles DataBar omnidirectionnels empilés. L’exemple complet montre l’initialisation, le réglage de la dimension X, la manipulation du ratio d’aspect et l’enregistrement de l’image—le tout dans un seul programme exécutable. + +À partir d’ici, vous pouvez explorer d’autres types de code‑barres, expérimenter avec les couleurs, ou intégrer le générateur dans un système de reporting ou de gestion d’inventaire plus vaste. Bonne programmation ! + +## 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 d’autres fonctionnalités de l’API et à explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Créer un PNG de code‑barres – Ratio d’aspect DataMatrix – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Comment générer un code‑barres Aztec avec un ratio d’aspect personnalisé en utilisant Aspose.BarCode pour .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Comment personnaliser le ratio d’aspect du code‑barres Codablock F avec Aspose.BarCode pour .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/french/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..bd0c7f087 --- /dev/null +++ b/barcode/french/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-08-03 +description: Créez rapidement un PNG de code-barres avec ce guide. Apprenez à générer + une image de code-barres en utilisant Aspose.BarCode et à créer un code-barres Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: fr +lastmod: 2026-08-03 +og_description: Créez un PNG de code‑barres instantanément. Ce tutoriel montre comment + générer une image de code‑barres et créer un code‑barres planétaire avec Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Créer un code‑barres PNG en Python – guide complet de programmation +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Créer un PNG de code‑barres en Python – guide étape par étape +url: /fr/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un PNG de code-barres en Python – guide étape par étape + +Si vous avez besoin de **créer des fichiers PNG de code-barres** à partir de votre application Python, ce tutoriel vous montre exactement comment faire. Nous parcourrons **comment générer une image de code-barres** en utilisant Aspose.BarCode et plus spécifiquement **générer un code-barres Planet** avec des dimensions personnalisées. + +Vous apprendrez comment installer la bibliothèque, configurer la symbologie Planet, ajuster les paramètres de taille et enregistrer le résultat sous forme de PNG de haute qualité. Le guide suppose des connaissances de base en Python et une version récente de Python 3 (3.8 ou plus récente). Aucune expérience préalable des normes de code-barres n’est requise. + +--- + +## Comment créer un PNG de code-barres avec Aspose.BarCode + +Cette section contient les étapes essentielles nécessaires pour **créer un PNG de code-barres**. Chaque étape comprend un extrait de code, une explication de son importance et des conseils pratiques que vous pouvez appliquer immédiatement. + +### 1. Installer le package Aspose.BarCode + +Aspose fournit un package pure‑Python qui encapsule son moteur .NET core. Installez‑le avec `pip` : + +```bash +pip install aspose-barcode +``` + +*Pourquoi cette étape est importante :* Le package fournit la classe `BarcodeGenerator` utilisée tout au long de l’exemple. L’installer globalement garantit que l’interpréteur peut localiser l’assembly au moment de l’exécution. + +### 2. Importer les classes requises + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Conseil :* Importez uniquement les symboles dont vous avez besoin ; cela garde l’espace de noms propre et accélère le chargement du module. + +### 3. Créer un générateur de code-barres pour la symbologie Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Pourquoi c’est important :* `EncodeTypes.Planet` indique au moteur d’utiliser la norme de code-barres Planet, tandis que le deuxième argument fournit les données à encoder. Modifier la symbologie (par ex., `EncodeTypes.Code128`) produirait un motif visuel complètement différent. + +### 4. Définir la dimension X (largeur du module) en pixels + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Explication :* La dimension X contrôle la largeur de la barre étroite. Une valeur de 4 pixels donne un code-barres modérément dense qui reste lisible sur la plupart des appareils. + +### 5. Définir une hauteur de barre manuelle en pixels + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Pourquoi vous pourriez ajuster cela :* Certains imprimantes de détail nécessitent des barres plus hautes pour un scan fiable. La hauteur par défaut est généralement de 50 px ; l’augmenter à 100 px améliore la lisibilité sans augmenter de façon spectaculaire la taille du fichier. + +### 6. Enregistrer le code-barres généré en tant qu’image PNG + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Résultat :* Un fichier PNG nommé **PlanetBarHeight100.png** apparaît dans le dossier `output`. PNG est sans perte, ce qui le rend idéal pour l’impression et l’intégration dans les pages web. + +### 7. Vérifier la sortie (optionnel) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Conseil :* Visualiser l’image confirme que les dimensions correspondent aux paramètres que vous avez définis. Si le code-barres apparaît déformé, revérifiez la dimension X ou les réglages de hauteur de barre. + +--- + +## Comment générer une image de code-barres au format PNG (paramètres alternatifs) + +Si vous avez besoin d’un format d’image différent ou souhaitez intégrer le code-barres dans un PDF ultérieurement, vous pouvez modifier l’énumération `BarCodeImageFormat` : + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Pourquoi c’est important :* PNG préserve chaque pixel, ce qui est crucial pour les codes-barres à fort contraste. JPEG introduit des artefacts de compression qui peuvent gêner le scan, tandis que BMP offre une compatibilité avec les outils plus anciens. + +## Générer un code-barres Planet avec des couleurs personnalisées (avancé) + +Au-delà de la taille, vous pouvez personnaliser les couleurs de premier plan et d’arrière‑plan : + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Conseil pratique :* Les paires de couleurs à fort contraste (sombre sur clair) maximisent la fiabilité du scanner. Évitez d’utiliser des teintes similaires pour le premier plan et l’arrière‑plan. + +## Pièges courants et comment les éviter + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Le code-barres ne se lit pas | Dimension X trop petite (≤ 2 px) | Augmenter `x_dimension.pixels` à au moins 3 px | +| L’image apparaît floue | PNG enregistré à faible DPI | Utiliser `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` pour spécifier 300 DPI (si supporté) | +| Exception `ImportError` | Aspose.BarCode non installé | Exécuter `pip install aspose-barcode` dans le même environnement que votre script | +| Symbologie incorrecte | Utilisé `EncodeTypes.Code128` au lieu de `EncodeTypes.Planet` | Remplacer par `EncodeTypes.Planet` lors de la création du générateur | + +## Récapitulatif de la solution complète + +Voici le script complet et exécutable qui **crée un PNG de code-barres** du début à la fin : + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +L’exécution de ce script produit un **PNG de code-barres Planet** net que vous pouvez intégrer dans du HTML, joindre à des e‑mails ou imprimer sur des étiquettes de produit. + +## Prochaines étapes et sujets associés + +* **Intégrer avec Flask ou Django** – servir le PNG généré directement depuis un point de terminaison web. +* **Génération par lots** – parcourir une liste d’identifiants de produit pour créer un dossier de fichiers PNG de code-barres. +* **Combiner avec la génération de PDF** – utiliser `aspose-pdf` pour placer le PNG dans une facture ou une étiquette d’expédition. +* **Explorer d’autres symbologies** – remplacer `EncodeTypes.Planet` par `EncodeTypes.QR`, `EncodeTypes.DataMatrix` ou `EncodeTypes.Code128` pour répondre à différents besoins métier. + +En maîtrisant les étapes ci‑dessus, vous savez maintenant **comment générer une image de code-barres** de façon programmatique et pouvez étendre le modèle à toute norme de code-barres prise en charge par Aspose.BarCode. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/french/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..7afe35711 --- /dev/null +++ b/barcode/french/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-08-03 +description: Créez rapidement une image de code‑barres postal en C#. Apprenez à générer + un code‑barres postal, à définir les dimensions du code‑barres et à générer un code‑barres + Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: fr +lastmod: 2026-08-03 +og_description: Créez une image de code-barres postal en C# avec ce tutoriel complet ; + apprenez à définir les dimensions du code-barres, à générer un code-barres Planet + et à produire des codes-barres RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Créer une image de code‑barres postal en C# – guide complet de programmation +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Créer une image de code‑barres postal en C# – guide étape par étape +url: /fr/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer une image de code-barres postal en C# – guide étape par étape + +Si vous devez **créer une image de code-barres postal** en C#, ce guide vous montre exactement comment faire. Nous couvrirons **comment générer un code-barres postal**, **comment définir les dimensions du code-barres**, et comment **générer un code-barres Planet** pour les normes postales courantes. + +Vous terminerez avec deux fichiers PNG prêts à l’emploi — un code-barres Planet et un code-barres RM4SCC — chacun de 100 px de hauteur. Aucun outil supplémentaire n’est requis au-delà de la bibliothèque Aspose.BarCode pour .NET. + +## Prérequis + +* SDK .NET 6 ou ultérieur (le code fonctionne également avec .NET Framework 4.7+) +* Visual Studio 2022 ou tout IDE C# +* Package NuGet **Aspose.BarCode** (la bibliothèque qui fournit `BarcodeGenerator`) + +## Étape 1 : Installer la bibliothèque de codes-barres + +Ouvrez un terminal dans le dossier de votre projet et exécutez : + +```bash +dotnet add package Aspose.BarCode +``` + +Le package ajoute l’espace de noms `Aspose.BarCode`, qui contient `BarcodeGenerator` et l’énumération `EncodeTypes` nécessaires aux codes-barres postaux. + +## Étape 2 : Définir le dossier de sortie + +Créer un chemin de sortie fiable évite les erreurs d’exécution lorsque le dossier n’existe pas. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Pourquoi c’est important* : `Directory.CreateDirectory` est idempotent — il crée le dossier uniquement s’il n’est pas déjà présent, évitant ainsi les exceptions lors des exécutions suivantes. + +## Étape 3 : Configurer les dimensions communes du code-barres + +Définir la dimension X (largeur d’une barre unique) et la hauteur totale de la barre vous permet de contrôler la taille visuelle de l’image générée. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Comment définir les dimensions du code-barres** : la propriété `Parameters.Barcode.XDimension.Pixels` définit la largeur de la barre étroite, tandis que `Parameters.Barcode.BarHeight.Pixels` définit la hauteur totale. Ajustez ces valeurs pour répondre aux spécifications de votre service postal. + +## Étape 4 : Générer un code-barres Planet + +Planet est un code-barres postal largement utilisé au Royaume-Uni. Le code suivant crée un code-barres Planet de 100 px de hauteur et l’enregistre au format PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Pourquoi cela fonctionne** : `EncodeTypes.Planet` indique au générateur d’utiliser la symbologie Planet. La méthode `Save` écrit un fichier PNG au chemin spécifié, en conservant les dimensions que nous avons définies précédemment. + +## Étape 5 : Générer un code-barres RM4SCC + +RM4SCC est la norme néerlandaise de code-barres postal. Le code ci‑dessous reproduit l’exemple Planet, démontrant **comment générer un code-barres postal** d’un type différent avec des dimensions identiques. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Les deux fichiers PNG se trouvent maintenant dans le dossier `Barcodes`. Les ouvrir affichera des codes-barres nets de 100 px de hauteur, prêts à être imprimés ou intégrés dans des documents. + +## Code source complet + +Voici le programme complet et exécutable qui **crée des fichiers d’image de code-barres postal** pour les normes Planet et RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Résultat attendu + +L’exécution du programme affiche les chemins des fichiers et crée deux fichiers PNG : + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Chaque image mesure 100 px de hauteur, avec une largeur de barre étroite de 4 pixels, correspondant aux dimensions que nous avons définies. + +## Conseils pratiques et pièges courants + +* **Permissions du dossier** – Si le programme s’exécute sous un compte restreint, assurez‑vous que le dossier cible est accessible en écriture. +* **Dimensions différentes** – Pour créer un code‑barres plus haut, augmentez `barHeightPixels`. Pour une résolution plus fine, réduisez `xDimensionPixels`, mais gardez‑la ≥ 2 pour éviter les artefacts de rendu. +* **Autres symbologies postales** – Aspose.BarCode prend également en charge `EncodeTypes.Postnet` et `EncodeTypes.AustralianPost`. Changez la valeur de `EncodeTypes` et conservez la même logique de dimensions. +* **Format d’image** – Utilisez `BarCodeImageFormat.Jpeg` pour une taille de fichier plus petite lorsque la qualité sans perte n’est pas requise. + +## Conclusion + +Vous savez maintenant comment **créer des fichiers d’image de code‑barres postal** en C# en configurant les dimensions, en sélectionnant la symbologie appropriée et en enregistrant le résultat au format PNG. Le tutoriel a couvert **comment générer un code‑barres postal**, a démontré **la génération d’un code‑barres Planet**, et a expliqué **comment définir les dimensions du code‑barres** pour un rendu cohérent. + +Ensuite, explorez **la personnalisation des couleurs du code‑barres**, l’ajout de **texte lisible par l’homme**, ou l’intégration des images dans des factures PDF. Le même modèle s’applique à tout autre type de code‑barres pris en charge par Aspose.BarCode, vous permettant d’étendre cette solution à un flux complet d’automatisation postale. + +## 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. + +- [Comment générer un code‑barres – Types de code‑barres unidimensionnels](/barcode/english/net/one-dimensional-barcode-types/) +- [Comment générer un code‑barres Aztec avec un rapport d’aspect personnalisé en utilisant Aspose.BarCode pour .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Comment générer un code‑barres java – Code‑barres Australia Post avec Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/french/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..d29adbf3a --- /dev/null +++ b/barcode/french/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-08-03 +description: Comment enregistrer un code‑barres en C# avec un exemple de générateur + de code‑barres étape par étape. Apprenez à générer des codes‑barres Planet, à définir + les dimensions et à exporter des images PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: fr +lastmod: 2026-08-03 +og_description: Comment enregistrer un code‑barres en C# à l'aide d'un exemple de + générateur de code‑barres. Ce tutoriel montre comment générer des codes‑barres Planet, + configurer la dimension X et exporter des fichiers PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Comment enregistrer un code‑barres en C# – guide étape par étape +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Comment enregistrer un code‑barres en C# – guide complet du générateur de codes‑barres +url: /fr/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment enregistrer un code-barres en C# – guide complet du générateur de code-barres + +Enregistrer des images de code-barres en C# est une exigence courante lorsque vous devez intégrer des codes-barres postaux dans des factures, des étiquettes d'expédition ou des étiquettes d'inventaire. Ce guide vous fait parcourir un flux de travail pratique de **c# barcode generator**, de la création d'un code-barres Planet à l'exportation de fichiers PNG avec barres remplies et barres vides. + +Vous apprendrez à définir la largeur des barres, à activer/désactiver les barres remplies et à gérer les dossiers de sortie de manière fiable. À la fin du tutoriel, vous disposerez d'un **barcode generator example** entièrement fonctionnel que vous pourrez copier dans n'importe quel projet .NET. + +## Ce dont vous avez besoin + +- .NET 6.0 SDK ou version ultérieure (l'exemple fonctionne avec .NET Core et .NET Framework) +- Visual Studio 2022 ou tout IDE compatible C# +- Le package NuGet **Aspose.BarCode** (ou une autre bibliothèque qui prend en charge `EncodeTypes.Planet`). Installez-le avec : + +```bash +dotnet add package Aspose.BarCode +``` + +La bibliothèque fournit la classe `BarcodeGenerator` utilisée tout au long de ce tutoriel. + +## Configuration de l'environnement de développement + +Créez un nouveau projet console et ajoutez l'espace de noms requis : + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +L'espace de noms `System.IO` nous fournit `Directory.CreateDirectory`, qui garantit que le dossier de sortie existe avant que nous essayions d'écrire des fichiers. + +## Comment enregistrer des images de code-barres avec le générateur de code-barres C# + +Le cœur de la solution est un petit ensemble d'étapes qui configurent un **code-barres Planet** puis enregistrent l'image sur le disque. Les sections suivantes décomposent le processus en morceaux gérables. + +### Étape 1 : Définir le dossier de sortie + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Pourquoi ?** +Coder en dur un chemin peut provoquer une `DirectoryNotFoundException` sur les machines où le dossier n'existe pas. `CreateDirectory` est idempotent — il crée le répertoire uniquement s'il manque, rendant le code sûr pour des exécutions répétées. + +### Étape 2 : Créer un générateur de code-barres Planet (barres remplies) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Pourquoi ?** +`EncodeTypes.Planet` indique à la bibliothèque de produire un code-barres postal Planet, largement utilisé par les services postaux. La chaîne `"123456"` est la charge utile d'exemple ; remplacez‑la par toute donnée numérique requise par votre logique métier. + +### Étape 3 : Configurer la largeur des barres (dimension X) et conserver les barres remplies par défaut + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Pourquoi ?** +La dimension X contrôle la largeur physique de chaque barre. Une valeur de `4` pixels donne un code-barres lisible sur les imprimantes standard 300 dpi. Laisser `FilledBars` à `true` (la valeur par défaut) produit l'apparence classique des barres pleines. + +### Étape 4 : Enregistrer l'image du code-barres à barres remplies + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Pourquoi ?** +Enregistrer au format PNG préserve une qualité d'image sans perte, ce qui est important pour la précision du scan. La méthode `Save` crée automatiquement le fichier image ; vous devez uniquement fournir le chemin complet et le format souhaité. + +### Étape 5 : Créer un second générateur pour la version à barres vides + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Créer une nouvelle instance garantit que les modifications apportées pour la version à barres vides n'affectent pas l'image à barres remplies déjà enregistrée. + +### Étape 6 : Désactiver les barres remplies tout en conservant la même dimension X + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Pourquoi ?** +Définir `FilledBars = false` rend le code-barres avec uniquement le contour de chaque barre, ce que certaines normes postales exigent pour la vérification visuelle. + +### Étape 7 : Enregistrer l'image du code-barres à barres vides + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Vous avez maintenant deux fichiers PNG — l'un avec des barres remplies et l'autre avec des barres vides — prêts à être inclus dans des PDF, des e‑mails HTML ou des étiquettes imprimées. + +## Programme complet exécutable + +Voici le code complet que vous pouvez copier dans `Program.cs`. Il compile et s'exécute sans modification (en supposant que le package Aspose.BarCode est installé). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Sortie attendue + +L'exécution du programme affiche deux lignes similaires à : + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Ouvrez le dossier `Barcodes` et vous verrez les deux fichiers PNG. Les deux images peuvent être ouvertes avec n'importe quel visualiseur d'images ou intégrées directement dans des documents. + +![exemple d'enregistrement de code-barres](barcode-example.png){: .align-center alt="exemple d'enregistrement de code-barres"} + +## Variantes courantes et cas limites + +| Scénario | Ajustement | +|----------|------------| +| **Format d'image différent** | Change `BarCodeImageFormat.Png` to `Jpeg`, `Gif`, or `Bmp` as needed. | +| **Taille de sortie personnalisée** | Use `filled.Parameters.Image.Width` and `Height` to force a specific pixel dimension. | +| **Données dynamiques** | Replace the static `"123456"` with a variable that holds order numbers, tracking IDs, etc. | +| **Dossier inexistant** | `Directory.CreateDirectory` already handles missing directories; no extra code required. | +| **Impression haute résolution** | Increase `XDimension.Pixels` to 6–8 for 600 dpi printers, but verify scanner compatibility. | + +**Astuce :** Si vous devez générer de nombreux codes-barres dans une boucle, réutilisez une seule instance `BarcodeGenerator` et ne changez que la propriété `CodeText` avant chaque `Save`. Cela réduit la surcharge d'allocation d'objets. + +## Comment générer un code-barres pour d'autres normes + +Le même schéma fonctionne pour d'autres `EncodeTypes` tels que `Code128`, `QR` ou `DataMatrix`. Remplacez simplement `EncodeTypes.Planet` par le type souhaité et ajustez les paramètres spécifiques au type (par ex., `QRCodeVersion` + +## 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 enregistrer un PNG en utilisant DataMatrix C40 avec Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Comment générer des codes-barres DataMatrix (ECC 200) avec Aspose.BarCode pour .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Comment générer un code-barres – Configuration Code 39 avec Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/german/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..51662a32f --- /dev/null +++ b/barcode/german/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-08-03 +description: Barcode‑Generator‑C#‑Tutorial, das zeigt, wie man einen Planet‑Barcode + mit Aspose.BarCode erstellt, die X‑Dimension festlegt und als PNG‑Bilder speichert. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: de +lastmod: 2026-08-03 +og_description: Das Barcode‑Generator‑C#‑Tutorial führt Sie durch das Erstellen eines + Planet‑Barcodes, das Anpassen der X‑Dimension und das Speichern als PNG mit Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Barcode‑Generator C# – Planet‑Barcode Schritt für Schritt erstellen +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Barcode-Generator C# – Beispiel zur Erstellung von Planet-Barcode und RM4SCC +url: /de/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode‑Generator C# – Planet‑Barcode und RM4SCC‑Beispiel erstellen + +Wenn Sie einen **barcode generator C#** benötigen, der post‑spezifische Symbole erzeugen kann, zeigt Ihnen dieser Leitfaden genau, wie Sie **Planet‑Barcode**‑Bilder mit Aspose.BarCode erstellen. Sie sehen, wie Sie die X‑Dimension konfigurieren, einen passenden RM4SCC‑Barcode generieren und beide als PNG‑Dateien speichern – alles in wenigen prägnanten Schritten. + +Das Tutorial behandelt alles, was Sie benötigen, um den Code unter .NET 6 oder höher auszuführen, erklärt, warum jede Einstellung wichtig ist, und weist auf häufige Stolperfallen wie falsche Modulbreite oder fehlende Ordnerberechtigungen hin. Am Ende haben Sie zwei druckfertige Barcode‑Bilder, die den Planet‑ und RM4SCC‑Standards entsprechen. + +## Voraussetzungen + +Bevor Sie beginnen, stellen Sie sicher, dass Sie Folgendes haben: + +* .NET 6 SDK (oder jede .NET‑Version, die von Aspose.BarCode unterstützt wird) +* Visual Studio 2022 oder eine beliebige C#‑IDE Ihrer Wahl +* Einen NuGet‑Verweis auf **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Schreibrechte für den Ordner, in dem Sie die PNG‑Dateien speichern möchten + +Zusätzliche externe Dienste sind nicht erforderlich; die Bibliothek erledigt die gesamte Codierung lokal. + +## Schritt 1: Initialisieren des barcode generator C#‑Objekts + +Die erste Aufgabe besteht darin, eine Instanz von `BarcodeGenerator` zu erstellen. Der Konstruktor nimmt die Barcode‑Symbologie (`EncodeTypes.Planet`) und die zu codierenden Daten entgegen. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Warum dieser Schritt?* +`BarcodeGenerator` ist der Einstiegspunkt für jeden Barcode, den Sie erzeugen. Die Auswahl von `EncodeTypes.Planet` weist die Bibliothek an, die ISO/IEC 24723‑Spezifikation zu verwenden, die von vielen Postdiensten genutzt wird. + +## Schritt 2: X‑Dimension (Modulbreite) für den Planet‑Barcode festlegen + +Die X‑Dimension definiert die Breite eines einzelnen Barcode‑Moduls (der kleinste Strich oder Abstand). Ein Wert von **4 Pixeln** funktioniert für die meisten Etikettendrucker gut. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Warum das wichtig ist* +Ist das Modul zu schmal, kann der Barcode unlesbar werden; ist es zu breit, wächst die Etikettengröße unnötig. Durch Anpassen von `Pixels` können Sie den Barcode exakt an die Auflösung Ihres Druckers anpassen. + +## Schritt 3: Planet‑Barcode als PNG‑Bild speichern + +Aspose.BarCode berechnet die Barcode‑Höhe automatisch basierend auf der gewählten Symbologie, sodass Sie nur den Dateipfad und das Format angeben müssen. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Hinweis* +Ersetzen Sie `YOUR_DIRECTORY` durch einen absoluten oder relativen Pfad, der auf Ihrem Rechner existiert. Existiert das Verzeichnis nicht, wirft die `Save`‑Methode eine `DirectoryNotFoundException`. + +**Erwartete Ausgabe** – eine PNG‑Datei, die der unten dargestellten Abbildung ähnelt (das eigentliche Bild wird hier nicht angezeigt, Sie sehen jedoch einen klassischen Planet‑Barcode mit dem numerischen Payload `123456`). + +## Schritt 4: Zweiten Generator für den RM4SCC‑Barcode initialisieren + +Viele Postsysteme verlangen sowohl Planet‑ als auch RM4SCC‑Symbole auf demselben Sendungsstück. Erstellen Sie eine neue `BarcodeGenerator`‑Instanz für die RM4SCC‑Symbologie. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Warum eine separate Instanz?* +Jede Symbologie hat ihre eigenen Parameter. Die Wiederverwendung desselben Generators könnte unbeabsichtigt Einstellungen (wie die X‑Dimension) übernehmen, die für den zweiten Barcode nicht optimal sind. + +## Schritt 5: X‑Dimension für den RM4SCC‑Barcode konfigurieren + +RM4SCC respektiert ebenfalls die X‑Dimension‑Einstellung, sodass wir dieselbe Pixel‑Breite für visuelle Konsistenz verwenden. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro‑Tipp* +Falls Sie einen höheren Barcode benötigen (z. B. für größere Etiketten), können Sie zusätzlich `Height.Pixels` setzen. Bleibt diese Einstellung leer, berechnet die Bibliothek die ideale Höhe automatisch. + +## Schritt 6: RM4SCC‑Barcode als PNG‑Bild speichern + +Abschließend speichern wir den RM4SCC‑Barcode auf dem Datenträger. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Sie haben nun zwei PNG‑Dateien – `PostalPlanetBarHeightNone.png` und `PostalRM4SCCBarHeightNone.png` – die Sie in Versandetiketten einbetten, auf Umschlägen drucken oder an einen Dritt‑Druckservice senden können. + +## Optional: Höhe anpassen oder andere Bildformate verwenden + +Falls Ihr Workflow eine bestimmte Barcode‑Höhe oder ein anderes Bildformat (z. B. JPEG oder BMP) erfordert, können Sie die Parameter vor dem Aufruf von `Save` ändern: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Randfall** – Wenn Sie eine benutzerdefinierte Höhe festlegen, stellen Sie sicher, dass der Wert die vom ISO‑Standard geforderte Mindesthöhe einhält; andernfalls könnte der Barcode die Validierung nicht bestehen. + +## Häufige Stolperfallen und wie man sie vermeidet + +| Stolperfalle | Warum es passiert | Lösung | +|--------------|-------------------|--------| +| `DirectoryNotFoundException` | Der Zielordner existiert nicht oder ist falsch geschrieben. | Ordner zuerst erstellen oder `Path.Combine` mit `Environment.CurrentDirectory` verwenden. | +| Barcode auf Niedrigauflösungs‑Druckern unlesbar | X‑Dimension zu klein für die DPI des Druckers. | `XDimension.Pixels` auf 5 – 6 für 203 dpi‑Drucker erhöhen oder mit einem Testetikett prüfen. | +| Falsche Symbologie verwendet | `EncodeTypes.Code128` anstelle von `EncodeTypes.Planet` übergeben. | Sicherstellen, dass der `EncodeTypes`‑Enum‑Wert dem benötigten Poststandard entspricht. | +| Null‑Referenz bei `Parameters` | Verwendung einer älteren Aspose.BarCode‑Version, bei der die API abweicht. | Auf das neueste NuGet‑Paket (v23.12 oder später) aktualisieren. | + +## Vollständiges, ausführbares Beispiel + +Unten finden Sie das komplette Programm, das Sie kopieren, einfügen und ausführen können. Es enthält `using`‑Anweisungen, Fehlerbehandlung und Kommentare, die jede Zeile erklären. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Beim Ausführen des Programms wird ein Ordner `Barcodes` neben der ausführbaren Datei erstellt und die beiden PNG‑Dateien dort abgelegt. Öffnen Sie sie mit einem Bildbetrachter, um das Ergebnis zu prüfen. + +## Fazit + +Sie verfügen nun über eine **barcode generator C#**‑Lösung, die **Planet‑Barcode**‑Bilder erzeugen, die X‑Dimension für optimalen Druck anpassen und einen passenden RM4SCC‑Barcode erzeugen kann – alles mit wenigen Code‑Zeilen. Der Ansatz funktioniert mit .NET 6+, erfordert nur das Aspose.BarCode‑NuGet‑Paket und lässt sich leicht auf andere Symbologien wie Code128, QR oder DataMatrix erweitern, indem Sie den `EncodeTypes`‑Wert austauschen. + +### Was kommt als Nächstes? + +* Experimentieren Sie mit verschiedenen `XDimension.Pixels`‑Werten, um sie an die DPI Ihres Druckers anzupassen. +* Generieren Sie Barcodes in anderen Formaten (PDF, SVG), indem Sie das `BarCodeImageFormat`‑Enum ändern. +* Kombinieren Sie die beiden PNG‑Dateien zu einem einzigen Etikett mithilfe einer Grafikbibliothek wie **SkiaSharp**. +* Erkunden Sie die komplette Aspose.BarCode‑API für erweiterte Funktionen wie Prüfsummen‑Validierung oder benutzerdefinierte Schriftarten. + +Passen Sie den Code gern für Batch‑Verarbeitung an oder integrieren Sie ihn in einen ASP.NET Core‑Webservice, der Barcode‑Bilder auf Abruf liefert. 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, damit Sie weitere API‑Funktionen meistern und alternative Implementierungsansätze in Ihren Projekten erkunden können. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/german/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..6a95368a6 --- /dev/null +++ b/barcode/german/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-08-03 +description: Das Barcode‑Generator‑C#‑Tutorial zeigt, wie man ein Barcode‑Bild mit + Aspose.BarCode erzeugt, Spalten und Zeilen festlegt und PNG‑Dateien für DataBar Expanded Stacked + speichert. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: de +lastmod: 2026-08-03 +og_description: Das Barcode‑Generator‑C#‑Tutorial erklärt, wie man mit Aspose.BarCode + ein Barcode‑Bild erzeugt, DataBar Expanded Stacked‑Spalten und‑Zeilen konfiguriert + und PNG‑Dateien speichert. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Barcode-Generator C# – Schritt‑für‑Schritt‑Anleitung zur Erstellung eines + Barcode‑Bildes +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Barcode‑Generator C# – Barcode‑Bild erzeugen +url: /de/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode-Generator C# – Barcode-Bild generieren + +Wenn Sie einen Barcode-Generator C# benötigen, der Barcode-Bilder für DataBar Expanded Stacked erzeugen kann, führt Sie dieser Leitfaden durch den gesamten Prozess. Sie lernen, wie Sie Spalten- und Zeileneinstellungen konfigurieren, das Ergebnis als PNG speichern und den Code für andere Symbologien anpassen. + +Das programmgesteuerte Erzeugen von Barcode-Bildern eliminiert manuelle Schritte und sorgt für Konsistenz bei Rechnungen, Versandetiketten und Inventursystemen. Dieses Tutorial deckt alles ab, was Sie benötigen, von der Projektkonfiguration bis zum vollständigen Quellcode, sodass Sie das Beispiel sofort ausführen können. + +## Voraussetzungen + +* .NET 6.0 oder höher installiert +* Eine IDE wie Visual Studio 2022 (jeder Editor, der C# unterstützt, funktioniert) +* Eine Lizenz für **Aspose.BarCode for .NET** – die kostenlose Evaluation ist zum Testen geeignet +* Grundlegende Kenntnisse der C#-Syntax + +Falls einer dieser Punkte fehlt, installieren Sie das .NET SDK von dotnet.microsoft.com und holen Sie das Aspose.BarCode NuGet-Paket mit: + +```bash +dotnet add package Aspose.BarCode +``` + +## Schritt 1: Ein Barcode-Generator C#‑Projekt erstellen + +Erstellen Sie eine neue Konsolenanwendung und fügen Sie die erforderlichen `using`‑Direktiven hinzu: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +Die Klasse `BarcodeGenerator` ist das Kernstück der Barcode‑Generator C#‑API. Sie erhält den Symbologie‑Typ und den zu kodierenden Text. + +## Schritt 2: Einen DataBar Expanded Stacked‑Barcode erzeugen und Spalten festlegen + +Das erste Beispiel erzeugt einen Barcode mit vier Spalten. Das Anpassen der Eigenschaft `Columns` ändert die visuelle Dichte der DataBar Expanded Stacked‑Symbologie. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Warum das wichtig ist:** Die Spaltenanzahl beeinflusst die Menge der Daten, die in einem kompakten Raum gespeichert werden können. Wird sie auf 4 gesetzt, entsteht ein breiterer Barcode, der von den meisten Scannern lesbar bleibt. + +## Schritt 3: Einen Barcode mit benutzerdefinierter Zeilenanzahl erzeugen + +Das zweite Beispiel zeigt, wie Sie das vertikale Layout durch Setzen der Eigenschaft `Rows` steuern können. Eine Konfiguration mit drei Zeilen ist nützlich, wenn Sie einen höheren Barcode für begrenzten horizontalen Raum benötigen. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Warum das wichtig ist:** Das Anpassen der Zeilen ermöglicht es, den Barcode in eine schmale Spalte zu passen und dabei die Lesbarkeit zu erhalten. Der Barcode‑Generator C# berechnet automatisch die Modulgröße neu, um die Spezifikation zu erfüllen. + +## Schritt 4: Vollständiges, ausführbares Beispiel + +Unten finden Sie ein eigenständiges Programm, das die vorherigen Schritte kombiniert. Kopieren Sie den Code in `Program.cs`, ersetzen Sie `YOUR_DIRECTORY` durch einen vorhandenen Ordnerpfad und führen Sie die Anwendung aus. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Erwartete Ausgabe + +Wenn Sie das Programm ausführen, erscheinen zwei PNG‑Dateien im Zielverzeichnis: + +* **DatabarCols4.png** – ein DataBar Expanded Stacked‑Barcode mit vier Spalten +* **DatabarRows3.png** – dieselben Daten, kodiert in drei Zeilen + +Öffnen Sie die Bilder mit einem beliebigen Bildbetrachter; sie zeigen scharfe, scanbare Barcodes, die zum Drucken oder Einbetten in PDFs bereitstehen. + +## Wie man ein Barcode‑Bild mit benutzerdefinierten Abmessungen erzeugt + +Wenn Sie eine bestimmte Bildgröße benötigen, passen Sie die Eigenschaften `ImageHeight` und `ImageWidth` vor dem Aufruf von `Save` an: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Das Ändern der Abmessungen beeinflusst nicht die kodierten Daten; es skaliert lediglich die visuelle Darstellung. Diese Technik ist nützlich, wenn Barcodes in UI‑Komponenten mit festen Layout‑Beschränkungen integriert werden. + +## Häufige Fallstricke und Profi‑Tipps + +* **Pfadtrennzeichen:** Verwenden Sie unverarbeitete Zeichenketten (`@"C:\Path\file.png"`) oder `Path.Combine`, um Escape‑Zeichen‑Probleme unter Windows zu vermeiden. +* **Lizenzdurchsetzung:** Ohne eine gültige Lizenz enthalten die erzeugten Bilder ein Wasserzeichen. Wenden Sie Ihre Lizenz frühzeitig in der Anwendung an: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Kodierungsgrenzen:** DataBar Expanded Stacked unterstützt bis zu 74 numerische Zeichen. Das Überschreiten dieses Limits löst eine Ausnahme aus. Validieren Sie die Eingabelänge, bevor Sie den Generator erstellen. +* **Performance:** Die Wiederverwendung einer einzelnen `BarcodeGenerator`‑Instanz für mehrere Saves reduziert die Speicherzuweisung. Ändern Sie die Eigenschaften `Rows` oder `Columns` zwischen den Saves nur, wenn der zu kodierende Text gleich bleibt. + +## Nächste Schritte + +Da Sie nun Barcode‑Bilder mit dem Barcode‑Generator C# erzeugen können, sollten Sie Folgendes erkunden: + +* **Verschiedene Symbologien** – probieren Sie `EncodeTypes.QR`, `EncodeTypes.Code128` oder `EncodeTypes.Pdf417`. +* **Farb-Anpassung** – setzen Sie `Parameters.Barcode.ForeColor` und `BackColor`, um das Branding anzupassen. +* **Einbetten in PDFs** – kombinieren Sie das erzeugte PNG mit Aspose.PDF, um druckbare Dokumente zu erstellen. + +Diese Erweiterungen ermöglichen es Ihnen, eine vollwertige Barcode‑Lösung für Inventar-, Logistik- oder Einzelhandelsanwendungen zu erstellen. + +--- + +## 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 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 DataMatrix‑Barcodes (ECC 200) mit Aspose.BarCode für .NET erzeugt](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/german/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..5d4a811d0 --- /dev/null +++ b/barcode/german/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-08-03 +description: Barcode‑Generator‑Beispiel in C#, das zeigt, wie man die Breite festlegt, + die Höhe ändert und ein Barcode‑Bild erzeugt. Befolgen Sie die Schritt‑für‑Schritt‑Anleitung. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: de +lastmod: 2026-08-03 +og_description: Das Barcode‑Generator‑Beispiel zeigt, wie man die X‑Dimension‑Breite + einstellt, die Balkenhöhe ändert und ein Barcode‑Bild in C# erzeugt. Folgen Sie + den Schritten, um PNG‑Dateien zu erstellen. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Barcode-Generator-Beispiel – C#‑Leitfaden für Breite und Höhe +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Barcode-Generator-Beispiel in C# – Breite und Höhe festlegen +url: /de/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode-Generator-Beispiel in C# – Breite und Höhe festlegen + +Wenn Sie ein **Barcode-Generator-Beispiel** in C# benötigen, zeigt Ihnen dieser Leitfaden, wie Sie die X‑Dimension‑Breite festlegen, die Balkenhöhe ändern und eine Barcode‑Bilddatei erzeugen. Sie sehen ein vollständiges, ausführbares Programm, das zwei PNG‑Dateien mit unterschiedlichen Höhen erzeugt. + +Ein typisches Szenario ist das Erstellen von Produktetiketten, bei denen die Barcode‑Größe den Scanner‑Spezifikationen entsprechen muss. Am Ende dieses Tutorials können Sie Breiten‑ und Höhenparameter programmgesteuert anpassen und das Ergebnis als PNG‑Bild speichern. + +## Voraussetzungen + +* .NET 6 (oder neuer) installiert – der Code zielt auf das .NET 6 SDK ab. +* Eine Barcode‑Bibliothek, die `EncodeTypes.DatabarOmniDirectional` unterstützt. Das Beispiel verwendet **Aspose.BarCode for .NET**, aber jede Bibliothek, die ähnliche Eigenschaften bereitstellt, funktioniert genauso. +* Eine IDE oder ein Editor (Visual Studio, VS Code, Rider), um das Programm zu kompilieren und auszuführen. +* Schreibberechtigung für ein Verzeichnis, in dem die PNG‑Dateien gespeichert werden. + +> **Pro Tipp:** Erstellen Sie einen Ordner namens `Barcodes` im Stammverzeichnis Ihres Projekts und referenzieren Sie ihn mit `Path.Combine`, um das Hard‑Coding von absoluten Pfaden zu vermeiden. + +## Barcode-Generator-Beispiel: Initialisieren und Konfigurieren + +Der erste Schritt besteht darin, eine `BarcodeGenerator`‑Instanz mit der gewünschten Symbolik und Datenzeichenfolge zu erstellen. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +Das Enum `EncodeTypes.DatabarOmniDirectional` wählt die Databar Omni‑directional‑Symbolik aus, und die GS1‑formatierte Datenzeichenfolge `(01)12345678901231` stellt einen typischen GTIN‑14‑Wert dar. Das einmalige Initialisieren des Generators ermöglicht die Wiederverwendung desselben Objekts für mehrere Bilder. + +## Wie man die Breite (X‑Dimension) festlegt + +Die X‑Dimension steuert die Modulbreite des Barcodes. Wird sie auf 2 Pixel gesetzt, ist jeder schmale Balken 2 Pixel breit, was eine gängige Anforderung für Hoch‑Druck‑Dichte ist. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Warum das wichtig ist: Ist die Breite zu klein, können Scanner einzelne Balken nicht auflösen; ist sie zu groß, kann der Barcode den Etikettenplatz überschreiten. Passen Sie den Pixelwert an die DPI des Druckers und die gewünschte Etikettengröße an. + +## Wie man die Höhe ändert + +Die Balkenhöhe bestimmt, wie hoch die Balken erscheinen. Das Beispiel erzeugt zwei Bilder: eines mit einer Höhe von 30 Pixeln und ein weiteres mit einer Höhe von 60 Pixeln. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Die Eigenschaft `BarHeight.Pixels` beeinflusst direkt die visuelle Höhe der Balken. Durch Ändern zwischen den Saves können Sie mehrere Varianten aus derselben Datenlast erzeugen, ohne den Generator neu zu erstellen. + +### Erwartete Ausgabe + +Das Ausführen des Programms erzeugt zwei PNG‑Dateien im Ordner `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – Balken sind 30 Pixel hoch. +* `DatabarBarHeight60Pixels.png` – Balken sind 60 Pixel hoch. + +Beide Bilder haben dieselbe Breite (bestimmt durch die X‑Dimension) und kodieren die identischen GTIN‑14‑Daten. + +![Zwei Barcode PNG-Dateien mit unterschiedlichen Höhen, erzeugt durch C#-Code](barcode-example.png "Barcode‑Generator‑Beispiel, das Höhenvariationen zeigt") + +*Der obige Alt‑Text des Bildes enthält das Hauptkeyword für Barrierefreiheit und SEO.* + +## Wie man ein Barcode‑Bild in C# erzeugt + +Die Methode `Save` übernimmt die Konvertierung von Barcode‑Daten in eine Bilddatei. Sie können andere Formate (JPEG, BMP, SVG) wählen, indem Sie einen anderen `BarCodeImageFormat`‑Enum‑Wert übergeben. Das Beispiel verwendet PNG, weil es verlustfreie Qualität bewahrt und weit verbreitet unterstützt wird. + +Wenn Sie den Barcode direkt in ein PDF oder eine Webseite einbetten müssen, holen Sie das Bild als `byte[]` ab: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Dieser Ansatz eliminiert die Notwendigkeit temporärer Dateien und ist nützlich für Hoch‑Durchsatz‑Dienste. + +## Häufige Variationen und Randfälle + +| Situation | Anpassung | +|-----------|------------| +| **Andere Symbolik** | Ersetzen Sie `EncodeTypes.DatabarOmniDirectional` durch einen anderen Enum‑Wert (z. B. `EncodeTypes.Code128`). | +| **Sehr kleine Etiketten** | Verringern Sie `XDimension.Pixels` auf 1 Pixel, prüfen Sie jedoch die Lesbarkeit durch den Scanner. | +| **Hochauflösender Druck** | Erhöhen Sie sowohl X‑Dimension als auch Balkenhöhe proportional (z. B. 4 px Breite, 80 px Höhe). | +| **Dynamische Daten** | Übergeben Sie die Datenzeichenfolge zur Laufzeit, eventuell aus einem Datenbankeintrag. | +| **Stapel‑Generierung** | Iterieren Sie über eine Sammlung von Datenzeichenfolgen und verwenden Sie dieselbe `BarcodeGenerator`‑Instanz erneut, während Sie `generator.Text` aktualisieren. | + +Wenn Sie auf eine Ausnahme wie `ArgumentOutOfRangeException` stoßen, überprüfen Sie, dass die Pixelwerte positive ganze Zahlen sind und das Ausgabeverzeichnis existiert. + +## Vollständiger Quellcode‑Rückblick + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Kopieren Sie den Code in ein neues Konsolenprojekt, stellen Sie das Aspose.BarCode‑NuGet‑Paket wieder her (`dotnet add package Aspose.BarCode`) und führen Sie `dotnet run` aus. Sie sehen Konsolennachrichten, die die gespeicherten Dateien bestätigen. + +## Fazit + +Dieses **barcode generator example** zeigt, wie man die Breite festlegt, die Höhe ändert und ein Barcode‑Bild in C# erzeugt. Durch Anpassen von `XDimension.Pixels` und `BarHeight.Pixels` steuern Sie die visuelle Größe des Barcodes, und die Methode `Save` schreibt das Ergebnis in PNG‑Dateien. Experimentieren Sie mit verschiedenen Symboliken, Ausgabeformaten und Datenzeichenfolgen, um die Anforderungen Ihrer Anwendung zu erfüllen. + +**Nächste Schritte** + +* Erkunden Sie **how to generate barcode** in anderen Bildformaten (SVG, JPEG) für die Web‑Nutzung. +* Lernen Sie **create barcode image c#** für ASP.NET Core‑Endpunkte, die das PNG direkt an einen Browser zurückgeben. +* Kombinieren Sie diesen Code mit einer PDF‑Generierungsbibliothek, um Barcodes in Rechnungen oder Versandetiketten einzubetten. + +Passen Sie das Beispiel gerne an, teilen Sie Ihre Ergebnisse oder stellen Sie Fragen in den Kommentaren. 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 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. + +- [Wie man Barcodes generiert – Ein‑dimensional‑Barcode‑Typen](/barcode/english/net/one-dimensional-barcode-types/) +- [Wie man den Rand für ITF‑14‑Barcode‑Anpassung festlegt](/barcode/english/net/itf-14-barcode-customization/) +- [Wie man DataMatrix‑Barcodes (ECC 200) mit Aspose.BarCode für .NET erzeugt](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/german/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..53a71d6d4 --- /dev/null +++ b/barcode/german/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-08-03 +description: Erstelle ein Barcode‑PNG in C# und lerne, wie man das Seitenverhältnis + von DataBar‑Bildern ändert. Folge diesem vollständigen Beispiel mit Code und Tipps. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: de +lastmod: 2026-08-03 +og_description: Erstelle Barcode‑PNG in C# und erfahre, wie du das Seitenverhältnis + für DataBar‑Barcodes ändern kannst. Dieser Leitfaden liefert sofort einsatzbereiten + Code und praktische Tipps. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Barcode-PNG in C# erstellen – vollständiges Beispiel mit Seitenverhältnis‑Steuerung +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Barcode-PNG in C# erstellen – Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode-PNG in C# erstellen – Schritt‑für‑Schritt‑Anleitung + +Wenn Sie **Barcode-PNG** in C# **erstellen** müssen, zeigt Ihnen dieses Tutorial genau, wie es geht. Sie generieren einen gestapelten omnidirektionalen DataBar‑Barcode, speichern ihn als PNG‑Datei und lernen **wie man das Seitenverhältnis ändert**, um unterschiedliche Scan‑Umgebungen zu berücksichtigen. + +Der Leitfaden deckt alles ab, was Sie benötigen: erforderliche Pakete, ein vollständiges, ausführbares Programm und Erklärungen, warum jede Einstellung wichtig ist. Am Ende haben Sie zwei PNG‑Dateien – eine mit einem Seitenverhältnis von 15 und eine mit 30 – bereit für Tests oder den Produktionseinsatz. + +## Voraussetzungen + +Bevor Sie beginnen, stellen Sie sicher, dass Sie Folgendes haben: + +- .NET 6.0 SDK oder neuer installiert +- Visual Studio 2022 (oder eine beliebige C#‑IDE) +- Einen NuGet‑Verweis auf **Aspose.BarCode** (die Bibliothek, die `BarcodeGenerator` bereitstellt) +- Schreibrechte für das Verzeichnis, in dem die PNG‑Dateien gespeichert werden + +Sie können das Aspose.BarCode‑Paket mit folgendem Befehl hinzufügen: + +```bash +dotnet add package Aspose.BarCode +``` + +## Schritt 1: Projekt einrichten und Namespaces importieren + +Erstellen Sie eine neue Konsolenanwendung und importieren Sie die Namespaces, die für die Barcode‑Erstellung und Dateiverarbeitung benötigt werden. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Warum das wichtig ist:** Durch das Importieren von `Aspose.BarCode.Generation` erhalten Sie Zugriff auf `BarcodeGenerator`. Der Code innerhalb von `Main` macht das Beispiel eigenständig und leicht ausführbar. + +## Schritt 2: Einen Barcode‑Generator für einen gestapelten omnidirektionalen DataBar erstellen + +Instanziieren Sie `BarcodeGenerator` mit dem Typ `EncodeTypes.DatabarStackedOmniDirectional` und einem Beispiel‑GS1‑128‑Datenstring. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Warum das wichtig ist:** Der gewählte Kodierungstyp erzeugt einen hochdichten DataBar, der von den meisten modernen Scannern gelesen werden kann. Der Datenstring folgt dem GS1‑Anwendungsidentifikator (01)‑Format, das häufig für Produktkennzeichnungen verwendet wird. + +## Schritt 3: Die X‑Dimension (Modulbreite) in Pixel festlegen + +Setzen Sie die Modulbreite, um die Gesamtabmessungen des Barcodes zu steuern, ohne die Lesbarkeit zu beeinträchtigen. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Warum das wichtig ist:** Eine X‑Dimension von 2 Pixeln ergibt einen Barcode, der weder zu klein für Scanner noch zu groß für typische Etikettenflächen ist. + +## Schritt 4: Das erste PNG mit einem Seitenverhältnis von 15 speichern + +Passen Sie das DataBar‑Seitenverhältnis an und speichern Sie das Bild als PNG‑Datei. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Warum das wichtig ist:** Das Seitenverhältnis bestimmt das Höhen‑zu‑Breiten‑Verhältnis des gestapelten DataBar. Ein Verhältnis von 15 ist ein gängiger Standard, der Lesbarkeit und Etikettenhöhe ausbalanciert. + +## Schritt 5: Das Seitenverhältnis auf 30 ändern und ein zweites PNG speichern + +Ändern Sie dieselbe Generator‑Instanz, um ein größeres Seitenverhältnis zu verwenden, und speichern Sie das zweite Bild. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Warum das wichtig ist:** Ein höheres Seitenverhältnis streckt den Barcode vertikal, was die Scan‑Zuverlässigkeit auf Niedrig‑Auflösungs‑Geräten oder bei schmalen Medien verbessern kann. + +## Erwartete Ausgabe + +Das Ausführen des Programms erzeugt zwei PNG‑Dateien: + +| Datei | Seitenverhältnis | Ungefähre Abmessungen (Pixel) | +|-------------------------------------|-------------------|------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (Breite × Höhe) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (Breite × Höhe) | + +Beide Bilder enthalten einen klaren, scanbaren DataBar‑Barcode, der den GS1‑Identifikator `(01)12345678901231` codiert. + +## Häufige Fragen und Sonderfälle + +### Wie ändere ich andere visuelle Eigenschaften? + +Sie können Vordergrundfarbe, Hintergrundfarbe oder menschenlesbaren Text über das Objekt `generator.Parameters.Barcode` anpassen. Beispiel: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Was tun, wenn ich ein anderes Bildformat benötige? + +Ersetzen Sie `BarCodeImageFormat.Png` durch `Jpeg`, `Bmp` oder `Gif`, je nach Bedarf. PNG bleibt die beste Wahl für verlustfreie Barcode‑Bilder. + +### Beeinflusst das Seitenverhältnis die Scan‑Geschwindigkeit? + +Höhere Seitenverhältnisse vergrößern die Barcode‑Höhe, was die Scan‑Zuverlässigkeit auf Geräten verbessern kann, die Schwierigkeiten mit kurzen gestapelten Symbolen haben. Sehr hohe Barcodes passen jedoch möglicherweise nicht auf kleine Etiketten, daher sollten Sie mit Ihrer Ziel‑Hardware testen. + +### Kann ich mehrere Barcodes in einer Schleife erzeugen? + +Ja. Erstellen Sie für jede Datenzeichenfolge eine neue `BarcodeGenerator`‑Instanz oder verwenden Sie dieselbe Instanz erneut, indem Sie `CodeText` und `DataBar.AspectRatio` aktualisieren. Dieser Ansatz reduziert den Aufwand für Objektinstanziierungen. + +## Profi‑Tipps + +- **Generator wiederverwenden**: Nur `CodeText` oder `AspectRatio` ändern, anstatt das Objekt neu zu instanziieren – das beschleunigt die Batch‑Verarbeitung. +- **Ausgabe validieren**: Nutzen Sie einen Handscanner oder eine mobile App, um sicherzustellen, dass das erzeugte PNG korrekt gelesen wird, bevor Sie es in die Produktion geben. +- **Dateinamen**: Das Seitenverhältnis im Dateinamen (wie gezeigt) aufnehmen, um Varianten während des Testens nachzuverfolgen. + +## Fazit + +Sie wissen jetzt, wie Sie **Barcode-PNG**‑Dateien in C# **erstellen** und exakt **das Seitenverhältnis** für gestapelte omnidirektionale DataBar‑Symbole **ändern**. Das vollständige Beispiel demonstriert Initialisierung, X‑Dimension‑Einstellung, Seitenverhältnis‑Manipulation und Bildspeicherung – alles in einem einzigen, ausführbaren Programm. + +Ab hier können Sie weitere Barcode‑Typen erkunden, mit Farben experimentieren oder den Generator in ein größeres Reporting‑ oder Inventursystem integrieren. 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, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/german/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..df63aed6b --- /dev/null +++ b/barcode/german/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-08-03 +description: Erstellen Sie schnell ein Barcode‑PNG mit dieser Anleitung. Erfahren + Sie, wie Sie ein Barcode‑Bild mit Aspose.BarCode generieren und einen Planet‑Barcode + erstellen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: de +lastmod: 2026-08-03 +og_description: Erstellen Sie sofort ein Barcode-PNG. Dieses Tutorial zeigt, wie man + ein Barcode‑Bild erzeugt und einen Planet‑Barcode mit Aspose.BarCode generiert. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Barcode-PNG in Python erstellen – vollständiger Programmierleitfaden +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Barcode-PNG in Python erstellen – Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode‑PNG in Python erstellen – Schritt‑für‑Schritt‑Anleitung + +Wenn Sie **Barcode‑PNG**‑Dateien aus Ihrer Python‑Anwendung erstellen müssen, zeigt Ihnen dieses Tutorial genau, wie es geht. Wir gehen Schritt für Schritt durch **wie man ein Barcode‑Bild** mit Aspose.BarCode erzeugt und speziell **einen Planet‑Barcode** mit benutzerdefinierten Abmessungen generiert. + +Sie lernen, wie Sie die Bibliothek installieren, die Planet‑Symbologie konfigurieren, Größenparameter anpassen und das Ergebnis als hochqualitatives PNG speichern. Die Anleitung setzt Grundkenntnisse in Python und eine aktuelle Version von Python 3 (3.8 oder neuer) voraus. Vorkenntnisse zu Barcode‑Standards sind nicht erforderlich. + +--- + +## So erstellen Sie Barcode‑PNG mit Aspose.BarCode + +Dieser Abschnitt enthält die Kernschritte, die zum **Erstellen von Barcode‑PNG** erforderlich sind. Jeder Schritt beinhaltet ein Code‑Snippet, eine Erklärung, warum er wichtig ist, und praktische Tipps, die Sie sofort anwenden können. + +### 1. Installieren des Aspose.BarCode‑Pakets + +Aspose bietet ein reines Python‑Paket, das seine .NET‑Core‑Engine einbindet. Installieren Sie es mit `pip`: + +```bash +pip install aspose-barcode +``` + +*Warum dieser Schritt wichtig ist:* Das Paket stellt die Klasse `BarcodeGenerator` bereit, die im gesamten Beispiel verwendet wird. Durch die globale Installation kann der Interpreter die Assembly zur Laufzeit finden. + +### 2. Importieren der benötigten Klassen + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Tipp:* Importieren Sie nur die Symbole, die Sie benötigen; das hält den Namensraum sauber und beschleunigt das Laden des Moduls. + +### 3. Erzeugen eines Barcode‑Generators für die Planet‑Symbologie + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Warum das wichtig ist:* `EncodeTypes.Planet` weist die Engine an, den Planet‑Barcode‑Standard zu verwenden, während das zweite Argument die zu codierenden Daten liefert. Das Ändern der Symbologie (z. B. `EncodeTypes.Code128`) würde ein völlig anderes visuelles Muster erzeugen. + +### 4. Festlegen der X‑Dimension (Modulbreite) in Pixeln + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Erklärung:* Die X‑Dimension steuert die Breite des schmalen Strichs. Ein Wert von 4 Pixel ergibt einen moderat dichten Barcode, der auf den meisten Geräten noch lesbar ist. + +### 5. Definieren einer manuellen Strichhöhe in Pixeln + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Warum Sie das anpassen könnten:* Einige Einzelhandelsdrucker benötigen höhere Striche für zuverlässiges Scannen. Die Standardhöhe beträgt meist 50 px; eine Erhöhung auf 100 px verbessert die Lesbarkeit, ohne die Dateigröße dramatisch zu vergrößern. + +### 6. Speichern des erzeugten Barcodes als PNG‑Bild + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Ergebnis:* Eine PNG‑Datei namens **PlanetBarHeight100.png** erscheint im Ordner `output`. PNG ist verlustfrei und damit ideal für den Druck sowie das Einbetten in Webseiten. + +### 7. Ausgabe überprüfen (optional) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Tipp:* Das Betrachten des Bildes bestätigt, dass die Abmessungen den eingestellten Parametern entsprechen. Sieht der Barcode verzerrt aus, überprüfen Sie die X‑Dimension oder die Strichhöhe. + +--- + +## Wie man ein Barcode‑Bild im PNG‑Format erzeugt (alternative Einstellungen) + +Falls Sie ein anderes Bildformat benötigen oder den Barcode später in ein PDF einbetten wollen, können Sie das `BarCodeImageFormat`‑Enum ändern: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Warum das wichtig ist:* PNG bewahrt jedes Pixel, was für hochkontrastreiche Barcodes entscheidend ist. JPEG führt zu Kompressionsartefakten, die das Scannen beeinträchtigen können, während BMP mit älteren Tools kompatibel ist. + +--- + +## Planet‑Barcode mit benutzerdefinierten Farben erzeugen (fortgeschritten) + +Neben der Größe können Sie Vorder‑ und Hintergrundfarben anpassen: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Praktischer Tipp:* Hochkontrast‑Farbpaare (dunkel auf hell) maximieren die Zuverlässigkeit des Scanners. Vermeiden Sie ähnliche Farbtöne für Vorder‑ und Hintergrund. + +--- + +## Häufige Stolperfallen und wie man sie vermeidet + +| Symptom | Ursache | Lösung | +|---------|---------|--------| +| Barcode wird nicht gelesen | X‑Dimension zu klein (≤ 2 px) | Erhöhen Sie `x_dimension.pixels` auf mindestens 3 px | +| Bild erscheint unscharf | PNG mit niedriger DPI gespeichert | Verwenden Sie `barcode_generator.save(..., BarCodeImageFormat.Png, 300)`, um 300 DPI anzugeben (falls unterstützt) | +| Exception `ImportError` | Aspose.BarCode nicht installiert | Führen Sie `pip install aspose-barcode` in derselben Umgebung wie Ihr Skript aus | +| Falsche Symbologie | `EncodeTypes.Code128` statt `EncodeTypes.Planet` verwendet | Ersetzen Sie es durch `EncodeTypes.Planet` beim Erzeugen des Generators | + +--- + +## Zusammenfassung der kompletten Lösung + +Unten finden Sie das vollständige, ausführbare Skript, das **Barcode‑PNG** von Anfang bis Ende **erstellt**: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Durch das Ausführen dieses Skripts erhalten Sie ein klares **Planet‑Barcode‑PNG**, das Sie in HTML einbetten, an E‑Mails anhängen oder auf Produktetiketten drucken können. + +--- + +## Nächste Schritte und verwandte Themen + +* **Integration mit Flask oder Django** – den erzeugten PNG‑Stream direkt über einen Web‑Endpoint bereitstellen. +* **Batch‑Erzeugung** – über eine Liste von Produkt‑IDs iterieren, um einen Ordner mit Barcode‑PNG‑Dateien zu erstellen. +* **Kombination mit PDF‑Erstellung** – `aspose-pdf` nutzen, um das PNG in eine Rechnung oder ein Versandetikett einzufügen. +* **Weitere Symbologien erkunden** – `EncodeTypes.Planet` durch `EncodeTypes.QR`, `EncodeTypes.DataMatrix` oder `EncodeTypes.Code128` ersetzen, um unterschiedliche geschäftliche Anforderungen zu erfüllen. + +Durch das Beherrschen der obigen Schritte wissen Sie jetzt **wie man Barcode‑Bilder** programmgesteuert erzeugt und können das Muster auf jeden von Aspose.BarCode unterstützten Barcode‑Standard ausweiten. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/german/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..652b1405d --- /dev/null +++ b/barcode/german/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-08-03 +description: Erstellen Sie schnell ein Post‑Barcode‑Bild in C#. Erfahren Sie, wie + Sie einen Post‑Barcode generieren, die Barcode‑Abmessungen festlegen und einen Planet‑Barcode + erzeugen. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: de +lastmod: 2026-08-03 +og_description: Erstellen Sie ein Post-Barcode-Bild in C# mit diesem umfassenden Tutorial; + lernen Sie, wie Sie Barcode-Abmessungen festlegen, einen Planet-Barcode generieren + und RM4SCC-Barcodes erzeugen. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Erstelle ein Post‑Barcode‑Bild in C# – vollständiger Programmierleitfaden +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Erstelle ein Post‑Barcode‑Bild in C# – Schritt‑für‑Schritt‑Anleitung +url: /de/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Erstellen eines Post‑Barcode‑Bildes in C# – Schritt‑für‑Schritt‑Anleitung + +Wenn Sie in C# ein **Post‑Barcode‑Bild erstellen** müssen, zeigt Ihnen dieser Leitfaden genau, wie es geht. Wir behandeln **wie man einen Post‑Barcode generiert**, **wie man Barcode‑Abmessungen festlegt** und wie man **Planet‑Barcode generiert** für gängige Poststandards. + +Am Ende haben Sie zwei einsatzbereite PNG‑Dateien – einen Planet‑Barcode und einen RM4SCC‑Barcode – jeweils 100 px hoch. Keine zusätzlichen Werkzeuge sind erforderlich, außer der Aspose.BarCode‑Bibliothek für .NET. + +## Voraussetzungen + +* .NET 6 SDK oder neuer (der Code funktioniert auch mit .NET Framework 4.7+) +* Visual Studio 2022 oder jede C#‑IDE +* NuGet‑Paket **Aspose.BarCode** (die Bibliothek, die `BarcodeGenerator` bereitstellt) + +## Schritt 1: Installieren der Barcode‑Bibliothek + +Öffnen Sie ein Terminal in Ihrem Projektordner und führen Sie aus: + +```bash +dotnet add package Aspose.BarCode +``` + +Das Paket fügt den Namespace `Aspose.BarCode` hinzu, der `BarcodeGenerator` und die Aufzählung `EncodeTypes` enthält, die für Post‑Barcodes benötigt werden. + +## Schritt 2: Definieren des Ausgabeverzeichnisses + +Das Erstellen eines zuverlässigen Ausgabepfads verhindert Laufzeitfehler, wenn das Verzeichnis nicht existiert. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Warum das wichtig ist*: `Directory.CreateDirectory` ist idempotent – es erstellt das Verzeichnis nur, wenn es noch nicht vorhanden ist, und verhindert Ausnahmen bei späteren Ausführungen. + +## Schritt 3: Konfigurieren gemeinsamer Barcode‑Abmessungen + +Das Festlegen der X‑Dimension (Breite eines einzelnen Strichs) und der Gesamthöhe des Strichs ermöglicht die Kontrolle der visuellen Größe des erzeugten Bildes. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Wie man Barcode‑Abmessungen festlegt**: Die Eigenschaft `Parameters.Barcode.XDimension.Pixels` definiert die Breite des schmalen Strichs, während `Parameters.Barcode.BarHeight.Pixels` die Gesamthöhe festlegt. Passen Sie diese Werte an die Vorgaben Ihres Versanddienstes an. + +## Schritt 4: Generieren eines Planet‑Barcodes + +Planet ist ein weit verbreiteter Post‑Barcode im Vereinigten Königreich. Der folgende Code erzeugt einen 100 px hohen Planet‑Barcode und speichert ihn als PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Warum das funktioniert**: `EncodeTypes.Planet` weist den Generator an, die Planet‑Symbologie zu verwenden. Die Methode `Save` schreibt eine PNG‑Datei an den angegebenen Pfad und bewahrt die zuvor festgelegten Abmessungen. + +## Schritt 5: Generieren eines RM4SCC‑Barcodes + +RM4SCC ist der niederländische Post‑Barcode‑Standard. Der untenstehende Code spiegelt das Planet‑Beispiel wider und demonstriert **wie man einen Post‑Barcode** eines anderen Typs mit identischen Abmessungen generiert. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Beide PNG‑Dateien befinden sich nun im Ordner `Barcodes`. Beim Öffnen sehen Sie saubere, 100 px hohe Barcodes, die druckbereit oder in Dokumente eingebettet sind. + +## Vollständiger Quellcode + +Unten finden Sie das vollständige, ausführbare Programm, das **Post‑Barcode‑Bilder** für sowohl Planet‑ als auch RM4SCC‑Standards **erstellt**. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Erwartete Ausgabe + +Beim Ausführen des Programms werden die Dateipfade ausgegeben und zwei PNG‑Dateien erstellt: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Jedes Bild ist 100 px hoch, mit einer 4‑Pixel breiten schmalen Strichbreite, passend zu den festgelegten Abmessungen. + +## Praktische Tipps und häufige Fallstricke + +* **Ordnerberechtigungen** – Wenn das Programm unter einem eingeschränkten Konto läuft, stellen Sie sicher, dass das Zielverzeichnis beschreibbar ist. +* **Unterschiedliche Abmessungen** – Um einen höheren Barcode zu erzeugen, erhöhen Sie `barHeightPixels`. Für feinere Auflösung verringern Sie `xDimensionPixels`, aber halten Sie es ≥ 2, um Darstellungsartefakte zu vermeiden. +* **Andere Post‑Symbologien** – Aspose.BarCode unterstützt außerdem `EncodeTypes.Postnet` und `EncodeTypes.AustralianPost`. Tauschen Sie den `EncodeTypes`‑Wert aus und behalten Sie die gleiche Dimensionslogik bei. +* **Bildformat** – Verwenden Sie `BarCodeImageFormat.Jpeg` für kleinere Dateigröße, wenn verlustfreie Qualität nicht erforderlich ist. + +## Fazit + +Sie wissen jetzt, wie man in C# **Post‑Barcode‑Bilddateien erstellt**, indem man Abmessungen konfiguriert, die passende Symbologie auswählt und das Ergebnis als PNG speichert. Das Tutorial behandelte **wie man einen Post‑Barcode generiert**, zeigte **wie man einen Planet‑Barcode erzeugt** und erklärte **wie man Barcode‑Abmessungen festlegt** für konsistente Ausgaben. + +Als Nächstes können Sie **Barcode‑Farben anpassen**, **menschlich lesbaren Text** hinzufügen oder die Bilder in PDF‑Rechnungen integrieren. Das gleiche Muster gilt für jeden anderen von Aspose.BarCode unterstützten Barcode‑Typ, sodass Sie diese Lösung zu einem vollständigen Post‑Automatisierungs‑Workflow erweitern können. + +## 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. + +- [Wie man Barcodes generiert – Ein‑Dimensionale Barcode‑Typen](/barcode/english/net/one-dimensional-barcode-types/) +- [Wie man Aztec‑Barcode mit benutzerdefiniertem Seitenverhältnis mit Aspose.BarCode für .NET generiert](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Wie man Barcode in Java generiert – Australia Post Barcode mit Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/german/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..ae2796fdd --- /dev/null +++ b/barcode/german/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-08-03 +description: Wie man Barcodes in C# speichert – ein Schritt‑für‑Schritt‑Beispiel für + einen Barcode‑Generator. Lernen Sie, Planet‑Barcodes zu erzeugen, Abmessungen festzulegen + und PNG‑Bilder zu exportieren. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: de +lastmod: 2026-08-03 +og_description: Wie man Barcode in C# mit einem Barcode‑Generator‑Beispiel speichert. + Dieses Tutorial zeigt, wie man Planet‑Barcodes erzeugt, die X‑Dimension konfiguriert + und PNG‑Dateien exportiert. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Wie man einen Barcode in C# speichert – Schritt‑für‑Schritt‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Wie man Barcode in C# speichert – vollständige Anleitung zum Barcode-Generator +url: /de/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man Barcodes in C# speichert – vollständiger Barcode-Generator-Leitfaden + +Barcodes in C# zu speichern ist ein häufiges Anliegen, wenn Sie Post‑Barcodes in Rechnungen, Versandetiketten oder Bestandskennzeichnungen einbetten müssen. Dieser Leitfaden führt Sie durch einen praktischen **c# barcode generator**‑Workflow, vom Erstellen eines Planet‑Barcodes bis zum Exportieren von sowohl gefüllten als auch leeren PNG‑Dateien. + +Sie lernen, wie Sie die Balkenbreite einstellen, gefüllte Balken umschalten und Ausgabeverzeichnisse zuverlässig handhaben. Am Ende des Tutorials haben Sie ein voll funktionsfähiges **barcode generator example**, das Sie in jedes .NET‑Projekt kopieren können. + +## Was Sie benötigen + +- .NET 6.0 SDK oder höher (das Beispiel funktioniert mit .NET Core und .NET Framework) +- Visual Studio 2022 oder jede C#‑kompatible IDE +- Das **Aspose.BarCode** NuGet‑Paket (oder eine andere Bibliothek, die `EncodeTypes.Planet` unterstützt). Installieren Sie es mit: + +```bash +dotnet add package Aspose.BarCode +``` + +Die Bibliothek stellt die Klasse `BarcodeGenerator` bereit, die im gesamten Tutorial verwendet wird. + +## Einrichten der Entwicklungsumgebung + +Erstellen Sie ein neues Konsolenprojekt und fügen Sie den erforderlichen Namespace hinzu: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +Der Namespace `System.IO` liefert uns `Directory.CreateDirectory`, der sicherstellt, dass das Ausgabeverzeichnis existiert, bevor wir versuchen, Dateien zu schreiben. + +## Wie man Barcode‑Bilder mit dem C#‑Barcode‑Generator speichert + +Der Kern der Lösung besteht aus einer kleinen Reihe von Schritten, die einen **Planet barcode** konfigurieren und anschließend das Bild auf die Festplatte speichern. Die folgenden Abschnitte zerlegen den Prozess in handhabbare Teile. + +### Schritt 1: Definieren des Ausgabeverzeichnisses + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Warum?** +Das Hard‑Coden eines Pfads kann auf Rechnern, auf denen das Verzeichnis nicht existiert, zu `DirectoryNotFoundException` führen. `CreateDirectory` ist idempotent – es erstellt das Verzeichnis nur, wenn es fehlt, wodurch der Code bei wiederholten Ausführungen sicher ist. + +### Schritt 2: Erstellen eines Planet‑Barcode‑Generators (gefüllte Balken) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Warum?** +`EncodeTypes.Planet` weist die Bibliothek an, einen postalischen Planet‑Barcode zu erzeugen, der von vielen Postdiensten verwendet wird. Der String `"123456"` ist das Beispiel‑Payload; ersetzen Sie ihn durch beliebige numerische Daten, die Ihre Geschäftslogik erfordert. + +### Schritt 3: Konfigurieren der Balkenbreite (X‑Dimension) und Beibehalten der standardmäßigen gefüllten Balken + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Warum?** +Die X‑Dimension steuert die physische Breite jedes Balkens. Ein Wert von `4` Pixeln ergibt einen lesbaren Barcode auf Standard‑300‑dpi‑Druckern. Das Belassen von `FilledBars` als `true` (Standard) erzeugt das klassische Voll‑Balken‑Aussehen. + +### Schritt 4: Speichern des Barcode‑Bildes mit gefüllten Balken + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Warum?** +Das Speichern als PNG bewahrt verlustfreie Bildqualität, was für die Scan‑Genauigkeit wichtig ist. Die Methode `Save` erstellt die Bilddatei automatisch; Sie müssen nur den vollständigen Pfad und das gewünschte Format angeben. + +### Schritt 5: Erstellen eines zweiten Generators für die leeren Balken‑Version + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Das Erstellen einer neuen Instanz stellt sicher, dass Änderungen für die leeren‑Balken‑Version das bereits gespeicherte Bild mit gefüllten Balken nicht beeinflussen. + +### Schritt 6: Deaktivieren gefüllter Balken bei gleichbleibender X‑Dimension + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Warum?** +Durch Setzen von `FilledBars = false` wird der Barcode nur mit der Kontur jedes Balkens dargestellt, was einige Poststandards für die visuelle Überprüfung verlangen. + +### Schritt 7: Speichern des Barcode‑Bildes mit leeren Balken + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Jetzt haben Sie zwei PNG‑Dateien – eine mit gefüllten Balken und eine mit leeren Balken – bereit für die Einbindung in PDFs, HTML‑E‑Mails oder gedruckte Etiketten. + +## Vollständiges ausführbares Programm + +Unten finden Sie den vollständigen Code, den Sie in `Program.cs` kopieren können. Er kompiliert und läuft ohne Änderungen (vorausgesetzt, das Aspose.BarCode‑Paket ist installiert). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Erwartete Ausgabe + +Das Ausführen des Programms gibt zwei Zeilen aus, die etwa wie folgt aussehen: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Öffnen Sie den Ordner `Barcodes` und Sie sehen die beiden PNG‑Dateien. Beide Bilder können in jedem Bildbetrachter geöffnet oder direkt in Dokumente eingebettet werden. + +![Beispiel zum Speichern von Barcodes](barcode-example.png){: .align-center alt="Beispiel zum Speichern von Barcodes"} + +## Häufige Variationen und Sonderfälle + +| Szenario | Anpassung | +|----------|------------| +| **Anderes Bildformat** | Ändern Sie `BarCodeImageFormat.Png` zu `Jpeg`, `Gif` oder `Bmp`, je nach Bedarf. | +| **Benutzerdefinierte Ausgabengröße** | Verwenden Sie `filled.Parameters.Image.Width` und `Height`, um eine bestimmte Pixelgröße zu erzwingen. | +| **Dynamische Daten** | Ersetzen Sie das statische `"123456"` durch eine Variable, die Bestellnummern, Tracking‑IDs usw. enthält. | +| **Nicht‑existierender Ordner** | `Directory.CreateDirectory` behandelt bereits fehlende Verzeichnisse; zusätzlicher Code ist nicht nötig. | +| **Hochauflösender Druck** | Erhöhen Sie `XDimension.Pixels` auf 6–8 für 600‑dpi‑Drucker, prüfen Sie jedoch die Scanner‑Kompatibilität. | + +**Pro‑Tipp:** Wenn Sie viele Barcodes in einer Schleife erzeugen müssen, verwenden Sie eine einzelne `BarcodeGenerator`‑Instanz und ändern Sie nur die `CodeText`‑Eigenschaft vor jedem `Save`. Das reduziert den Overhead bei der Objektzuweisung. + +## Wie man Barcodes für andere Standards generiert + +Das gleiche Muster funktioniert für andere `EncodeTypes` wie `Code128`, `QR` oder `DataMatrix`. Ersetzen Sie einfach `EncodeTypes.Planet` durch den gewünschten Typ und passen Sie ggf. typ‑spezifische Parameter an (z. B. `QRCodeVersion`). + +## 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. + +- [Wie man PNG mit DataMatrix C40 mit Aspose.BarCode speichert](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Wie man DataMatrix‑Barcodes (ECC 200) mit Aspose.BarCode für .NET erzeugt](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Wie man Barcodes erzeugt – Code‑39‑Konfiguration mit Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/greek/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..5100f49ec --- /dev/null +++ b/barcode/greek/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-08-03 +description: Μάθημα δημιουργίας barcode σε C# που δείχνει πώς να δημιουργήσετε κωδικό + Planet με το Aspose.BarCode, να ορίσετε τη διάσταση X και να αποθηκεύσετε ως εικόνες + PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: el +lastmod: 2026-08-03 +og_description: Το σεμινάριο δημιουργίας barcode C# σας καθοδηγεί στη δημιουργία ενός + barcode Planet, στην προσαρμογή της διάστασης X και στην αποθήκευση ως PNG χρησιμοποιώντας + το Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Γεννήτρια barcode C# – δημιουργήστε το barcode Planet βήμα‑βήμα +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Γεννήτρια barcode C# – δημιουργία κωδικού Planet και παράδειγμα RM4SCC +url: /el/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – create Planet barcode and RM4SCC example + +Αν χρειάζεστε έναν **barcode generator C#** που μπορεί να παράγει σύμβολα ειδικά για τα ταχυδρομεία, αυτός ο οδηγός σας δείχνει ακριβώς πώς να **δημιουργήσετε εικόνες Planet barcode** με το Aspose.BarCode. Θα δείτε πώς να ρυθμίσετε τη διάσταση X, να δημιουργήσετε ένα αντίστοιχο barcode RM4SCC και να αποθηκεύσετε και τα δύο ως αρχεία PNG—όλα σε λίγα σύντομα βήματα. + +Το tutorial καλύπτει όλα όσα χρειάζεστε για να εκτελέσετε τον κώδικα σε .NET 6 ή νεότερο, εξηγεί γιατί κάθε ρύθμιση είναι σημαντική και επισημαίνει κοινά προβλήματα όπως λανθασμένο πλάτος μονάδας ή έλλειψη δικαιωμάτων φακέλου. Στο τέλος θα έχετε δύο εικόνες barcode έτοιμες για εκτύπωση που συμμορφώνονται με τα πρότυπα Planet και RM4SCC. + +## Προαπαιτούμενα + +* .NET 6 SDK (ή οποιαδήποτε έκδοση .NET υποστηρίζεται από Aspose.BarCode) +* Visual Studio 2022 ή οποιοδήποτε IDE C# προτιμάτε +* Μια αναφορά NuGet στο **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Δικαίωμα εγγραφής στον φάκελο όπου σκοπεύετε να αποθηκεύσετε τα αρχεία PNG + +Δεν απαιτούνται πρόσθετες εξωτερικές υπηρεσίες· η βιβλιοθήκη διαχειρίζεται όλη την κωδικοποίηση τοπικά. + +## Βήμα 1: Αρχικοποίηση του αντικειμένου barcode generator C# object + +Το πρώτο βήμα είναι να δημιουργήσετε μια παρουσία του `BarcodeGenerator`. Ο κατασκευαστής δέχεται τη συμβολική μορφή του barcode (`EncodeTypes.Planet`) και τα δεδομένα προς κωδικοποίηση. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Γιατί αυτό το βήμα;* +`BarcodeGenerator` είναι το σημείο εισόδου για κάθε barcode που δημιουργείτε. Επιλέγοντας `EncodeTypes.Planet` η βιβλιοθήκη ακολουθεί την προδιαγραφή ISO/IEC 24723 που χρησιμοποιείται από πολλές ταχυδρομικές υπηρεσίες. + +## Βήμα 2: Ορισμός της διάστασης X (πλάτος μονάδας) για το Planet barcode + +Η διάσταση X ορίζει το πλάτος μιας μονής μονάδας barcode (το μικρότερο μπαρ ή κενό). Μια τιμή **4 pixel** λειτουργεί καλά για τις περισσότερες εκτυπωτές ετικετών. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Γιατί αυτό είναι σημαντικό* +Αν η μονάδα είναι πολύ στενή, το barcode μπορεί να γίνει μη αναγνώσιμο· αν είναι πολύ πλατιά, το μέγεθος της ετικέτας αυξάνεται άσκοπα. Η ρύθμιση του `Pixels` σας επιτρέπει να ρυθμίσετε ακριβώς το barcode σύμφωνα με την ανάλυση του εκτυπωτή σας. + +## Βήμα 3: Αποθήκευση του Planet barcode ως εικόνα PNG + +Το Aspose.BarCode υπολογίζει αυτόματα το ύψος του barcode βάσει της επιλεγμένης συμβολικής μορφής, οπότε χρειάζεται μόνο να καθορίσετε τη διαδρομή αρχείου και τη μορφή. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Συμβουλή* +Αντικαταστήστε το `YOUR_DIRECTORY` με μια απόλυτη ή σχετική διαδρομή που υπάρχει στον υπολογιστή σας. Εάν ο φάκελος δεν υπάρχει, η μέθοδος `Save` ρίχνει `DirectoryNotFoundException`. + +**Αναμενόμενο αποτέλεσμα** – ένα αρχείο PNG που μοιάζει με την παρακάτω εικονογράφηση (η πραγματική εικόνα δεν εμφανίζεται εδώ, αλλά θα δείτε ένα κλασικό Planet barcode με αριθμητικό φορτίο `123456`). + +## Βήμα 4: Αρχικοποίηση δεύτερου δημιουργού για το barcode RM4SCC + +Πολλά ταχυδρομικά συστήματα απαιτούν και τα σύμβολα Planet και RM4SCC στο ίδιο τεμάχιο αλληλογραφίας. Δημιουργήστε μια νέα παρουσία `BarcodeGenerator` για τη συμβολική μορφή RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Γιατί ξεχωριστή παρουσία;* +Κάθε συμβολική μορφή έχει το δικό της σύνολο παραμέτρων. Η επαναχρησιμοποίηση του ίδιου δημιουργού μπορεί ακούσια να μεταφέρει ρυθμίσεις (όπως η διάσταση X) που δεν είναι βέλτιστες για το δεύτερο barcode. + +## Βήμα 5: Ρύθμιση της διάστασης X για το barcode RM4SCC + +Το RM4SCC επίσης σέβεται τη ρύθμιση της διάστασης X, έτσι εφαρμόζουμε το ίδιο πλάτος pixel για οπτική συνέπεια. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Συμβουλή επαγγελματία* +Αν χρειάζεστε ένα πιο ψηλό barcode (π.χ., για μεγαλύτερες ετικέτες), μπορείτε επίσης να ορίσετε `Height.Pixels`. Αν το αφήσετε ακαθόριστο, η βιβλιοθήκη υπολογίζει αυτόματα το ιδανικό ύψος. + +## Βήμα 6: Αποθήκευση του barcode RM4SCC ως εικόνα PNG + +Τέλος, αποθηκεύστε το barcode RM4SCC στο δίσκο. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Τώρα έχετε δύο αρχεία PNG—`PostalPlanetBarHeightNone.png` και `PostalRM4SCCBarHeightNone.png`—που μπορείτε να ενσωματώσετε σε ετικέτες αλληλογραφίας, να εκτυπώσετε σε φακέλους ή να στείλετε σε υπηρεσία εκτύπωσης τρίτου. + +## Προαιρετικό: Ρύθμιση ύψους ή χρήση άλλων μορφών εικόνας + +Αν η ροή εργασίας σας απαιτεί συγκεκριμένο ύψος barcode ή διαφορετική μορφή εικόνας (π.χ., JPEG ή BMP), μπορείτε να τροποποιήσετε τις παραμέτρους πριν καλέσετε το `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Ακραία περίπτωση** – Όταν ορίσετε προσαρμοσμένο ύψος, βεβαιωθείτε ότι η τιμή σέβεται το ελάχιστο ύψος που απαιτεί το πρότυπο ISO· διαφορετικά το barcode μπορεί να αποτύχει στην επικύρωση. + +## Συνηθισμένα προβλήματα και πώς να τα αποφύγετε + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| `DirectoryNotFoundException` | Ο φάκελος προορισμού δεν υπάρχει ή υπάρχει λάθος στην ονομασία. | Δημιουργήστε πρώτα το φάκελο ή χρησιμοποιήστε `Path.Combine` με `Environment.CurrentDirectory`. | +| Barcode unreadable on low‑resolution printers | Η διάσταση X είναι πολύ μικρή για το DPI του εκτυπωτή. | Αυξήστε το `XDimension.Pixels` σε 5‑6 για εκτυπωτές 203 dpi, ή δοκιμάστε με δείγμα ετικέτας. | +| Wrong symbology used | Χρήση `EncodeTypes.Code128` αντί για `EncodeTypes.Planet`. | Ελέγξτε ξανά ότι η τιμή του enum `EncodeTypes` ταιριάζει με το απαιτούμενο ταχυδρομικό πρότυπο. | +| Null reference on `Parameters` | Χρήση παλαιότερης έκδοσης του Aspose.BarCode όπου το API διαφέρει. | Αναβαθμίστε στην πιο πρόσφατη έκδοση του πακέτου NuGet (v23.12 ή νεότερη). | + +## Πλήρες εκτελέσιμο παράδειγμα + +Παρακάτω είναι το πλήρες πρόγραμμα που μπορείτε να αντιγράψετε, επικολλήσετε και εκτελέσετε. Περιλαμβάνει δηλώσεις `using`, διαχείριση σφαλμάτων και σχόλια που εξηγούν κάθε γραμμή. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Η εκτέλεση του προγράμματος δημιουργεί έναν φάκελο `Barcodes` δίπλα στο εκτελέσιμο και τοποθετεί μέσα τα δύο αρχεία PNG. Ανοίξτε τα με οποιονδήποτε προβολέα εικόνων για να επαληθεύσετε το αποτέλεσμα. + +## Συμπέρασμα + +Τώρα έχετε μια λύση **barcode generator C#** που μπορεί να **δημιουργήσει εικόνες Planet barcode**, να ρυθμίσει τη διάσταση X για βέλτιστη εκτύπωση και να παράγει ένα αντίστοιχο barcode RM4SCC—όλα με λίγες γραμμές κώδικα. Η προσέγγιση λειτουργεί με .NET 6+, απαιτεί μόνο το πακέτο NuGet Aspose.BarCode και μπορεί να επεκταθεί σε άλλες συμβολικές μορφές όπως Code128, QR ή DataMatrix αλλάζοντας την τιμή του `EncodeTypes`. + +### Τι θα ακολουθήσει; + +* Δοκιμάστε διαφορετικές τιμές `XDimension.Pixels` για να ταιριάξουν με το DPI του εκτυπωτή σας. +* Δημιουργήστε barcodes σε άλλες μορφές (PDF, SVG) αλλάζοντας το enum `BarCodeImageFormat`. +* Συνδυάστε τα δύο αρχεία PNG σε μία ετικέτα χρησιμοποιώντας μια βιβλιοθήκη γραφικών όπως **SkiaSharp**. +* Εξερευνήστε ολόκληρο το API του Aspose.BarCode για προχωρημένα χαρακτηριστικά όπως επικύρωση checksum ή προσαρμοσμένες γραμματοσειρές. + +Μη διστάσετε να προσαρμόσετε τον κώδικα για επεξεργασία σε παρτίδες ή να τον ενσωματώσετε σε μια υπηρεσία web ASP.NET Core που επιστρέφει εικόνες barcode κατόπιν ζήτησης. Καλή προγραμματιστική! + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που βασίζονται στις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Δημιουργία Barcode PNG – Αναλογία Διαστάσεων DataMatrix – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Πώς να αποθηκεύσετε PNG χρησιμοποιώντας DataMatrix C40 με Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Προσαρμογή Αναλογιών Διαστάσεων Code 16K Barcode με Aspose.BarCode για .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/greek/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..f5336ef55 --- /dev/null +++ b/barcode/greek/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-03 +description: Το σεμινάριο δημιουργίας barcode σε C# δείχνει πώς να δημιουργήσετε εικόνα + barcode με το Aspose.BarCode, να ορίσετε στήλες και γραμμές και να αποθηκεύσετε + αρχεία PNG για το DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: el +lastmod: 2026-08-03 +og_description: Το σεμινάριο δημιουργίας barcode C# εξηγεί πώς να δημιουργήσετε εικόνα + barcode χρησιμοποιώντας το Aspose.BarCode, να διαμορφώσετε στήλες και σειρές DataBar + Expanded Stacked και να αποθηκεύσετε αρχεία PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Γεννήτρια barcode C# – βήμα-βήμα οδηγός για τη δημιουργία εικόνας barcode +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Γεννήτρια barcode C# – δημιουργία εικόνας barcode +url: /el/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Γεννήτρια barcode C# – δημιουργία εικόνας barcode + +Αν χρειάζεστε μια γεννήτρια barcode C# που μπορεί να δημιουργήσει εικόνα barcode για DataBar Expanded Stacked, αυτός ο οδηγός σας καθοδηγεί μέσω της πλήρους διαδικασίας. Θα μάθετε πώς να ρυθμίσετε τις ρυθμίσεις στήλης και γραμμής, να αποθηκεύσετε το αποτέλεσμα ως PNG και να προσαρμόσετε τον κώδικα για άλλες συμβολές. + +Η προγραμματιστική δημιουργία εικόνων barcode αφαιρεί τα χειροκίνητα βήματα και εξασφαλίζει συνέπεια σε τιμολόγια, ετικέτες αποστολής και συστήματα αποθεμάτων. Αυτό το tutorial καλύπτει όλα όσα χρειάζεστε, από τη ρύθμιση του έργου μέχρι τον πλήρη πηγαίο κώδικα, ώστε να μπορείτε να εκτελέσετε το παράδειγμα αμέσως. + +## Προαπαιτούμενα + +* .NET 6.0 ή νεότερη έκδοση εγκατεστημένη +* Ένα IDE όπως το Visual Studio 2022 (οποιοσδήποτε επεξεργαστής που υποστηρίζει C# λειτουργεί) +* Άδεια για **Aspose.BarCode for .NET** – η δωρεάν αξιολόγηση λειτουργεί για δοκιμές +* Βασική εξοικείωση με τη σύνταξη C# + +Αν λείπει κάποιο από αυτά τα στοιχεία, εγκαταστήστε το .NET SDK από dotnet.microsoft.com και αποκτήστε το πακέτο NuGet Aspose.BarCode με: + +```bash +dotnet add package Aspose.BarCode +``` + +## Βήμα 1: Δημιουργία έργου γεννήτριας barcode C# + +Δημιουργήστε μια νέα εφαρμογή κονσόλας και προσθέστε τις απαιτούμενες οδηγίες `using`: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +Η κλάση `BarcodeGenerator` είναι ο πυρήνας του API της γεννήτριας barcode C#. Λαμβάνει τον τύπο συμβολής και το κείμενο προς κωδικοποίηση. + +## Βήμα 2: Δημιουργία barcode DataBar Expanded Stacked και ορισμός στηλών + +Το πρώτο παράδειγμα δημιουργεί ένα barcode με τέσσερις στήλες. Η ρύθμιση της ιδιότητας `Columns` αλλάζει την οπτική πυκνότητα της συμβολής DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Γιατί είναι σημαντικό:** Ο αριθμός των στηλών επηρεάζει την ποσότητα των δεδομένων που μπορούν να αποθηκευτούν σε έναν συμπαγή χώρο. Ορίζοντας το σε 4 παράγει ένα πιο ευρύ barcode που παραμένει αναγνώσιμο από τους περισσότερους σαρωτές. + +## Βήμα 3: Δημιουργία barcode με προσαρμοσμένο αριθμό γραμμών + +Το δεύτερο παράδειγμα δείχνει πώς να ελέγξετε τη κάθετη διάταξη ορίζοντας την ιδιότητα `Rows`. Μια διαμόρφωση τριών γραμμών είναι χρήσιμη όταν χρειάζεστε ένα πιο ψηλό barcode για περιορισμένο οριζόντιο χώρο. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Γιατί είναι σημαντικό:** Η ρύθμιση των γραμμών σας επιτρέπει να προσαρμόσετε το barcode σε στενή στήλη διατηρώντας την αναγνωσιμότητα. Η γεννήτρια barcode C# επαναϋπολογίζει αυτόματα το μέγεθος του μονάδας ώστε να πληροί τις προδιαγραφές. + +## Βήμα 4: Πλήρες, εκτελέσιμο παράδειγμα + +Παρακάτω υπάρχει ένα αυτόνομο πρόγραμμα που συνδυάζει τα προηγούμενα βήματα. Αντιγράψτε τον κώδικα στο `Program.cs`, αντικαταστήστε το `YOUR_DIRECTORY` με μια υπάρχουσα διαδρομή φακέλου και εκτελέστε την εφαρμογή. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Αναμενόμενο αποτέλεσμα + +Όταν εκτελέσετε το πρόγραμμα, δύο αρχεία PNG εμφανίζονται στον προορισμό: + +* **DatabarCols4.png** – ένα barcode DataBar Expanded Stacked με τέσσερις στήλες +* **DatabarRows3.png** – τα ίδια δεδομένα κωδικοποιημένα σε τρεις γραμμές + +Ανοίξτε τις εικόνες με οποιονδήποτε προβολέα εικόνων· εμφανίζουν καθαρά, αναγνώσιμα barcodes έτοιμα για εκτύπωση ή ενσωμάτωση σε PDF. + +## Πώς να δημιουργήσετε εικόνα barcode με προσαρμοσμένες διαστάσεις + +Αν χρειάζεστε συγκεκριμένο μέγεθος εικόνας, ρυθμίστε τις ιδιότητες `ImageHeight` και `ImageWidth` πριν καλέσετε το `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Η αλλαγή των διαστάσεων δεν επηρεάζει τα κωδικοποιημένα δεδομένα· απλώς κλιμακώνει την οπτική αναπαράσταση. Αυτή η τεχνική είναι χρήσιμη όταν ενσωματώνετε barcodes σε UI στοιχεία με σταθερούς περιορισμούς διάταξης. + +## Συνηθισμένα προβλήματα και επαγγελματικές συμβουλές + +* **Διαχωριστές διαδρομής:** Χρησιμοποιήστε αλφαριθμητικά κυριολεκτικά (`@"C:\Path\file.png"`) ή `Path.Combine` για να αποφύγετε προβλήματα χαρακτήρων διαφυγής στα Windows. +* **Επιβολή άδειας:** Χωρίς έγκυρη άδεια, οι παραγόμενες εικόνες περιέχουν υδατογράφημα. Εφαρμόστε την άδειά σας νωρίς στην εφαρμογή: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Όρια κωδικοποίησης:** Το DataBar Expanded Stacked υποστηρίζει έως 74 αριθμητικούς χαρακτήρες. Η υπέρβαση αυτού του ορίου προκαλεί εξαίρεση. Επικυρώστε το μήκος της εισόδου πριν δημιουργήσετε τη γεννήτρια. +* **Απόδοση:** Η επαναχρησιμοποίηση μιας μόνο παρουσίας `BarcodeGenerator` για πολλαπλές αποθηκεύσεις μειώνει την κατανομή μνήμης. Αλλάξτε τις ιδιότητες `Rows` ή `Columns` μεταξύ αποθηκεύσεων μόνο αν το κωδικοποιημένο κείμενο παραμένει το ίδιο. + +## Επόμενα βήματα + +Τώρα που μπορείτε να δημιουργήσετε εικόνες barcode με τη γεννήτρια barcode C#, σκεφτείτε να εξερευνήσετε: + +* **Διαφορετικές συμβολές** – δοκιμάστε `EncodeTypes.QR`, `EncodeTypes.Code128` ή `EncodeTypes.Pdf417`. +* **Προσαρμογή χρώματος** – ορίστε `Parameters.Barcode.ForeColor` και `BackColor` ώστε να ταιριάζουν με την εταιρική ταυτότητα. +* **Ενσωμάτωση σε PDF** – συνδυάστε το παραγόμενο PNG με το Aspose.PDF για δημιουργία εκτυπώσιμων εγγράφων. + +Αυτές οι επεκτάσεις σας επιτρέπουν να δημιουργήσετε μια πλήρη λύση barcode για αποθέματα, logistics ή λιανικές εφαρμογές. + +--- + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω 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/) +- [Πώς να δημιουργήσετε DataMatrix Barcodes (ECC 200) με Aspose.BarCode για .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/greek/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..a2490649f --- /dev/null +++ b/barcode/greek/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-08-03 +description: Παράδειγμα γεννήτριας barcode σε C# που δείχνει πώς να ορίσετε το πλάτος, + πώς να αλλάξετε το ύψος και πώς να δημιουργήσετε εικόνα barcode. Ακολουθήστε οδηγίες + βήμα‑προς‑βήμα. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: el +lastmod: 2026-08-03 +og_description: Το παράδειγμα δημιουργού barcode δείχνει τη ρύθμιση του πλάτους της + διάστασης X, την αλλαγή του ύψους της γραμμής και τη δημιουργία εικόνας barcode + σε C#. Ακολουθήστε τα βήματα για να δημιουργήσετε αρχεία PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Παράδειγμα γεννήτριας barcode – Οδηγός πλάτους και ύψους C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Παράδειγμα δημιουργού barcode σε C# – ορισμός πλάτους και ύψους +url: /el/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Παράδειγμα δημιουργού barcode σε C# – ορισμός πλάτους και ύψους + +Αν χρειάζεστε ένα **barcode generator example** σε C#, αυτός ο οδηγός σας δείχνει πώς να ορίσετε το πλάτος της διάστασης X, πώς να αλλάξετε το ύψος των γραμμών, και πώς να δημιουργήσετε ένα αρχείο εικόνας barcode. Θα δείτε ένα πλήρες, εκτελέσιμο πρόγραμμα που παράγει δύο αρχεία PNG με διαφορετικά ύψη. + +Ένα τυπικό σενάριο είναι η δημιουργία ετικετών προϊόντων όπου το μέγεθος του barcode πρέπει να πληροί τις προδιαγραφές του scanner. Στο τέλος αυτού του tutorial θα μπορείτε να ρυθμίσετε προγραμματιστικά τις παραμέτρους πλάτους και ύψους και να αποθηκεύσετε το αποτέλεσμα ως εικόνα PNG. + +## Προαπαιτούμενα + +Πριν ξεκινήσετε, βεβαιωθείτε ότι έχετε: + +* .NET 6 (ή νεότερη) εγκατεστημένη – ο κώδικας στοχεύει στο .NET 6 SDK. +* Μια βιβλιοθήκη barcode που υποστηρίζει `EncodeTypes.DatabarOmniDirectional`. Το παράδειγμα χρησιμοποιεί **Aspose.BarCode for .NET**, αλλά οποιαδήποτε βιβλιοθήκη που εκθέτει παρόμοιες ιδιότητες λειτουργεί με τον ίδιο τρόπο. +* Ένα IDE ή επεξεργαστή (Visual Studio, VS Code, Rider) για να μεταγλωττίσετε και να εκτελέσετε το πρόγραμμα. +* Δικαίωμα εγγραφής σε έναν φάκελο όπου θα αποθηκευτούν τα αρχεία PNG. + +> **Συμβουλή:** Δημιουργήστε έναν φάκελο με όνομα `Barcodes` στη ρίζα του έργου σας και αναφερθείτε σε αυτόν με `Path.Combine` για να αποφύγετε την σκληρή κωδικοποίηση απόλυτων διαδρομών. + +## Παράδειγμα δημιουργού barcode: αρχικοποίηση και διαμόρφωση + +Το πρώτο βήμα είναι η δημιουργία ενός αντικειμένου `BarcodeGenerator` με την επιθυμητή συμβολική μορφή και τη συμβολοσειρά δεδομένων. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +Το enum `EncodeTypes.DatabarOmniDirectional` επιλέγει τη συμβολική μορφή Databar Omni‑directional, και η συμβολοσειρά δεδομένων μορφοποιημένη σε GS1 `(01)12345678901231` αντιπροσωπεύει μια τυπική τιμή GTIN‑14. Η αρχικοποίηση του generator μία φορά σας επιτρέπει να επαναχρησιμοποιήσετε το ίδιο αντικείμενο για πολλαπλές εικόνες. + +## Πώς να ορίσετε το πλάτος (διάσταση X) + +Η διάσταση X ελέγχει το πλάτος του μονάδας του barcode. Ορίζοντάς το σε 2 pixel, κάθε στενή γραμμή γίνεται 2 pixel πλατιά, κάτι που είναι κοινή απαίτηση για εκτύπωση υψηλής πυκνότητας. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Γιατί είναι σημαντικό: Αν το πλάτος είναι πολύ μικρό, οι scanners μπορεί να μην διακρίνουν τις μεμονωμένες γραμμές· αν είναι πολύ μεγάλο, το barcode μπορεί να υπερβεί το χώρο της ετικέτας. Ρυθμίστε την τιμή pixel ώστε να ταιριάζει με το DPI του εκτυπωτή και το μέγεθος της ετικέτας-στόχου. + +## Πώς να αλλάξετε το ύψος + +Το ύψος των γραμμών καθορίζει πόσο ψηλές εμφανίζονται. Το παράδειγμα δημιουργεί δύο εικόνες: μία με ύψος 30 pixel και άλλη με ύψος 60 pixel. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Η ιδιότητα `BarHeight.Pixels` επηρεάζει άμεσα το οπτικό ύψος των γραμμών. Αλλάζοντάς την μεταξύ αποθηκεύσεων, μπορείτε να δημιουργήσετε πολλαπλές παραλλαγές από το ίδιο payload δεδομένων χωρίς να ξαναδημιουργήσετε το generator. + +### Αναμενόμενο αποτέλεσμα + +Η εκτέλεση του προγράμματος παράγει δύο αρχεία PNG στον φάκελο `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – οι γραμμές έχουν ύψος 30 pixel. +* `DatabarBarHeight60Pixels.png` – οι γραμμές έχουν ύψος 60 pixel. + +Και οι δύο εικόνες μοιράζονται το ίδιο πλάτος (που καθορίζεται από τη διάσταση X) και κωδικοποιούν τα ίδια δεδομένα GTIN‑14. + +![Two barcode PNG files with different heights generated by C# code](barcode-example.png "Barcode generator example showing height variations") + +*Το κείμενο alt της εικόνας παραπάνω περιέχει τη βασική λέξη‑κλειδί για προσβασιμότητα και SEO.* + +## Πώς να δημιουργήσετε εικόνα barcode σε C# + +Η μέθοδος `Save` διαχειρίζεται τη μετατροπή από τα δεδομένα barcode σε αρχείο εικόνας. Μπορείτε να επιλέξετε άλλες μορφές (JPEG, BMP, SVG) περνώντας διαφορετική τιμή του enum `BarCodeImageFormat`. Το παράδειγμα χρησιμοποιεί PNG επειδή διατηρεί την απώλεια‑ποιότητας ποιότητα και υποστηρίζεται ευρέως. + +Αν χρειάζεται να ενσωματώσετε το barcode απευθείας σε PDF ή σε ιστοσελίδα, ανακτήστε την εικόνα ως `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Αυτή η προσέγγιση εξαλείφει την ανάγκη για προσωρινά αρχεία και είναι χρήσιμη για υπηρεσίες υψηλής διακίνησης. + +## Συνηθισμένες παραλλαγές και ειδικές περιπτώσεις + +| Κατάσταση | Προσαρμογή | +|-----------|------------| +| **Different symbology** | Αντικαταστήστε το `EncodeTypes.DatabarOmniDirectional` με άλλη τιμή enum (π.χ., `EncodeTypes.Code128`). | +| **Very small labels** | Μειώστε το `XDimension.Pixels` σε 1 pixel, αλλά ελέγξτε την αναγνωσιμότητα από τον scanner. | +| **High‑resolution printing** | Αυξήστε τόσο τη διάσταση X όσο και το ύψος των γραμμών αναλογικά (π.χ., 4 px πλάτος, 80 px ύψος). | +| **Dynamic data** | Περάστε τη συμβολοσειρά δεδομένων κατά την εκτέλεση, ίσως από μια εγγραφή βάσης δεδομένων. | +| **Batch generation** | Επανάληψη πάνω σε μια συλλογή συμβολοσειρών δεδομένων, επαναχρησιμοποιώντας το ίδιο αντικείμενο `BarcodeGenerator` ενώ ενημερώνετε το `generator.Text`. | + +Όταν αντιμετωπίζετε μια εξαίρεση όπως `ArgumentOutOfRangeException`, ελέγξτε ξανά ότι οι τιμές pixel είναι θετικοί ακέραιοι και ότι ο φάκελος εξόδου υπάρχει. + +## Πλήρης επανάληψη κώδικα + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Αντιγράψτε τον κώδικα σε ένα νέο console project, επαναφέρετε το πακέτο NuGet Aspose.BarCode (`dotnet add package Aspose.BarCode`), και εκτελέστε `dotnet run`. Θα δείτε μηνύματα στην κονσόλα που επιβεβαιώνουν τα αποθηκευμένα αρχεία. + +## Συμπέρασμα + +Αυτό το **barcode generator example** δείχνει πώς να ορίσετε το πλάτος, πώς να αλλάξετε το ύψος, και πώς να δημιουργήσετε μια εικόνα barcode σε C#. Με την προσαρμογή των `XDimension.Pixels` και `BarHeight.Pixels` ελέγχετε το οπτικό μέγεθος του barcode, και η μέθοδος `Save` γράφει το αποτέλεσμα σε αρχεία PNG. Πειραματιστείτε με διαφορετικές συμβολικές μορφές, μορφές εξόδου και συμβολοσειρές δεδομένων για να ταιριάξετε τις απαιτήσεις της εφαρμογής σας. + +**Επόμενα βήματα** + +* Εξερευνήστε **πώς να δημιουργήσετε barcode** σε άλλες μορφές εικόνας (SVG, JPEG) για χρήση στο web. +* Μάθετε **create barcode image c#** για endpoints ASP.NET Core που επιστρέφουν το PNG απευθείας σε έναν browser. +* Συνδυάστε αυτόν τον κώδικα με μια βιβλιοθήκη δημιουργίας PDF για να ενσωματώσετε barcodes σε τιμολόγια ή ετικέτες αποστολής. + +Νιώστε ελεύθεροι να προσαρμόσετε το παράδειγμα, να μοιραστείτε τα αποτελέσματα ή να θέσετε ερωτήσεις στα σχόλια. Καλή προγραμματιστική! + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να κατακτήσετε πρόσθετα χαρακτηριστικά του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας projects. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to Set Border for ITF-14 Barcode Customization](/barcode/english/net/itf-14-barcode-customization/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/greek/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..af9eaa06b --- /dev/null +++ b/barcode/greek/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-08-03 +description: Δημιουργήστε PNG barcode σε C# και μάθετε πώς να αλλάζετε την αναλογία + διαστάσεων για εικόνες DataBar. Ακολουθήστε αυτό το πλήρες παράδειγμα με κώδικα + και συμβουλές. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: el +lastmod: 2026-08-03 +og_description: Δημιουργήστε PNG barcode σε C# και δείτε πώς να αλλάξετε την αναλογία + διαστάσεων για τα DataBar barcode. Αυτός ο οδηγός σας παρέχει κώδικα έτοιμο για + εκτέλεση και πρακτικές συμβουλές. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Δημιουργία barcode PNG σε C# – πλήρες παράδειγμα με έλεγχο αναλογίας διαστάσεων +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Δημιουργία PNG barcode σε C# – οδηγός βήμα‑βήμα +url: /el/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία barcode PNG σε C# – οδηγός βήμα‑βήμα + +Αν χρειάζεστε **να δημιουργήσετε barcode PNG** σε C#, αυτό το tutorial σας δείχνει ακριβώς πώς. Θα δημιουργήσετε ένα στοίβαγμα omnidirectional DataBar barcode, θα το αποθηκεύσετε ως αρχείο PNG και θα μάθετε **πώς να αλλάξετε το aspect ratio** ώστε να ταιριάζει σε διαφορετικά περιβάλλοντα σάρωσης. + +Ο οδηγός καλύπτει όλα όσα χρειάζεστε: απαιτούμενα πακέτα, ένα πλήρες, εκτελέσιμο πρόγραμμα και εξηγήσεις για το γιατί κάθε ρύθμιση είναι σημαντική. Στο τέλος θα έχετε δύο αρχεία PNG—ένα με aspect ratio 15 και ένα με 30—έτοιμα για δοκιμή ή παραγωγική χρήση. + +## Προαπαιτούμενα + +Πριν ξεκινήσετε, βεβαιωθείτε ότι έχετε: + +- .NET 6.0 SDK ή νεότερο εγκατεστημένο +- Visual Studio 2022 (ή οποιοδήποτε IDE για C#) +- Αναφορά NuGet στο **Aspose.BarCode** (η βιβλιοθήκη που παρέχει `BarcodeGenerator`) +- Δικαιώματα εγγραφής στον φάκελο όπου θα αποθηκευτούν τα αρχεία PNG + +Μπορείτε να προσθέσετε το πακέτο Aspose.BarCode με την ακόλουθη εντολή: + +```bash +dotnet add package Aspose.BarCode +``` + +## Βήμα 1: Ρύθμιση του έργου και εισαγωγή ονομάτων χώρου + +Δημιουργήστε μια νέα εφαρμογή κονσόλας και εισάγετε τα ονόματα χώρου που απαιτούνται για τη δημιουργία barcode και την I/O αρχείων. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Γιατί είναι σημαντικό:** Η εισαγωγή του `Aspose.BarCode.Generation` σας δίνει πρόσβαση στο `BarcodeGenerator`. Η διατήρηση του κώδικα μέσα στο `Main` κάνει το παράδειγμα αυτό-συνεκτικό και εύκολο στην εκτέλεση. + +## Βήμα 2: Δημιουργία γεννήτριας barcode για στοίβαξη omnidirectional DataBar + +Δημιουργήστε ένα αντικείμενο `BarcodeGenerator` με τύπο `EncodeTypes.DatabarStackedOmniDirectional` και ένα δείγμα δεδομένων GS1‑128. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Γιατί είναι σημαντικό:** Ο επιλεγμένος τύπος κωδικοποίησης παράγει ένα υψηλής πυκνότητας DataBar που μπορεί να διαβαστεί από τους περισσότερους σύγχρονους σαρωτές. Η συμβολοσειρά δεδομένων ακολουθεί τη μορφή GS1 Application Identifier (01), η οποία είναι κοινή για αναγνωριστικά προϊόντων. + +## Βήμα 3: Ορισμός της διάστασης X (πλάτος μονάδας) σε pixel + +Ορίστε το πλάτος μονάδας για να ελέγξετε το συνολικό μέγεθος του barcode χωρίς να επηρεάσετε την αναγνωσιμότητά του. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Γιατί είναι σημαντικό:** Μια διάσταση X ίση με 2 pixel παράγει ένα barcode που δεν είναι ούτε πολύ μικρό για τους σαρωτές ούτε πολύ μεγάλο για τυπικούς χώρους ετικετών. + +## Βήμα 4: Αποθήκευση του πρώτου PNG με aspect ratio 15 + +Ρυθμίστε το aspect ratio του DataBar, στη συνέχεια αποθηκεύστε την εικόνα ως αρχείο PNG. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Γιατί είναι σημαντικό:** Το aspect ratio ελέγχει τη σχέση ύψους‑πλάτους του στοίβαγματος DataBar. Ένα ratio 15 είναι η κοινή προεπιλογή που ισορροπεί την αναγνωσιμότητα και το ύψος της ετικέτας. + +## Βήμα 5: Αλλαγή του aspect ratio σε 30 και αποθήκευση δεύτερου PNG + +Τροποποιήστε το ίδιο αντικείμενο γεννήτριας ώστε να χρησιμοποιεί μεγαλύτερο aspect ratio και αποθηκεύστε τη δεύτερη εικόνα. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Γιατί είναι σημαντικό:** Η αύξηση του aspect ratio τεντώνει το barcode κάθετα, κάτι που μπορεί να βελτιώσει την αξιοπιστία σάρωσης σε συσκευές χαμηλής ανάλυσης ή όταν η ετικέτα εκτυπώνεται σε στενό μέσο. + +## Αναμενόμενο αποτέλεσμα + +Η εκτέλεση του προγράμματος δημιουργεί δύο αρχεία PNG: + +| Αρχείο | Aspect Ratio | Προσεγγιστικές διαστάσεις (pixels) | +|-------------------------------------|--------------|-----------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (πλάτος × ύψος) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (πλάτος × ύψος) | + +Και οι δύο εικόνες περιέχουν ένα καθαρό, αναγνώσιμο DataBar barcode που κωδικοποιεί το GS1 αναγνωριστικό `(01)12345678901231`. + +## Συχνές ερωτήσεις και ειδικές περιπτώσεις + +### Πώς να αλλάξετε άλλες οπτικές ιδιότητες; + +Μπορείτε να ρυθμίσετε το χρώμα προσκηνίου, το χρώμα φόντου ή να προσθέσετε κείμενο αναγνώσιμη από άνθρωπο μέσω του αντικειμένου `generator.Parameters.Barcode`. Για παράδειγμα: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Τι γίνεται αν χρειάζομαι διαφορετική μορφή εικόνας; + +Αντικαταστήστε το `BarCodeImageFormat.Png` με `Jpeg`, `Bmp` ή `Gif` ανάλογα με τις ανάγκες. Το PNG παραμένει η καλύτερη επιλογή για εικόνες barcode χωρίς απώλειες. + +### Επηρεάζει το aspect ratio την ταχύτητα σάρωσης; + +Υψηλότερα aspect ratios αυξάνουν το ύψος του barcode, κάτι που μπορεί να βελτιώσει την αξιοπιστία σάρωσης σε συσκευές που δυσκολεύονται με σύντομα στοίβαγματα σύμβολα. Ωστόσο, πολύ ψηλά barcodes μπορεί να μην χωράνε σε μικρές ετικέτες, οπότε δοκιμάστε με το στοχευόμενο υλικό σας. + +### Μπορώ να δημιουργήσω πολλαπλά barcode σε βρόχο; + +Ναι. Δημιουργήστε ένα νέο αντικείμενο `BarcodeGenerator` για κάθε συμβολοσειρά δεδομένων ή επαναχρησιμοποιήστε το ίδιο αντικείμενο ενημερώνοντας το `CodeText` και το `DataBar.AspectRatio`. Αυτή η προσέγγιση μειώνει το κόστος κατανομής αντικειμένων. + +## Συμβουλές + +- **Επαναχρησιμοποίηση της γεννήτριας**: Η αλλαγή μόνο του `CodeText` ή του `AspectRatio` αποφεύγει την επανεκκίνηση του αντικειμένου, κάτι που επιταχύνει την επεξεργασία μεγάλων παρτίδων. +- **Επικύρωση του αποτελέσματος**: Χρησιμοποιήστε έναν φορητό σαρωτή ή μια εφαρμογή κινητού για να επιβεβαιώσετε ότι το παραγόμενο PNG διαβάζεται σωστά πριν το αναπτύξετε στην παραγωγή. +- **Ονομασία αρχείων**: Συμπεριλάβετε το aspect ratio στο όνομα του αρχείου (όπως φαίνεται) για να παρακολουθείτε τις παραλλαγές κατά τη δοκιμή. + +## Συμπέρασμα + +Τώρα ξέρετε πώς να **δημιουργήσετε barcode PNG** αρχεία σε C# και ακριβώς **πώς να αλλάξετε το aspect ratio** για στοίβαγμα omnidirectional DataBar συμβόλων. Το πλήρες παράδειγμα δείχνει την αρχικοποίηση, τη ρύθμιση της διάστασης X, τη διαχείριση του aspect ratio και την αποθήκευση της εικόνας—όλα σε ένα μόνο, εκτελέσιμο πρόγραμμα. + +Από εδώ μπορείτε να εξερευνήσετε πρόσθετους τύπους barcode, να πειραματιστείτε με χρώματα ή να ενσωματώσετε τη γεννήτρια σε ένα μεγαλύτερο σύστημα αναφορών ή απογραφής. Καλό προγραμματισμό! + +## Τι πρέπει να μάθετε στη συνέχεια; + +Οι παρακάτω οδηγίες καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κυριαρχήσετε επιπλέον δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στην υλοποίηση σας. + +- [Δημιουργία Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Πώς να δημιουργήσετε Aztec barcode με προσαρμοσμένο aspect ratio χρησιμοποιώντας Aspose.BarCode για .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Πώς να προσαρμόσετε Barcode - Codablock F Aspect Ratio με Aspose.BarCode για .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/greek/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..8d7d9ab9e --- /dev/null +++ b/barcode/greek/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-08-03 +description: Δημιουργήστε γρήγορα PNG barcode με αυτόν τον οδηγό. Μάθετε πώς να δημιουργήσετε + εικόνα barcode χρησιμοποιώντας το Aspose.BarCode και να δημιουργήσετε κώδικα planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: el +lastmod: 2026-08-03 +og_description: Δημιουργήστε άμεσα PNG barcode. Αυτός ο οδηγός δείχνει πώς να δημιουργήσετε + εικόνα barcode και να δημιουργήσετε planet barcode με το Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Δημιουργία barcode PNG σε Python – πλήρης οδηγός προγραμματισμού +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Δημιουργία barcode PNG σε Python – βήμα‑βήμα οδηγός +url: /el/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία barcode PNG σε Python – βήμα‑βήμα οδηγός + +Αν χρειάζεστε να **δημιουργήσετε αρχεία barcode PNG** από την εφαρμογή σας σε Python, αυτό το tutorial σας δείχνει ακριβώς πώς. Θα περάσουμε από το **πώς να δημιουργήσετε εικόνα barcode** χρησιμοποιώντας το Aspose.BarCode και συγκεκριμένα **να δημιουργήσετε planet barcode** με προσαρμοσμένες διαστάσεις. + +Θα μάθετε πώς να εγκαταστήσετε τη βιβλιοθήκη, να διαμορφώσετε τη συμβολική Planet, να προσαρμόσετε τις παραμέτρους μεγέθους και να αποθηκεύσετε το αποτέλεσμα ως PNG υψηλής ποιότητας. Ο οδηγός υποθέτει βασικές γνώσεις Python και μια πρόσφατη έκδοση της Python 3 (3.8 ή νεότερη). Δεν απαιτείται προηγούμενη εμπειρία με πρότυπα barcode. + +--- + +## Πώς να δημιουργήσετε barcode PNG με Aspose.BarCode + +Αυτή η ενότητα περιέχει τα βασικά βήματα που απαιτούνται για **δημιουργία barcode PNG**. Κάθε βήμα περιλαμβάνει ένα απόσπασμα κώδικα, μια εξήγηση του γιατί είναι σημαντικό, και πρακτικές συμβουλές που μπορείτε να εφαρμόσετε άμεσα. + +### 1. Εγκατάσταση του πακέτου Aspose.BarCode + +Η Aspose παρέχει ένα καθαρό‑Python πακέτο που περιβάλλει τη μηχανή .NET core της. Εγκαταστήστε το με `pip`: + +```bash +pip install aspose-barcode +``` + +*Γιατί είναι σημαντικό αυτό το βήμα:* Το πακέτο παρέχει την κλάση `BarcodeGenerator` που χρησιμοποιείται σε όλο το παράδειγμα. Η παγκόσμια εγκατάσταση διασφαλίζει ότι ο διερμηνέας μπορεί να εντοπίσει τη συναρμολόγηση κατά την εκτέλεση. + +### 2. Εισαγωγή απαιτούμενων κλάσεων + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Συμβουλή:* Εισάγετε μόνο τα σύμβολα που χρειάζεστε· αυτό διατηρεί καθαρό το namespace και επιταχύνει τη φόρτωση του module. + +### 3. Δημιουργία γεννήτριας barcode για τη συμβολική Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Γιατί είναι σημαντικό:* `EncodeTypes.Planet` λέει στη μηχανή να χρησιμοποιήσει το πρότυπο barcode Planet, ενώ το δεύτερο όρισμα παρέχει τα δεδομένα προς κωδικοποίηση. Η αλλαγή της συμβολικής (π.χ., `EncodeTypes.Code128`) θα παρήγαγε ένα εντελώς διαφορετικό οπτικό μοτίβο. + +### 4. Ορισμός της διάστασης X (πλάτος μονάδας) σε pixel + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Εξήγηση:* Η διάσταση X ελέγχει το πλάτος της στενής γραμμής. Μια τιμή 4 pixel παράγει ένα μέτρια πυκνό barcode που παραμένει αναγνώσιμο στα περισσότερα συστήματα. + +### 5. Ορισμός χειροκίνητου ύψους γραμμής σε pixel + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Γιατί μπορεί να το ρυθμίσετε:* Ορισμένοι εκτυπωτές λιανικής απαιτούν ψηλότερες γραμμές για αξιόπιστη σάρωση. Το προεπιλεγμένο ύψος είναι συνήθως 50 px· η αύξηση σε 100 px βελτιώνει την αναγνωσιμότητα χωρίς να αυξάνει δραστικά το μέγεθος του αρχείου. + +### 6. Αποθήκευση του παραγόμενου barcode ως εικόνα PNG + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Αποτέλεσμα:* Ένα αρχείο PNG με όνομα **PlanetBarHeight100.png** εμφανίζεται στο φάκελο `output`. Το PNG είναι loss‑less, καθιστώντας το ιδανικό για εκτύπωση και ενσωμάτωση σε ιστοσελίδες. + +### 7. Επαλήθευση του αποτελέσματος (προαιρετικό) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Συμβουλή:* Η προβολή της εικόνας επιβεβαιώνει ότι οι διαστάσεις ταιριάζουν με τις παραμέτρους που ορίσατε. Αν το barcode φαίνεται παραμορφωμένο, ελέγξτε ξανά τη διάσταση X ή τις ρυθμίσεις του ύψους γραμμής. + +--- + +## Πώς να δημιουργήσετε εικόνα barcode σε μορφή PNG (εναλλακτικές ρυθμίσεις) + +Αν χρειάζεστε διαφορετική μορφή εικόνας ή θέλετε να ενσωματώσετε το barcode σε PDF αργότερα, μπορείτε να αλλάξετε το enum `BarCodeImageFormat`: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Γιατί είναι σημαντικό:* Το PNG διατηρεί κάθε pixel, κάτι που είναι κρίσιμο για barcode υψηλής αντίθεσης. Το JPEG εισάγει συμπιεστικά artefacts που μπορούν να επηρεάσουν τη σάρωση, ενώ το BMP προσφέρει συμβατότητα με παλαιότερα εργαλεία. + +--- + +## Δημιουργία planet barcode με προσαρμοσμένα χρώματα (προχωρημένο) + +Πέρα από το μέγεθος, μπορείτε να προσαρμόσετε τα χρώματα προσκηνίου και φόντου: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Πρακτική συμβουλή:* Ζεύγη χρωμάτων υψηλής αντίθεσης (σκούρο σε ανοιχτό) μεγιστοποιούν την αξιοπιστία του scanner. Αποφύγετε τη χρήση παρόμοιων αποχρώσεων για προσκήνιο και φόντο. + +--- + +## Συνηθισμένα προβλήματα και πώς να τα αποφύγετε + +| Συμπτωμα | Αιτία | Διόρθωση | +|----------|-------|----------| +| Το barcode δεν σαρώνεται | Διάσταση X πολύ μικρή (≤ 2 px) | Αυξήστε το `x_dimension.pixels` τουλάχιστον σε 3 px | +| Η εικόνα εμφανίζεται θολή | PNG αποθηκεύτηκε με χαμηλό DPI | Χρησιμοποιήστε `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` για να ορίσετε 300 DPI (αν υποστηρίζεται) | +| Εξαίρεση `ImportError` | Το Aspose.BarCode δεν είναι εγκατεστημένο | Εκτελέστε `pip install aspose-barcode` στο ίδιο περιβάλλον με το script σας | +| Λάθος συμβολική | Χρησιμοποιήθηκε `EncodeTypes.Code128` αντί για `EncodeTypes.Planet` | Αντικαταστήστε με `EncodeTypes.Planet` κατά τη δημιουργία του γεννήτρια | + +--- + +## Ανασκόπηση της πλήρους λύσης + +Παρακάτω είναι το πλήρες, εκτελέσιμο script που **δημιουργεί barcode PNG** από την αρχή μέχρι το τέλος: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Η εκτέλεση αυτού του script παράγει ένα καθαρό **Planet barcode PNG** που μπορείτε να ενσωματώσετε σε HTML, να το επισυνάψετε σε email ή να το εκτυπώσετε σε ετικέτες προϊόντων. + +--- + +## Επόμενα βήματα και σχετικές θεματικές + +* **Integrate with Flask or Django** – εξυπηρετήστε το παραγόμενο PNG απευθείας από ένα web endpoint. +* **Batch generation** – επαναλάβετε πάνω σε λίστα με IDs προϊόντων για να δημιουργήσετε φάκελο με αρχεία barcode PNG. +* **Combine with PDF generation** – χρησιμοποιήστε το `aspose-pdf` για να τοποθετήσετε το PNG σε τιμολόγιο ή ετικέτα αποστολής. +* **Explore other symbologies** – αντικαταστήστε το `EncodeTypes.Planet` με `EncodeTypes.QR`, `EncodeTypes.DataMatrix` ή `EncodeTypes.Code128` για να καλύψετε διαφορετικές επιχειρηματικές ανάγκες. + +Με την κατανόηση των παραπάνω βημάτων, τώρα γνωρίζετε **πώς να δημιουργήσετε εικόνα barcode** προγραμματιστικά και μπορείτε να επεκτείνετε το μοτίβο σε οποιοδήποτε πρότυπο barcode υποστηρίζεται από το Aspose.BarCode. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/greek/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..70a333bb5 --- /dev/null +++ b/barcode/greek/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-08-03 +description: Δημιουργήστε εικόνα ταχυδρομικού barcode σε C# γρήγορα. Μάθετε πώς να + δημιουργείτε ταχυδρομικό barcode, να ορίζετε τις διαστάσεις του barcode και να δημιουργείτε + ένα Planet barcode. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: el +lastmod: 2026-08-03 +og_description: Δημιουργήστε εικόνα ταχυδρομικού barcode σε C# με αυτόν τον πλήρη + οδηγό· μάθετε πώς να ορίζετε τις διαστάσεις του barcode, να δημιουργείτε ένα barcode + Planet και να παράγετε barcodes RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Δημιουργία εικόνας ταχυδρομικού barcode σε C# – πλήρης οδηγός προγραμματισμού +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Δημιουργία εικόνας ταχυδρομικού γραμμωτού κώδικα σε C# – οδηγός βήμα‑βήμα +url: /el/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία εικόνας ταχυδρομικού barcode σε C# – οδηγός βήμα‑βήμα + +Αν χρειάζεστε **να δημιουργήσετε εικόνα ταχυδρομικού barcode** σε C#, αυτός ο οδηγός σας δείχνει ακριβώς πώς. Θα καλύψουμε **πώς να δημιουργήσετε ταχυδρομικό barcode**, **πώς να ορίσετε τις διαστάσεις του barcode**, και πώς να **δημιουργήσετε Planet barcode** για κοινά ταχυδρομικά πρότυπα. + +Θα ολοκληρώσετε με δύο έτοιμα αρχεία PNG — ένα Planet barcode και ένα RM4SCC barcode — το καθένα ύψους 100 px. Δεν απαιτούνται πρόσθετα εργαλεία πέρα από τη βιβλιοθήκη Aspose.BarCode για .NET. + +## Προαπαιτήσεις + +* .NET 6 SDK ή νεότερο (ο κώδικας λειτουργεί επίσης με .NET Framework 4.7+) +* Visual Studio 2022 ή οποιοδήποτε IDE για C# +* Πακέτο NuGet **Aspose.BarCode** (η βιβλιοθήκη που παρέχει το `BarcodeGenerator`) + +## Βήμα 1: Εγκατάσταση της βιβλιοθήκης barcode + +Ανοίξτε ένα τερματικό στον φάκελο του έργου σας και εκτελέστε: + +```bash +dotnet add package Aspose.BarCode +``` + +Το πακέτο προσθέτει το namespace `Aspose.BarCode`, το οποίο περιλαμβάνει το `BarcodeGenerator` και την απαραίτητη απαρίθμηση `EncodeTypes` για ταχυδρομικά barcodes. + +## Βήμα 2: Ορισμός του φακέλου εξόδου + +Η δημιουργία μιας αξιόπιστης διαδρομής εξόδου αποτρέπει σφάλματα χρόνου εκτέλεσης όταν ο φάκελος δεν υπάρχει. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Γιατί είναι σημαντικό*: Η μέθοδος `Directory.CreateDirectory` είναι ιδεομετρική — δημιουργεί το φάκελο μόνο εάν δεν υπάρχει ήδη, αποφεύγοντας εξαιρέσεις σε επόμενες εκτελέσεις. + +## Βήμα 3: Διαμόρφωση κοινών διαστάσεων barcode + +Ο καθορισμός της διάστασης X (πλάτος ενός μεμονωμένου ράβδου) και του συνολικού ύψους της ράβδου σας επιτρέπει να ελέγξετε το οπτικό μέγεθος της παραγόμενης εικόνας. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Πώς να ορίσετε τις διαστάσεις του barcode**: Η ιδιότητα `Parameters.Barcode.XDimension.Pixels` ορίζει το πλάτος της στενής ράβδου, ενώ η `Parameters.Barcode.BarHeight.Pixels` ορίζει το πλήρες ύψος. Προσαρμόστε αυτές τις τιμές ώστε να ανταποκρίνονται στις προδιαγραφές της υπηρεσίας ταχυδρομείου σας. + +## Βήμα 4: Δημιουργία Planet barcode + +Το Planet είναι ένα ευρέως χρησιμοποιούμενο ταχυδρομικό barcode στο Ηνωμένο Βασίλειο. Ο παρακάτω κώδικας δημιουργεί ένα Planet barcode ύψους 100 px και το αποθηκεύει ως PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Γιατί λειτουργεί**: Η τιμή `EncodeTypes.Planet` λέει στον γεννήτρια να χρησιμοποιήσει τη συμβολική γραφική παράσταση Planet. Η μέθοδος `Save` γράφει ένα αρχείο PNG στη συγκεκριμένη διαδρομή, διατηρώντας τις διαστάσεις που ορίσαμε νωρίτερα. + +## Βήμα 5: Δημιουργία RM4SCC barcode + +Το RM4SCC είναι το ολλανδικό πρότυπο ταχυδρομικού barcode. Ο παρακάτω κώδικας αντικατοπτρίζει το παράδειγμα Planet, δείχνοντας **πώς να δημιουργήσετε ταχυδρομικό barcode** διαφορετικού τύπου με ίδιες διαστάσεις. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Και τα δύο αρχεία PNG βρίσκονται τώρα στον φάκελο `Barcodes`. Ανοίγοντας τα θα δείτε καθαρά, 100 px‑υψούς barcodes έτοιμα για εκτύπωση ή ενσωμάτωση σε έγγραφα. + +## Πλήρης κώδικας προγράμματος + +Παρακάτω βρίσκεται το πλήρες, εκτελέσιμο πρόγραμμα που **δημιουργεί εικόνες ταχυδρομικού barcode** για τα πρότυπα Planet και RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Αναμενόμενο αποτέλεσμα + +Η εκτέλεση του προγράμματος εκτυπώνει τις διαδρομές των αρχείων και δημιουργεί δύο αρχεία PNG: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Κάθε εικόνα έχει ύψος 100 px, με πλάτος στενής ράβδου 4 pixel, ταιριάζοντας με τις διαστάσεις που ορίσαμε. + +## Πρακτικές συμβουλές και συχνές παγίδες + +* **Δικαιώματα φακέλου** – Εάν το πρόγραμμα εκτελείται με περιορισμένο λογαριασμό, βεβαιωθείτε ότι ο προορισμός φακέλου είναι εγγράψιμος. +* **Διαφορετικές διαστάσεις** – Για να δημιουργήσετε ένα ψηλότερο barcode, αυξήστε το `barHeightPixels`. Για πιο λεπτή ανάλυση, μειώστε το `xDimensionPixels`, αλλά διατηρήστε το ≥ 2 ώστε να αποφύγετε εφέ απόδοσης. +* **Άλλες ταχυδρομικές συμβολές** – Η Aspose.BarCode υποστηρίζει επίσης `EncodeTypes.Postnet` και `EncodeTypes.AustralianPost`. Αλλάξτε την τιμή του `EncodeTypes` και διατηρήστε την ίδια λογική διαστάσεων. +* **Μορφή εικόνας** – Χρησιμοποιήστε `BarCodeImageFormat.Jpeg` για μικρότερο μέγεθος αρχείου όταν δεν απαιτείται απώλεια ποιότητας. + +## Συμπέρασμα + +Τώρα ξέρετε πώς να **δημιουργήσετε εικόνες ταχυδρομικού barcode** σε C# ρυθμίζοντας τις διαστάσεις, επιλέγοντας τη σωστή συμβολική γραφική παράσταση και αποθηκεύοντας το αποτέλεσμα ως PNG. Ο οδηγός κάλυψε **πώς να δημιουργήσετε ταχυδρομικό barcode**, έδειξε **πώς να δημιουργήσετε Planet barcode** και εξήγησε **πώς να ορίσετε τις διαστάσεις του barcode** για συνεπή έξοδο. + +Στη συνέχεια, εξερευνήστε **προσαρμογή χρωμάτων barcode**, προσθήκη **κείμενου αναγνώσιμου από άνθρωπο**, ή ενσωμάτωση των εικόνων σε τιμολόγια PDF. Το ίδιο μοτίβο ισχύει για οποιονδήποτε άλλο τύπο barcode που υποστηρίζεται από την Aspose.BarCode, επιτρέποντάς σας να επεκτείνετε αυτή τη λύση σε μια πλήρη ροή αυτοματοποίησης ταχυδρομικών διαδικασιών. + +## Τι Θα Πρέπει Να Μάθετε Στη Σειρά; + +- [Πώς να Δημιουργήσετε Barcode - Μονοδιάστατοι Τύποι Barcode](/barcode/english/net/one-dimensional-barcode-types/) +- [Πώς να δημιουργήσετε Aztec barcode με προσαρμοσμένη αναλογία διαστάσεων χρησιμοποιώντας Aspose.BarCode για .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Πώς να δημιουργήσετε barcode java – Australia Post Barcode με Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/greek/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..1da8dd96a --- /dev/null +++ b/barcode/greek/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-08-03 +description: Πώς να αποθηκεύσετε barcode σε C# με ένα βήμα‑βήμα παράδειγμα δημιουργίας + barcode. Μάθετε να δημιουργείτε Planet barcode, να ορίζετε διαστάσεις και να εξάγετε + εικόνες PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: el +lastmod: 2026-08-03 +og_description: Πώς να αποθηκεύσετε γραμμωτό κώδικα σε C# χρησιμοποιώντας ένα παράδειγμα + γεννήτριας γραμμωτού κώδικα. Αυτό το σεμινάριο δείχνει πώς να δημιουργήσετε γραμμωτούς + κώδικες Planet, να ρυθμίσετε τη διάσταση X και να εξάγετε αρχεία PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Πώς να αποθηκεύσετε γραμμωτό κώδικα σε C# – βήμα‑βήμα οδηγός +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Πώς να αποθηκεύσετε γραμμωτό κώδικα σε C# – πλήρης οδηγός δημιουργίας γραμμωτού + κώδικα +url: /el/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να αποθηκεύσετε barcode σε C# – πλήρης οδηγός δημιουργού barcode + +Η αποθήκευση εικόνων barcode σε C# είναι μια συνηθισμένη απαίτηση όταν χρειάζεται να ενσωματώσετε ταχυδρομικά barcode σε τιμολόγια, ετικέτες αποστολής ή ετικέτες αποθεμάτων. Αυτός ο οδηγός σας καθοδηγεί μέσα από μια πρακτική **c# barcode generator** ροή εργασίας, από τη δημιουργία ενός Planet barcode μέχρι την εξαγωγή τόσο των αρχείων PNG με γεμιστές γραμμές όσο και των αρχείων PNG με κενές γραμμές. + +Θα μάθετε πώς να ορίσετε το πλάτος των γραμμών, να εναλλάξετε τις γεμιστές γραμμές και να διαχειριστείτε αξιόπιστα τους φακέλους εξόδου. Στο τέλος του tutorial θα έχετε ένα πλήρως λειτουργικό **barcode generator example** που μπορείτε να αντιγράψετε σε οποιοδήποτε έργο .NET. + +## Τι θα χρειαστείτε + +- .NET 6.0 SDK ή νεότερο (το παράδειγμα λειτουργεί με .NET Core και .NET Framework) +- Visual Studio 2022 ή οποιοδήποτε IDE συμβατό με C# +- Το πακέτο NuGet **Aspose.BarCode** (ή άλλη βιβλιοθήκη που υποστηρίζει `EncodeTypes.Planet`). Εγκαταστήστε το με: + +```bash +dotnet add package Aspose.BarCode +``` + +Η βιβλιοθήκη παρέχει την κλάση `BarcodeGenerator` που χρησιμοποιείται σε όλο αυτό το tutorial. + +## Ρύθμιση του περιβάλλοντος ανάπτυξης + +Δημιουργήστε ένα νέο έργο console και προσθέστε το απαιτούμενο namespace: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +Το namespace `System.IO` μας παρέχει τη μέθοδο `Directory.CreateDirectory`, η οποία εξασφαλίζει ότι ο φάκελος εξόδου υπάρχει πριν προσπαθήσουμε να γράψουμε αρχεία. + +## Πώς να αποθηκεύσετε εικόνες barcode με το C# barcode generator + +Ο πυρήνας της λύσης είναι ένα μικρό σύνολο βημάτων που διαμορφώνουν ένα **Planet barcode** και στη συνέχεια αποθηκεύουν την εικόνα στο δίσκο. Οι παρακάτω ενότητες χωρίζουν τη διαδικασία σε διαχειρίσιμα κομμάτια. + +### Βήμα 1: Ορισμός του φακέλου εξόδου + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Γιατί;** +Η σκληρή κωδικοποίηση μιας διαδρομής μπορεί να προκαλέσει `DirectoryNotFoundException` σε μηχανές όπου ο φάκελος δεν υπάρχει. Η `CreateDirectory` είναι ιδεομετρική — δημιουργεί τον φάκελο μόνο αν λείπει, κάνοντας τον κώδικα ασφαλή για επαναλαμβανόμενες εκτελέσεις. + +### Βήμα 2: Δημιουργία ενός Planet barcode generator (γεμιστές γραμμές) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Γιατί;** +Η `EncodeTypes.Planet` λέει στη βιβλιοθήκη να παράγει ένα ταχυδρομικό Planet barcode, το οποίο χρησιμοποιείται ευρέως από τις υπηρεσίες ταχυδρομείου. Η συμβολοσειρά `"123456"` είναι το δείγμα φορτίου· αντικαταστήστε την με οποιαδήποτε αριθμητικά δεδομένα απαιτούνται από τη λογική της επιχείρησής σας. + +### Βήμα 3: Διαμόρφωση του πλάτους των γραμμών (X‑διάσταση) και διατήρηση των προεπιλεγμένων γεμιστών γραμμών + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Γιατί;** +Η X‑διάσταση ελέγχει το φυσικό πλάτος κάθε γραμμής. Μια τιμή `4` εικονοστοιχεία παράγει ένα αναγνώσιμο barcode σε τυπικούς εκτυπωτές 300 dpi. Η διατήρηση του `FilledBars` ως `true` (προεπιλογή) παράγει την κλασική εμφάνιση γεμιστών γραμμών. + +### Βήμα 4: Αποθήκευση της εικόνας barcode με γεμιστές γραμμές + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Γιατί;** +Η αποθήκευση ως PNG διατηρεί την απώλεια‑απαράλλακτη ποιότητα εικόνας, η οποία είναι σημαντική για την ακρίβεια σάρωσης. Η μέθοδος `Save` δημιουργεί αυτόματα το αρχείο εικόνας· χρειάζεται μόνο να παρέχετε τη πλήρη διαδρομή και τη μορφή που επιθυμείτε. + +### Βήμα 5: Δημιουργία δεύτερου generator για την έκδοση με κενές γραμμές + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Η δημιουργία μιας νέας στιγμής εξασφαλίζει ότι οι αλλαγές που γίνονται για την έκδοση με κενές γραμμές δεν επηρεάζουν την ήδη αποθηκευμένη εικόνα με γεμιστές γραμμές. + +### Βήμα 6: Απενεργοποίηση γεμιστών γραμμών διατηρώντας την ίδια X‑διάσταση + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Γιατί;** +Ο ορισμός `FilledBars = false` αποδίδει το barcode μόνο με το περίγραμμα κάθε γραμμής, κάτι που ορισμένα ταχυδρομικά πρότυπα απαιτούν για οπτική επαλήθευση. + +### Βήμα 7: Αποθήκευση της εικόνας barcode με κενές γραμμές + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Τώρα έχετε δύο αρχεία PNG — ένα με γεμιστές γραμμές και ένα με κενές γραμμές — έτοιμα για ενσωμάτωση σε PDF, HTML email ή εκτυπωμένες ετικέτες. + +## Πλήρες εκτελέσιμο πρόγραμμα + +Παρακάτω βρίσκεται ο πλήρης κώδικας που μπορείτε να αντιγράψετε στο `Program.cs`. Συγκεντρώνεται και εκτελείται χωρίς τροποποίηση (υπό την προϋπόθεση ότι το πακέτο Aspose.BarCode είναι εγκατεστημένο). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Αναμενόμενη έξοδος + +Η εκτέλεση του προγράμματος εκτυπώνει δύο γραμμές παρόμοιες με: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Ανοίξτε το φάκελο `Barcodes` και θα δείτε τα δύο αρχεία PNG. Και οι δύο εικόνες μπορούν να ανοιχτούν σε οποιονδήποτε προβολέα εικόνων ή να ενσωματωθούν απευθείας σε έγγραφα. + +![παράδειγμα αποθήκευσης barcode](barcode-example.png){: .align-center alt="παράδειγμα αποθήκευσης barcode"} + +## Συνηθισμένες παραλλαγές και ειδικές περιπτώσεις + +| Σενάριο | Προσαρμογή | +|----------|------------| +| **Διαφορετική μορφή εικόνας** | Αλλάξτε το `BarCodeImageFormat.Png` σε `Jpeg`, `Gif` ή `Bmp` όπως απαιτείται. | +| **Προσαρμοσμένο μέγεθος εξόδου** | Χρησιμοποιήστε `filled.Parameters.Image.Width` και `Height` για να επιβάλετε μια συγκεκριμένη διάσταση σε εικονοστοιχεία. | +| **Δυναμικά δεδομένα** | Αντικαταστήστε το στατικό `"123456"` με μια μεταβλητή που περιέχει αριθμούς παραγγελιών, IDs παρακολούθησης κ.λπ. | +| **Μη‑υπάρχων φάκελος** | `Directory.CreateDirectory` ήδη διαχειρίζεται τους ελλείποντες φακέλους· δεν απαιτείται επιπλέον κώδικας. | +| **Εκτύπωση υψηλής ανάλυσης** | Αυξήστε το `XDimension.Pixels` σε 6–8 για εκτυπωτές 600 dpi, αλλά ελέγξτε τη συμβατότητα του σαρωτή. | + +**Συμβουλή:** Εάν χρειάζεται να δημιουργήσετε πολλά barcode σε βρόχο, επαναχρησιμοποιήστε μια μόνο στιγμιότυπο `BarcodeGenerator` και αλλάξτε μόνο την ιδιότητα `CodeText` πριν από κάθε `Save`. Αυτό μειώνει το κόστος κατανομής αντικειμένων. + +## Πώς να δημιουργήσετε barcode για άλλα πρότυπα + +Το ίδιο μοτίβο λειτουργεί για άλλα `EncodeTypes` όπως `Code128`, `QR` ή `DataMatrix`. Απλώς αντικαταστήστε το `EncodeTypes.Planet` με τον επιθυμητό τύπο και προσαρμόστε τυχόν παραμέτρους ειδικές για τον τύπο (π.χ., `QRCodeVersion`). + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Πώς να αποθηκεύσετε PNG χρησιμοποιώντας DataMatrix C40 με Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Πώς να δημιουργήσετε DataMatrix Barcodes (ECC 200) με Aspose.BarCode για .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Πώς να δημιουργήσετε Barcode – Ρύθμιση Code 39 με Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/hindi/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..4babdcd16 --- /dev/null +++ b/barcode/hindi/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-08-03 +description: बारकोड जेनरेटर C# ट्यूटोरियल जिसमें Aspose.BarCode के साथ प्लैनेट बारकोड + बनाना, X‑डायमेंशन सेट करना, और PNG इमेजेज़ के रूप में सहेजना दिखाया गया है। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: hi +lastmod: 2026-08-03 +og_description: बारकोड जेनरेटर C# ट्यूटोरियल आपको प्लैनेट बारकोड बनाने, X‑डायमेंशन + को समायोजित करने और Aspose.BarCode का उपयोग करके PNG के रूप में सहेजने की प्रक्रिया + से परिचित कराता है। +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: बारकोड जेनरेटर C# – प्लैनेट बारकोड चरण‑दर‑चरण बनाएं +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: बारकोड जेनरेटर C# – Planet बारकोड और RM4SCC उदाहरण बनाएं +url: /hi/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – Planet बारकोड और RM4SCC उदाहरण बनाएं + +यदि आपको एक **barcode generator C#** चाहिए जो डाक‑विशिष्ट प्रतीक बना सके, तो यह गाइड आपको ठीक‑ठीक दिखाएगा कि Aspose.BarCode के साथ **Planet बारकोड** छवियां कैसे बनाएं। आप देखेंगे कि X‑dimension कैसे कॉन्फ़िगर करें, मिलते‑जुलते RM4SCC बारकोड कैसे जनरेट करें, और दोनों को PNG फ़ाइलों के रूप में कैसे सहेजें—सभी कुछ संक्षिप्त चरणों में। + +यह ट्यूटोरियल .NET 6 या बाद के संस्करण पर कोड चलाने के लिए आवश्यक सभी चीज़ें कवर करता है, प्रत्येक सेटिंग क्यों महत्वपूर्ण है समझाता है, और सामान्य समस्याओं जैसे गलत मॉड्यूल चौड़ाई या फ़ोल्डर अनुमतियों की कमी को उजागर करता है। अंत तक आपके पास दो प्रिंट‑तैयार बारकोड छवियां होंगी जो Planet और RM4SCC मानकों के अनुरूप होंगी। + +## पूर्वापेक्षाएँ + +* .NET 6 SDK (या Aspose.BarCode द्वारा समर्थित कोई भी .NET संस्करण) +* Visual Studio 2022 या आपका पसंदीदा C# IDE +* **Aspose.BarCode** का NuGet रेफ़रेंस (`Install-Package Aspose.BarCode`) +* उस फ़ोल्डर में लिखने की अनुमति जहाँ आप PNG फ़ाइलें संग्रहीत करने की योजना बना रहे हैं + +कोई अतिरिक्त बाहरी सेवा आवश्यक नहीं है; लाइब्रेरी सभी एन्कोडिंग स्थानीय रूप से संभालती है। + +## चरण 1: barcode generator C# ऑब्जेक्ट को प्रारंभ करें + +पहला कार्य `BarcodeGenerator` का एक इंस्टेंस बनाना है। कंस्ट्रक्टर बारकोड सिम्बोलॉजी (`EncodeTypes.Planet`) और एन्कोड करने वाले डेटा को लेता है। + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*इस चरण का कारण?* +`BarcodeGenerator` प्रत्येक बारकोड को जनरेट करने का एंट्री पॉइंट है। `EncodeTypes.Planet` चुनने से लाइब्रेरी को कई डाक सेवाओं द्वारा उपयोग किए जाने वाले ISO/IEC 24723 स्पेसिफिकेशन का पालन करने का निर्देश मिलता है। + +## चरण 2: Planet बारकोड के लिए X‑dimension (मॉड्यूल चौड़ाई) सेट करें + +X‑dimension एकल बारकोड मॉड्यूल (सबसे छोटा बार या स्पेस) की चौड़ाई निर्धारित करता है। अधिकांश लेबल प्रिंटरों के लिए **4 पिक्सेल** का मान उपयुक्त रहता है। + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*यह क्यों महत्वपूर्ण है* +यदि मॉड्यूल बहुत संकरी हो, तो बारकोड पढ़ने योग्य नहीं रहेगा; बहुत चौड़ी होने पर लेबल का आकार अनावश्यक रूप से बढ़ जाएगा। `Pixels` को समायोजित करके आप अपने प्रिंटर की रिज़ॉल्यूशन के अनुसार बारकोड को बारीकी से ट्यून कर सकते हैं। + +## चरण 3: Planet बारकोड को PNG इमेज के रूप में सहेजें + +Aspose.BarCode चयनित सिम्बोलॉजी के आधार पर बारकोड की ऊँचाई स्वचालित रूप से गणना करता है, इसलिए आपको केवल फ़ाइल पाथ और फॉर्मेट निर्दिष्ट करना है। + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*टिप* +`YOUR_DIRECTORY` को अपने मशीन पर मौजूद पूर्ण या सापेक्ष पाथ से बदलें। यदि डायरेक्टरी मौजूद नहीं है, तो `Save` मेथड `DirectoryNotFoundException` फेंकेगा। + +**अपेक्षित आउटपुट** – एक PNG फ़ाइल जो नीचे दिखाए गए चित्र के समान दिखेगी (वास्तविक छवि यहाँ नहीं दिखाई गई है, लेकिन आप `123456` संख्यात्मक पेलोड वाला क्लासिक Planet बारकोड देखेंगे)। + +## चरण 4: RM4SCC बारकोड के लिए दूसरा जेनरेटर प्रारंभ करें + +कई डाक प्रणालियों को एक ही मेलपीस पर Planet और RM4SCC दोनों प्रतीकों की आवश्यकता होती है। RM4SCC सिम्बोलॉजी के लिए एक नया `BarcodeGenerator` इंस्टेंस बनाएं। + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*एक अलग इंस्टेंस क्यों?* +प्रत्येक सिम्बोलॉजी की अपनी सेटिंग्स होती हैं। वही जेनरेटर पुनः उपयोग करने से अनजाने में सेटिंग्स (जैसे X‑dimension) दूसरे बारकोड के लिए उपयुक्त नहीं रह सकतीं। + +## चरण 5: RM4SCC बारकोड के लिए X‑dimension कॉन्फ़िगर करें + +RM4SCC भी X‑dimension सेटिंग का सम्मान करता है, इसलिए दृश्य संगति के लिए हम वही पिक्सेल चौड़ाई लागू करते हैं। + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*प्रो टिप* +यदि आपको बड़े लेबलों के लिए ऊँचा बारकोड चाहिए (जैसे, बड़े लेबल), तो आप `Height.Pixels` भी सेट कर सकते हैं। इसे अनसेट छोड़ने पर लाइब्रेरी स्वचालित रूप से आदर्श ऊँचाई की गणना करती है। + +## चरण 6: RM4SCC बारकोड को PNG इमेज के रूप में सहेजें + +अंत में, RM4SCC बारकोड को डिस्क पर सहेजें। + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +अब आपके पास दो PNG फ़ाइलें—`PostalPlanetBarHeightNone.png` और `PostalRM4SCCBarHeightNone.png`—हैं, जिन्हें आप मेल लेबल में एम्बेड कर सकते हैं, लिफ़ाफ़ों पर प्रिंट कर सकते हैं, या थर्ड‑पार्टी प्रिंटिंग सेवा को भेज सकते हैं। + +## वैकल्पिक: ऊँचाई समायोजित करना या अन्य इमेज फॉर्मेट उपयोग करना + +यदि आपके वर्कफ़्लो को विशिष्ट बारकोड ऊँचाई या अलग इमेज फॉर्मेट (जैसे JPEG या BMP) चाहिए, तो `Save` कॉल करने से पहले पैरामीटर बदल सकते हैं: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**एज केस** – जब आप कस्टम ऊँचाई सेट करते हैं, तो सुनिश्चित करें कि मान ISO मानक द्वारा आवश्यक न्यूनतम ऊँचाई का सम्मान करता है; अन्यथा बारकोड वैधता में विफल हो सकता है। + +## सामान्य समस्याएँ और उन्हें कैसे रोकें + +| समस्या | क्यों होता है | समाधान | +|---------|----------------|-----| +| `DirectoryNotFoundException` | लक्ष्य फ़ोल्डर मौजूद नहीं है या नाम गलत लिखा गया है। | पहले फ़ोल्डर बनाएं या `Path.Combine` के साथ `Environment.CurrentDirectory` का उपयोग करें। | +| कम‑रिज़ॉल्यूशन प्रिंटरों पर बारकोड पढ़ने योग्य नहीं | X‑dimension प्रिंटर के DPI के लिए बहुत छोटा है। | 203 dpi प्रिंटरों के लिए `XDimension.Pixels` को 5 – 6 तक बढ़ाएँ, या नमूना लेबल के साथ परीक्षण करें। | +| गलत सिम्बोलॉजी उपयोग की गई | `EncodeTypes.Code128` पास किया गया बजाय `EncodeTypes.Planet` के। | `EncodeTypes` enum मान को आवश्यक डाक मानक से मेल खाता है, यह दोबारा जांचें। | +| `Parameters` पर Null रेफ़रेंस | Aspose.BarCode के पुराने संस्करण का उपयोग जहाँ API अलग है। | नवीनतम NuGet पैकेज (v23.12 या बाद) में अपग्रेड करें। | + +## पूर्ण चलाने योग्य उदाहरण + +नीचे पूरा प्रोग्राम दिया गया है जिसे आप कॉपी‑पेस्ट करके चला सकते हैं। इसमें `using` स्टेटमेंट्स, एरर हैंडलिंग, और प्रत्येक लाइन को समझाने वाले कमेंट्स शामिल हैं। + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +प्रोग्राम चलाने पर निष्पादन फ़ाइल के बगल में एक `Barcodes` फ़ोल्डर बनता है और दो PNG फ़ाइलें उसमें रखी जाती हैं। किसी भी इमेज व्यूअर से खोलें और आउटपुट की जाँच करें। + +## निष्कर्ष + +अब आपके पास एक **barcode generator C#** समाधान है जो **Planet बारकोड** छवियां बना सकता है, इष्टतम प्रिंटिंग के लिए X‑dimension समायोजित कर सकता है, और मिलते‑जुलते RM4SCC बारकोड उत्पन्न कर सकता है—सिर्फ कुछ लाइनों के कोड से। यह तरीका .NET 6+ के साथ काम करता है, केवल Aspose.BarCode NuGet पैकेज की आवश्यकता होती है, और `EncodeTypes` मान बदलकर Code128, QR, या DataMatrix जैसी अन्य सिम्बोलॉजीज़ में विस्तारित किया जा सकता है। + +### आगे क्या करें? + +* अपने प्रिंटर के DPI से मेल खाने के लिए विभिन्न `XDimension.Pixels` मानों के साथ प्रयोग करें। +* `BarCodeImageFormat` enum बदलकर बारकोड को अन्य फॉर्मेट (PDF, SVG) में जनरेट करें। +* **SkiaSharp** जैसी ग्राफ़िक्स लाइब्रेरी का उपयोग करके दो PNG फ़ाइलों को एक ही लेबल में संयोजित करें। +* चेकसम वैलिडेशन या कस्टम फ़ॉन्ट जैसी उन्नत सुविधाओं के लिए पूरी Aspose.BarCode API का अन्वेषण करें। + +कोड को बैच प्रोसेसिंग के लिए अनुकूलित करने या ASP.NET Core वेब सर्विस में एकीकृत करने में संकोच न करें जो मांग पर बारकोड इमेजेज़ लौटाता है। हैप्पी कोडिंग! + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दर्शाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में निपुण हो सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोच का पता लगा सकें। + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/hindi/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..a7ef042db --- /dev/null +++ b/barcode/hindi/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-03 +description: बारकोड जेनरेटर C# ट्यूटोरियल दिखाता है कि Aspose.BarCode के साथ बारकोड + इमेज कैसे जनरेट करें, कॉलम और पंक्तियों को सेट करें, और DataBar Expanded Stacked + के लिए PNG फ़ाइलें सहेजें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: hi +lastmod: 2026-08-03 +og_description: बारकोड जेनरेटर C# ट्यूटोरियल बताता है कि Aspose.BarCode का उपयोग करके + बारकोड इमेज कैसे जनरेट करें, DataBar Expanded Stacked कॉलम और पंक्तियों को कॉन्फ़िगर + करें, और PNG फ़ाइलें सहेजें। +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: बारकोड जेनरेटर C# – बारकोड छवि बनाने के लिए चरण-दर-चरण गाइड +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: बारकोड जेनरेटर C# – बारकोड छवि उत्पन्न करें +url: /hi/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – बारकोड इमेज जनरेट करें + +यदि आपको DataBar Expanded Stacked के लिए बारकोड इमेज जनरेट करने वाला barcode generator C# चाहिए, तो यह गाइड आपको पूरी प्रक्रिया से गुजारता है। आप सीखेंगे कि कॉलम और रो सेटिंग्स कैसे कॉन्फ़िगर करें, परिणाम को PNG के रूप में सहेजें, और कोड को अन्य symbologies के लिए अनुकूलित करें। + +बारकोड इमेज को प्रोग्रामेटिकली जनरेट करने से मैन्युअल कदम हटते हैं और इनवॉइस, शिपिंग लेबल, और इन्वेंटरी सिस्टम्स में स्थिरता सुनिश्चित होती है। यह ट्यूटोरियल आपको प्रोजेक्ट सेटअप से लेकर पूर्ण सोर्स कोड तक सब कुछ प्रदान करता है, ताकि आप उदाहरण को तुरंत चला सकें। + +## आवश्यकताएँ + +* .NET 6.0 या बाद का संस्करण स्थापित हो +* Visual Studio 2022 जैसी IDE (कोई भी एडिटर जो C# को सपोर्ट करता हो) +* **Aspose.BarCode for .NET** के लिए लाइसेंस – परीक्षण के लिए मुफ्त इवैल्यूएशन काम करता है +* C# सिंटैक्स की बुनियादी परिचितता + +यदि इनमें से कोई भी आइटम गायब है, तो dotnet.microsoft.com से .NET SDK इंस्टॉल करें और Aspose.BarCode NuGet पैकेज प्राप्त करें: + +```bash +dotnet add package Aspose.BarCode +``` + +## चरण 1: barcode generator C# प्रोजेक्ट बनाएं + +एक नया कंसोल एप्लिकेशन बनाएं और आवश्यक `using` निर्देश जोड़ें: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +`BarcodeGenerator` क्लास barcode generator C# API का कोर है। यह symbology प्रकार और एन्कोड करने के लिए टेक्स्ट प्राप्त करता है। + +## चरण 2: DataBar Expanded Stacked बारकोड जनरेट करें और कॉलम सेट करें + +पहला उदाहरण चार कॉलम वाला बारकोड बनाता है। `Columns` प्रॉपर्टी को समायोजित करने से DataBar Expanded Stacked symbology की दृश्य घनत्व बदलती है। + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**यह क्यों महत्वपूर्ण है:** कॉलम संख्या यह निर्धारित करती है कि कितनी डेटा को कॉम्पैक्ट स्पेस में संग्रहीत किया जा सकता है। इसे 4 पर सेट करने से एक विस्तृत बारकोड बनता है जो अधिकांश स्कैनरों द्वारा पढ़ा जा सकता है। + +## चरण 3: कस्टम रो काउंट के साथ बारकोड जनरेट करें + +दूसरा उदाहरण दिखाता है कि `Rows` प्रॉपर्टी सेट करके वर्टिकल लेआउट को कैसे नियंत्रित किया जाए। तीन‑रो कॉन्फ़िगरेशन तब उपयोगी होता है जब सीमित हॉरिज़ॉन्टल स्पेस के लिए आपको ऊँचा बारकोड चाहिए। + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**यह क्यों महत्वपूर्ण है:** रो को समायोजित करने से आप बारकोड को संकीर्ण कॉलम में फिट कर सकते हैं जबकि पठनीयता बनी रहती है। barcode generator C# स्वचालित रूप से मॉड्यूल आकार को पुनः गणना करता है ताकि स्पेसिफिकेशन पूरा हो। + +## चरण 4: पूर्ण, चलाने योग्य उदाहरण + +नीचे एक स्व-निहित प्रोग्राम है जो पिछले चरणों को मिलाता है। कोड को `Program.cs` में कॉपी करें, `YOUR_DIRECTORY` को मौजूदा फ़ोल्डर पाथ से बदलें, और एप्लिकेशन चलाएँ। + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### अपेक्षित आउटपुट + +जब आप प्रोग्राम चलाते हैं, तो लक्ष्य डायरेक्टरी में दो PNG फ़ाइलें दिखाई देती हैं: + +* **DatabarCols4.png** – चार कॉलम वाला DataBar Expanded Stacked बारकोड +* **DatabarRows3.png** – वही डेटा तीन रो में एन्कोड किया गया + +इन्हें किसी भी इमेज व्यूअर से खोलें; ये तेज़, स्कैन करने योग्य बारकोड दिखाते हैं जो प्रिंटिंग या PDFs में एम्बेड करने के लिए तैयार हैं। + +## कस्टम डाइमेंशन्स के साथ बारकोड इमेज कैसे जनरेट करें + +यदि आपको विशिष्ट इमेज साइज चाहिए, तो `Save` कॉल करने से पहले `ImageHeight` और `ImageWidth` प्रॉपर्टी को समायोजित करें: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +डाइमेंशन्स बदलने से एन्कोडेड डेटा पर असर नहीं पड़ता; यह केवल विज़ुअल रिप्रेज़ेंटेशन को स्केल करता है। यह तकनीक तब उपयोगी होती है जब बारकोड को फिक्स्ड लेआउट कंस्ट्रेंट्स वाले UI कंपोनेंट्स में इंटीग्रेट किया जाता है। + +## सामान्य pitfalls और प्रो टिप्स + +* **Path separators:** Windows पर escape‑character समस्याओं से बचने के लिए verbatim strings (`@"C:\Path\file.png"`) या `Path.Combine` का उपयोग करें। +* **License enforcement:** वैध लाइसेंस के बिना, जनरेट की गई इमेज में वॉटरमार्क रहता है। एप्लिकेशन में जल्दी लाइसेंस लागू करें: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Encoding limits:** DataBar Expanded Stacked अधिकतम 74 न्यूमेरिक कैरेक्टर्स को सपोर्ट करता है। इस सीमा से अधिक करने पर एक्सेप्शन फेंका जाता है। जेनरेटर बनाने से पहले इनपुट की लंबाई वैलिडेट करें। +* **Performance:** कई सेव्स के लिए एक ही `BarcodeGenerator` इंस्टेंस को पुन: उपयोग करने से मेमोरी अलोकेशन कम होती है। यदि एन्कोडेड टेक्स्ट वही रहता है तो सेव्स के बीच केवल `Rows` या `Columns` प्रॉपर्टी बदलें। + +## अगले कदम + +अब जब आप barcode generator C# से बारकोड इमेज जनरेट कर सकते हैं, तो निम्नलिखित को एक्सप्लोर करने पर विचार करें: + +* **Different symbologies** – `EncodeTypes.QR`, `EncodeTypes.Code128`, या `EncodeTypes.Pdf417` आज़माएँ। +* **Color customization** – ब्रांडिंग से मेल खाने के लिए `Parameters.Barcode.ForeColor` और `BackColor` सेट करें। +* **Embedding in PDFs** – जनरेट किए गए PNG को Aspose.PDF के साथ मिलाकर प्रिंटेबल डॉक्यूमेंट बनाएं। + +ये एक्सटेंशन आपको इन्वेंटरी, लॉजिस्टिक्स, या रिटेल एप्लिकेशन्स के लिए पूर्ण‑फ़ीचर बारकोड समाधान बनाने में मदद करते हैं। + +--- + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन निकट संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर करने में मदद करती हैं। + +- [बारकोड इमेज जनरेट करें – GS1 कूपन UPC-A डेटाबार](/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 के साथ DataMatrix बारकोड (ECC 200) कैसे जनरेट करें](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/hindi/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..0d11dda77 --- /dev/null +++ b/barcode/hindi/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-08-03 +description: C# में बारकोड जेनरेटर का उदाहरण, जिसमें चौड़ाई सेट करना, ऊँचाई बदलना + और बारकोड इमेज बनाना दिखाया गया है। चरण‑दर‑चरण निर्देशों का पालन करें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: hi +lastmod: 2026-08-03 +og_description: बारकोड जेनरेटर उदाहरण X‑डायमेंशन की चौड़ाई सेट करने, बार की ऊँचाई + बदलने और C# में बारकोड छवि उत्पन्न करने को दर्शाता है। PNG फ़ाइलें बनाने के लिए + चरणों का पालन करें। +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: बारकोड जनरेटर उदाहरण – C# चौड़ाई और ऊँचाई गाइड +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: C# में बारकोड जेनरेटर का उदाहरण – चौड़ाई और ऊँचाई सेट करें +url: /hi/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में बारकोड जेनरेटर उदाहरण – चौड़ाई और ऊँचाई सेट करें + +यदि आपको C# में **बारकोड जेनरेटर उदाहरण** चाहिए, तो यह गाइड आपको X‑डायमेंशन चौड़ाई कैसे सेट करें, बार की ऊँचाई कैसे बदलें, और बारकोड इमेज फ़ाइल कैसे जेनरेट करें, दिखाता है। आप एक पूर्ण, चलाने योग्य प्रोग्राम देखेंगे जो दो PNG फ़ाइलें विभिन्न ऊँचाइयों के साथ बनाता है। + +एक सामान्य परिदृश्य उत्पाद लेबल बनाना है जहाँ बारकोड का आकार स्कैनर की विशिष्टताओं को पूरा करना चाहिए। इस ट्यूटोरियल के अंत तक आप प्रोग्रामेटिक रूप से चौड़ाई और ऊँचाई पैरामीटर को समायोजित कर सकेंगे और परिणाम को PNG इमेज के रूप में सहेज सकेंगे। + +## आवश्यकताएँ + +शुरू करने से पहले सुनिश्चित करें कि आपके पास हैं: + +* .NET 6 (या बाद का) स्थापित – कोड .NET 6 SDK को टार्गेट करता है। +* एक बारकोड लाइब्रेरी जो `EncodeTypes.DatabarOmniDirectional` को सपोर्ट करती हो। उदाहरण में **Aspose.BarCode for .NET** का उपयोग किया गया है, लेकिन कोई भी लाइब्रेरी जो समान प्रॉपर्टीज़ प्रदान करती है, उसी तरह काम करेगी। +* एक IDE या एडिटर (Visual Studio, VS Code, Rider) जिससे प्रोग्राम को कंपाइल और रन किया जा सके। +* उस डायरेक्टरी में लिखने की अनुमति जहाँ PNG फ़ाइलें सहेजी जाएँगी। + +> **Pro tip:** अपने प्रोजेक्ट रूट में `Barcodes` नाम का फ़ोल्डर बनाएँ और इसे `Path.Combine` के साथ रेफ़रेंस करें ताकि एब्सोल्यूट पाथ हार्ड‑कोडिंग से बचा जा सके। + +## बारकोड जेनरेटर उदाहरण: इनिशियलाइज़ और कॉन्फ़िगर करें + +पहला कदम है `BarcodeGenerator` इंस्टेंस को इच्छित सिम्बोलॉजी और डेटा स्ट्रिंग के साथ बनाना। + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +`EncodeTypes.DatabarOmniDirectional` एन्‍यूम Databar Omni‑directional सिम्बोलॉजी चुनता है, और GS1‑फ़ॉर्मेटेड डेटा स्ट्रिंग `(01)12345678901231` एक सामान्य GTIN‑14 वैल्यू को दर्शाता है। जेनरेटर को एक बार इनिशियलाइज़ करने से आप एक ही ऑब्जेक्ट को कई इमेज के लिए पुनः उपयोग कर सकते हैं। + +## चौड़ाई (X‑डायमेंशन) कैसे सेट करें + +X‑डायमेंशन बारकोड की मॉड्यूल चौड़ाई को नियंत्रित करता है। इसे 2 पिक्सेल सेट करने से प्रत्येक संकीर्ण बार 2 पिक्सेल चौड़ा हो जाता है, जो हाई‑डेंसिटी प्रिंटिंग के लिए सामान्य आवश्यकता है। + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +क्यों महत्वपूर्ण है: यदि चौड़ाई बहुत छोटी होगी, तो स्कैनर व्यक्तिगत बार को पहचान नहीं पाएगा; यदि बहुत बड़ी होगी, तो बारकोड लेबल की जगह से बाहर हो सकता है। प्रिंटर DPI और लक्षित लेबल आकार के अनुसार पिक्सेल वैल्यू को समायोजित करें। + +## ऊँचाई कैसे बदलें + +बार की ऊँचाई निर्धारित करती है कि बार कितने ऊँचे दिखेंगे। उदाहरण दो इमेज बनाता है: एक 30‑पिक्सेल ऊँचाई के साथ और दूसरी 60‑पिक्सेल ऊँचाई के साथ। + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +`BarHeight.Pixels` प्रॉपर्टी सीधे बार की दृश्य ऊँचाई को प्रभावित करती है। इसे सेव्स के बीच बदलने से आप एक ही डेटा पेलोड से कई वैरिएंट जेनरेट कर सकते हैं बिना जेनरेटर को फिर से बनाये। + +### अपेक्षित आउटपुट + +प्रोग्राम चलाने पर `Barcodes` फ़ोल्डर में दो PNG फ़ाइलें बनती हैं: + +* `DatabarBarHeight30Pixels.png` – बार 30 पिक्सेल ऊँचे हैं। +* `DatabarBarHeight60Pixels.png` – बार 60 पिक्सेल ऊँचे हैं। + +दोनों इमेज की चौड़ाई (X‑डायमेंशन द्वारा निर्धारित) समान है और समान GTIN‑14 डेटा को एन्कोड करती हैं। + +![C# कोड द्वारा विभिन्न ऊँचाइयों के साथ जेनरेट की गई दो बारकोड PNG फ़ाइलें](barcode-example.png "बारकोड जेनरेटर उदाहरण जिसमें ऊँचाई के विविधताएँ दिखायी गई हैं") + +*ऊपर की इमेज का alt टेक्स्ट एक्सेसिबिलिटी और SEO के लिए मुख्य कीवर्ड शामिल करता है।* + +## C# में बारकोड इमेज कैसे जेनरेट करें + +`Save` मेथड बारकोड डेटा को इमेज फ़ाइल में बदलने का काम करता है। आप एक अलग `BarCodeImageFormat` एन्‍यूम वैल्यू पास करके अन्य फ़ॉर्मेट (JPEG, BMP, SVG) चुन सकते हैं। उदाहरण में PNG का उपयोग किया गया है क्योंकि यह लॉसलेस क्वालिटी को बनाए रखता है और व्यापक रूप से सपोर्टेड है। + +यदि आपको बारकोड को सीधे PDF या वेब पेज में एम्बेड करना है, तो इमेज को `byte[]` के रूप में प्राप्त करें: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +यह तरीका टेम्पररी फ़ाइलों की आवश्यकता को समाप्त करता है और हाई‑थ्रूपुट सर्विसेज़ के लिए उपयोगी है। + +## सामान्य वैरिएशन और एज केस + +| स्थिति | समायोजन | +|-----------|------------| +| **विभिन्न सिम्बोलॉजी** | `EncodeTypes.DatabarOmniDirectional` को किसी अन्य एन्‍यूम वैल्यू (जैसे `EncodeTypes.Code128`) से बदलें। | +| **बहुत छोटे लेबल** | `XDimension.Pixels` को 1 पिक्सेल तक घटाएँ, लेकिन स्कैनर रीडेबिलिटी की जाँच करें। | +| **हाई‑रेज़ोल्यूशन प्रिंटिंग** | X‑डायमेंशन और बार ऊँचाई दोनों को अनुपातिक रूप से बढ़ाएँ (उदाहरण: 4 px चौड़ाई, 80 px ऊँचाई)। | +| **डायनामिक डेटा** | डेटा स्ट्रिंग को रनटाइम पर पास करें, संभवतः डेटाबेस रिकॉर्ड से। | +| **बैच जेनरेशन** | डेटा स्ट्रिंग्स के कलेक्शन पर लूप चलाएँ, `generator.Text` को अपडेट करते हुए वही `BarcodeGenerator` इंस्टेंस पुनः उपयोग करें। | + +जब आपको `ArgumentOutOfRangeException` जैसी अपवाद मिले, तो दोबारा जाँचें कि पिक्सेल वैल्यू सकारात्मक पूर्णांक हैं और आउटपुट डायरेक्टरी मौजूद है। + +## पूर्ण स्रोत कोड सारांश + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +कोड को एक नए कंसोल प्रोजेक्ट में कॉपी करें, Aspose.BarCode NuGet पैकेज (`dotnet add package Aspose.BarCode`) रिस्टोर करें, और `dotnet run` चलाएँ। आपको कंसोल में सहेजी गई फ़ाइलों की पुष्टि करने वाले संदेश दिखेंगे। + +## निष्कर्ष + +यह **बारकोड जेनरेटर उदाहरण** दिखाता है कि कैसे चौड़ाई सेट करें, ऊँचाई बदलें, और C# में बारकोड इमेज जेनरेट करें। `XDimension.Pixels` और `BarHeight.Pixels` को समायोजित करके आप बारकोड के विज़ुअल साइज को नियंत्रित कर सकते हैं, और `Save` मेथड परिणाम को PNG फ़ाइलों में लिखता है। विभिन्न सिम्बोलॉजी, आउटपुट फ़ॉर्मेट, और डेटा स्ट्रिंग्स के साथ प्रयोग करें ताकि आपके एप्लिकेशन की आवश्यकताओं को पूरा किया जा सके। + +**अगले कदम** + +* अन्य इमेज फ़ॉर्मेट (SVG, JPEG) में **बारकोड जेनरेट** करने के तरीकों का अन्वेषण करें, जो वेब उपयोग के लिए उपयुक्त हों। +* ASP.NET Core एंडपॉइंट्स के लिए **create barcode image c#** सीखें, जो PNG को सीधे ब्राउज़र में रिटर्न करता है। +* इस कोड को PDF जेनरेशन लाइब्रेरी के साथ मिलाकर इनवॉइस या शिपिंग लेबल में बारकोड एम्बेड करें। + +नमूना को अनुकूलित करने, अपने परिणाम साझा करने, या कमेंट्स में प्रश्न पूछने में संकोच न करें। हैप्पी कोडिंग! + +## आप अगला क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर करने में मदद करेंगे। + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to Set Border for ITF-14 Barcode Customization](/barcode/english/net/itf-14-barcode-customization/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/hindi/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..00d26d801 --- /dev/null +++ b/barcode/hindi/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-08-03 +description: C# में बारकोड PNG बनाएं और DataBar इमेजेज़ के लिए आस्पेक्ट रेशियो बदलना + सीखें। कोड और टिप्स के साथ इस पूर्ण उदाहरण का पालन करें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: hi +lastmod: 2026-08-03 +og_description: C# में बारकोड PNG बनाएं और DataBar बारकोड के लिए आस्पेक्ट रेशियो कैसे + बदलें देखें। यह गाइड आपको तैयार‑से‑चलाने वाला कोड और व्यावहारिक टिप्स देता है। +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: C# में बारकोड PNG बनाएं – आस्पेक्ट‑रेशियो नियंत्रण के साथ पूर्ण उदाहरण +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: C# में बारकोड PNG बनाएं – चरण‑दर‑चरण मार्गदर्शिका +url: /hi/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में बारकोड PNG बनाएं – चरण‑दर‑चरण गाइड + +यदि आपको C# में **बारकोड PNG बनाना** है, तो यह ट्यूटोरियल आपको बिल्कुल बताता है कि कैसे। आप एक stacked omnidirectional DataBar बारकोड जेनरेट करेंगे, इसे PNG फ़ाइल के रूप में सहेजेंगे, और विभिन्न स्कैनिंग पर्यावरणों के अनुरूप **aspect ratio बदलने का तरीका** सीखेंगे। + +यह गाइड वह सब कवर करता है जिसकी आपको आवश्यकता है: आवश्यक पैकेज, एक पूर्ण, चलाने योग्य प्रोग्राम, और यह समझाने के लिए कि प्रत्येक सेटिंग क्यों महत्वपूर्ण है। अंत तक आपके पास दो PNG फ़ाइलें होंगी—एक aspect ratio 15 के साथ और दूसरी 30 के साथ—जो परीक्षण या प्रोडक्शन उपयोग के लिए तैयार होंगी। + +## पूर्वापेक्षाएँ + +शुरू करने से पहले सुनिश्चित करें कि आपके पास निम्नलिखित हों: + +- .NET 6.0 SDK या बाद का संस्करण स्थापित हो +- Visual Studio 2022 (या कोई भी C# IDE) +- **Aspose.BarCode** का NuGet रेफ़रेंस (लाइब्रेरी जो `BarcodeGenerator` प्रदान करती है) +- PNG फ़ाइलें जहाँ सहेजी जाएँगी, उस डायरेक्टरी में लिखने की अनुमति + +आप निम्नलिखित कमांड के साथ Aspose.BarCode पैकेज जोड़ सकते हैं: + +```bash +dotnet add package Aspose.BarCode +``` + +## चरण 1: प्रोजेक्ट सेट अप करें और नेमस्पेस इम्पोर्ट करें + +एक नया कंसोल एप्लिकेशन बनाएं और बारकोड जेनरेशन तथा फ़ाइल I/O के लिए आवश्यक नेमस्पेस इम्पोर्ट करें। + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Why this matters:** `Aspose.BarCode.Generation` को इम्पोर्ट करने से आपको `BarcodeGenerator` तक पहुँच मिलती है। कोड को `Main` के भीतर रखकर उदाहरण स्व‑निर्भर और चलाने में आसान बनता है। + +## चरण 2: stacked omnidirectional DataBar के लिए बारकोड जेनरेटर बनाएं + +`EncodeTypes.DatabarStackedOmniDirectional` प्रकार और एक नमूना GS1‑128 डेटा स्ट्रिंग के साथ `BarcodeGenerator` को इंस्टैंशिएट करें। + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Why this matters:** चुना गया encode type एक high‑density DataBar बनाता है जिसे अधिकांश आधुनिक स्कैनर पढ़ सकते हैं। डेटा स्ट्रिंग GS1 Application Identifier (01) फ़ॉर्मेट का पालन करती है, जो प्रोडक्ट आइडेंटिफ़ायर के लिए सामान्य है। + +## चरण 3: X‑dimension (मॉड्यूल चौड़ाई) को पिक्सेल में परिभाषित करें + +मॉड्यूल चौड़ाई सेट करें ताकि बारकोड का कुल आकार नियंत्रित हो सके, बिना उसकी पठनीयता को प्रभावित किए। + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Why this matters:** 2 पिक्सेल की X‑dimension एक ऐसा बारकोड देती है जो स्कैनरों के लिए न तो बहुत छोटा है और न ही लेबल स्पेस के लिए बहुत बड़ा। + +## चरण 4: aspect ratio 15 के साथ पहला PNG सहेजें + +DataBar aspect ratio को समायोजित करें, फिर इमेज को PNG फ़ाइल के रूप में सहेजें। + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Why this matters:** aspect ratio stacked DataBar की height‑to‑width संबंध को नियंत्रित करता है। 15 का अनुपात एक सामान्य डिफ़ॉल्ट है जो पठनीयता और लेबल ऊँचाई के बीच संतुलन बनाता है। + +## चरण 5: aspect ratio 30 में बदलें और दूसरा PNG सहेजें + +उसी जेनरेटर इंस्टेंस को बड़े aspect ratio का उपयोग करने के लिए संशोधित करें, फिर दूसरी इमेज सहेजें। + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Why this matters:** aspect ratio बढ़ाने से बारकोड ऊर्ध्वाधर रूप से फैलता है, जिससे कम‑रिज़ॉल्यूशन डिवाइस या संकरी मीडिया पर लेबल प्रिंट होने पर स्कैन विश्वसनीयता सुधर सकती है। + +## अपेक्षित आउटपुट + +प्रोग्राम चलाने से दो PNG फ़ाइलें बनती हैं: + +| फ़ाइल | Aspect Ratio | लगभग आयाम (पिक्सेल) | +|------------------------------------|--------------|----------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (width × height) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (width × height) | + +दोनों इमेज में एक स्पष्ट, स्कैन करने योग्य DataBar बारकोड होता है जो GS1 पहचानकर्ता `(01)12345678901231` को एन्कोड करता है। + +## सामान्य प्रश्न और किनारे के मामलों + +### अन्य दृश्य गुण कैसे बदलें? + +आप `generator.Parameters.Barcode` ऑब्जेक्ट के माध्यम से फ़ोरग्राउंड रंग, बैकग्राउंड रंग, या ह्यूमन‑रीडेबल टेक्स्ट को समायोजित कर सकते हैं। उदाहरण के लिए: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### यदि मुझे अलग इमेज फ़ॉर्मेट चाहिए तो? + +आवश्यकतानुसार `BarCodeImageFormat.Png` को `Jpeg`, `Bmp`, या `Gif` से बदलें। PNG लॉसलेस बारकोड इमेज के लिए सबसे अच्छा विकल्प बना रहता है। + +### क्या aspect ratio स्कैनिंग गति को प्रभावित करता है? + +उच्च aspect ratios बारकोड की ऊँचाई बढ़ाते हैं, जिससे छोटे stacked सिम्बॉल वाले डिवाइस पर स्कैन विश्वसनीयता सुधर सकती है। हालांकि, अत्यधिक ऊँचे बारकोड छोटे लेबल पर फिट नहीं हो सकते, इसलिए अपने टार्गेट हार्डवेयर के साथ परीक्षण करें। + +### क्या मैं लूप में कई बारकोड जेनरेट कर सकता हूँ? + +हां। प्रत्येक डेटा स्ट्रिंग के लिए नया `BarcodeGenerator` इंस्टेंस बनाएं या `CodeText` और `DataBar.AspectRatio` को अपडेट करते हुए उसी इंस्टेंस को पुन: उपयोग करें। यह तरीका ऑब्जेक्ट अलोकेशन ओवरहेड को कम करता है। + +## प्रो टिप्स + +- **Reuse the generator**: केवल `CodeText` या `AspectRatio` को बदलने से ऑब्जेक्ट को पुनः‑इंस्टैंशिएट करने से बचा जा सकता है, जिससे बैच प्रोसेसिंग तेज़ होती है। +- **Validate the output**: प्रोडक्शन में डिप्लॉय करने से पहले किसी हैंडहेल्ड स्कैनर या मोबाइल ऐप से जाँचें कि जेनरेट किया गया PNG सही पढ़ा जा रहा है या नहीं। +- **File naming**: फ़ाइल नाम में aspect ratio शामिल करें (जैसा कि दिखाया गया है) ताकि परीक्षण के दौरान विभिन्नताओं को ट्रैक किया जा सके। + +## निष्कर्ष + +अब आप जानते हैं कि C# में **बारकोड PNG** फ़ाइलें कैसे बनाएं और stacked omnidirectional DataBar सिम्बॉल के लिए **aspect ratio कैसे बदलें**। पूरा उदाहरण इनिशियलाइज़ेशन, X‑dimension सेटिंग, aspect‑ratio मैनिपुलेशन, और इमेज सेविंग को एक ही चलाने योग्य प्रोग्राम में दर्शाता है। + +अब आप अतिरिक्त बारकोड प्रकारों का अन्वेषण कर सकते हैं, रंगों के साथ प्रयोग कर सकते हैं, या जेनरेटर को बड़े रिपोर्टिंग या इन्वेंटरी सिस्टम में इंटीग्रेट कर सकते हैं। हैप्पी कोडिंग! + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट में वैकल्पिक इम्प्लीमेंटेशन अप्रोच का पता लगा सकें। + +- [बारकोड PNG बनाएं – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Aspose.BarCode for .NET का उपयोग करके कस्टम aspect ratio के साथ Aztec बारकोड कैसे जेनरेट करें](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [बारकोड को कस्टमाइज़ करें - Codablock F Aspect Ratio के साथ Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/hindi/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..bfa62521e --- /dev/null +++ b/barcode/hindi/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-08-03 +description: इस गाइड के साथ जल्दी से बारकोड PNG बनाएं। Aspose.BarCode का उपयोग करके + बारकोड इमेज बनाना सीखें और प्लैनेट बारकोड जेनरेट करें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: hi +lastmod: 2026-08-03 +og_description: बारकोड PNG तुरंत बनाएं। यह ट्यूटोरियल दिखाता है कि कैसे बारकोड इमेज + जनरेट करें और Aspose.BarCode के साथ प्लैनेट बारकोड बनाएं। +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Python में बारकोड PNG बनाएं – पूर्ण प्रोग्रामिंग गाइड +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Python में बारकोड PNG बनाएं – चरण‑दर‑चरण मार्गदर्शिका +url: /hi/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में बारकोड PNG बनाएं – चरण‑दर‑चरण गाइड + +यदि आपको अपने Python एप्लिकेशन से **barcode PNG** फ़ाइलें बनानी हैं, तो यह ट्यूटोरियल आपको बिल्कुल वही दिखाएगा। हम Aspose.BarCode का उपयोग करके **barcode image** कैसे जेनरेट करें, और विशेष रूप से कस्टम डाइमेंशन के साथ **planet barcode** कैसे बनाएं, यह चरण‑दर‑चरण समझेंगे। + +आप सीखेंगे कि लाइब्रेरी कैसे स्थापित करें, Planet symbology को कैसे कॉन्फ़िगर करें, आकार पैरामीटर को कैसे समायोजित करें, और परिणाम को उच्च‑गुणवत्ता वाले PNG के रूप में कैसे सहेजें। यह गाइड बुनियादी Python ज्ञान और Python 3 (3.8 या नया) के हालिया संस्करण को मानता है। बारकोड मानकों का पूर्व अनुभव आवश्यक नहीं है। + +--- + +## Aspose.BarCode के साथ barcode PNG कैसे बनाएं + +यह सेक्शन **barcode PNG** बनाने के लिए आवश्यक मुख्य चरणों को सम्मिलित करता है। प्रत्येक चरण में एक कोड स्निपेट, इसका महत्व समझाने वाला विवरण, और तुरंत लागू करने योग्य व्यावहारिक टिप्स शामिल हैं। + +### 1. Aspose.BarCode पैकेज स्थापित करें + +Aspose एक शुद्ध‑Python पैकेज प्रदान करता है जो अपने .NET कोर इंजन को रैप करता है। इसे `pip` के साथ स्थापित करें: + +```bash +pip install aspose-barcode +``` + +*Why this step matters:* पैकेज `BarcodeGenerator` क्लास प्रदान करता है जिसका उपयोग पूरे उदाहरण में किया गया है। इसे ग्लोबली इंस्टॉल करने से इंटरप्रेटर रन‑टाइम पर असेंबली को ढूँढ सकेगा। + +### 2. आवश्यक क्लासेस इम्पोर्ट करें + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Tip:* केवल उन सिम्बॉल्स को इम्पोर्ट करें जिनकी आपको जरूरत है; इससे नेमस्पेस साफ़ रहता है और मॉड्यूल लोडिंग तेज़ होती है। + +### 3. Planet symbology के लिए barcode generator बनाएं + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Why this matters:* `EncodeTypes.Planet` इंजन को Planet barcode मानक उपयोग करने के लिए बताता है, जबकि दूसरा आर्ग्यूमेंट एन्कोड करने के लिए डेटा प्रदान करता है। symbology बदलने (जैसे `EncodeTypes.Code128`) से पूरी तरह अलग विज़ुअल पैटर्न बनता है। + +### 4. X dimension (module width) को पिक्सेल में सेट करें + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Explanation:* X dimension संकीर्ण बार की चौड़ाई को नियंत्रित करता है। 4 पिक्सेल का मान मध्यम घनत्व वाला barcode देता है जो अधिकांश डिवाइसों पर स्कैन योग्य रहता है। + +### 5. मैन्युअल बार ऊँचाई पिक्सेल में निर्धारित करें + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Why you might adjust this:* कुछ रिटेल प्रिंटर विश्वसनीय स्कैनिंग के लिए लंबी बार की आवश्यकता रखते हैं। डिफ़ॉल्ट ऊँचाई आमतौर पर 50 px होती है; इसे 100 px तक बढ़ाने से पठनीयता में सुधार होता है बिना फ़ाइल आकार को बहुत बढ़ाए। + +### 6. जेनरेटेड barcode को PNG इमेज के रूप में सहेजें + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Result:* `output` फ़ोल्डर में **PlanetBarHeight100.png** नाम की PNG फ़ाइल बनती है। PNG लॉस‑लेस है, जिससे यह प्रिंटिंग और वेब पेजों में एम्बेड करने के लिए आदर्श है। + +### 7. आउटपुट को सत्यापित करें (वैकल्पिक) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Tip:* इमेज को देख कर पुष्टि करें कि आयाम आपके सेट किए हुए पैरामीटर से मेल खाते हैं। यदि barcode विकृत दिखे, तो X dimension या बार ऊँचाई सेटिंग को पुनः देखें। + +--- + +## PNG फ़ॉर्मेट में barcode इमेज कैसे जेनरेट करें (वैकल्पिक सेटिंग्स) + +यदि आपको अलग इमेज फ़ॉर्मेट चाहिए या बाद में barcode को PDF में एम्बेड करना है, तो आप `BarCodeImageFormat` एन्नुम को बदल सकते हैं: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Why this matters:* PNG हर पिक्सेल को संरक्षित रखता है, जो हाई‑कॉन्ट्रास्ट बारकोड के लिए महत्वपूर्ण है। JPEG में कम्प्रेशन आर्टिफैक्ट्स आते हैं जो स्कैनिंग में बाधा डाल सकते हैं, जबकि BMP पुराने टूल्स के साथ संगतता देता है। + +--- + +## कस्टम रंगों के साथ planet barcode जेनरेट करें (उन्नत) + +आकार के अलावा, आप फोरग्राउंड और बैकग्राउंड रंगों को कस्टमाइज़ कर सकते हैं: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Practical tip:* हाई‑कॉन्ट्रास्ट रंग संयोजन (डार्क ऑन लाइट) स्कैनर की विश्वसनीयता को अधिकतम करता है। फोरग्राउंड और बैकग्राउंड के लिए समान शेड्स का उपयोग करने से बचें। + +--- + +## सामान्य समस्याएँ और उन्हें कैसे टालें + +| लक्षण | कारण | समाधान | +|---------|-------|-----| +| बारकोड स्कैन नहीं हो रहा है | X dimension बहुत छोटा (≤ 2 px) | कम से कम 3 px करने के लिए `x_dimension.pixels` बढ़ाएँ | +| इमेज धुंधली दिख रही है | PNG कम DPI पर सेव किया गया | `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` का उपयोग करके 300 DPI निर्दिष्ट करें (यदि समर्थित हो) | +| Exception `ImportError` | Aspose.BarCode स्थापित नहीं है | अपने स्क्रिप्ट के समान वातावरण में `pip install aspose-barcode` चलाएँ | +| गलत symbology | `EncodeTypes.Planet` के बजाय `EncodeTypes.Code128` उपयोग किया | जनरेटर बनाते समय `EncodeTypes.Planet` से बदलें | + +--- + +## पूरा समाधान का सारांश + +नीचे पूर्ण, चलाने योग्य स्क्रिप्ट है जो **barcode PNG** को शुरू से अंत तक बनाती है: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +इस स्क्रिप्ट को चलाने से एक स्पष्ट **Planet barcode PNG** बनता है जिसे आप HTML में एम्बेड कर सकते हैं, ईमेल में संलग्न कर सकते हैं, या प्रोडक्ट लेबल पर प्रिंट कर सकते हैं। + +--- + +## आगे के कदम और संबंधित विषय + +* **Flask या Django के साथ एकीकृत करें** – जेनरेटेड PNG को सीधे वेब एंडपॉइंट से सर्व करें। +* **बैच जेनरेशन** – प्रोडक्ट IDs की सूची पर लूप करके barcode PNG फ़ाइलों का फ़ोल्डर बनाएं। +* **PDF जेनरेशन के साथ संयोजन** – `aspose-pdf` का उपयोग करके PNG को इनवॉइस या शिपिंग लेबल में रखें। +* **अन्य symbologies का अन्वेषण करें** – विभिन्न व्यावसायिक आवश्यकताओं को पूरा करने के लिए `EncodeTypes.Planet` को `EncodeTypes.QR`, `EncodeTypes.DataMatrix`, या `EncodeTypes.Code128` से बदलें। + +ऊपर बताए गए चरणों को महारत हासिल करके, अब आप प्रोग्रामेटिक रूप से **barcode image** कैसे जेनरेट करें, जानते हैं और इसे Aspose.BarCode द्वारा समर्थित किसी भी barcode मानक तक विस्तारित कर सकते हैं। + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/hindi/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..4234858eb --- /dev/null +++ b/barcode/hindi/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-08-03 +description: C# में तेज़ी से पोस्टल बारकोड इमेज बनाएं। सीखें कि पोस्टल बारकोड कैसे + जेनरेट करें, बारकोड के आयाम सेट करें, और प्लैनेट बारकोड जेनरेट करें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: hi +lastmod: 2026-08-03 +og_description: इस पूर्ण ट्यूटोरियल के साथ C# में पोस्टल बारकोड इमेज बनाएं; बारकोड + के आयाम सेट करना, प्लैनेट बारकोड जेनरेट करना और RM4SCC बारकोड बनाना सीखें। +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: C# में पोस्टल बारकोड इमेज बनाएं – पूर्ण प्रोग्रामिंग गाइड +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: C# में पोस्टल बारकोड इमेज बनाएं – चरण‑दर‑चरण गाइड +url: /hi/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में पोस्टल बारकोड इमेज बनाएं – चरण‑दर‑चरण गाइड + +यदि आपको C# में **पोस्टल बारकोड इमेज** बनानी है, तो यह गाइड आपको बिल्कुल बताता है कैसे। हम कवर करेंगे **पोस्टल बारकोड कैसे जेनरेट करें**, **बारकोड के आयाम कैसे सेट करें**, और सामान्य पोस्टल मानकों के लिए **प्लैनेट बारकोड कैसे जेनरेट करें**। + +आप दो तैयार‑उपयोग PNG फ़ाइलों के साथ समाप्त करेंगे—एक Planet बारकोड और एक RM4SCC बारकोड—प्रत्येक 100 px ऊँचा। Aspose.BarCode for .NET लाइब्रेरी के अलावा कोई अतिरिक्त टूल आवश्यक नहीं है। + +## आवश्यकताएँ + +* .NET 6 SDK या बाद का संस्करण (कोड .NET Framework 4.7+ के साथ भी काम करता है) +* Visual Studio 2022 या कोई भी C# IDE +* NuGet पैकेज **Aspose.BarCode** (`BarcodeGenerator` प्रदान करने वाली लाइब्रेरी) + +## चरण 1: बारकोड लाइब्रेरी स्थापित करें + +अपने प्रोजेक्ट फ़ोल्डर में एक टर्मिनल खोलें और चलाएँ: + +```bash +dotnet add package Aspose.BarCode +``` + +यह पैकेज `Aspose.BarCode` नेमस्पेस जोड़ता है, जिसमें `BarcodeGenerator` और पोस्टल बारकोड्स के लिए आवश्यक `EncodeTypes` एनेमरेशन शामिल है। + +## चरण 2: आउटपुट फ़ोल्डर निर्धारित करें + +एक विश्वसनीय आउटपुट पाथ बनाना तब रनटाइम त्रुटियों से बचाता है जब फ़ोल्डर मौजूद नहीं होता। + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*क्यों महत्वपूर्ण है*: `Directory.CreateDirectory` इडेम्पोटेंट है—यह फ़ोल्डर केवल तभी बनाता है जब वह पहले से मौजूद न हो, जिससे बाद के रन में अपवाद नहीं आते। + +## चरण 3: सामान्य बारकोड आयाम कॉन्फ़िगर करें + +X‑डायमेंशन (एक बार की चौड़ाई) और कुल बार ऊँचाई सेट करने से आप जेनरेट हुई इमेज के दृश्य आकार को नियंत्रित कर सकते हैं। + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**बारकोड आयाम कैसे सेट करें**: `Parameters.Barcode.XDimension.Pixels` प्रॉपर्टी संकीर्ण बार की चौड़ाई निर्धारित करती है, जबकि `Parameters.Barcode.BarHeight.Pixels` पूरी ऊँचाई निर्धारित करती है। इन मानों को अपने मेलिंग सर्विस की विशिष्टताओं के अनुसार समायोजित करें। + +## चरण 4: Planet बारकोड जेनरेट करें + +Planet यूनाइटेड किंगडम में व्यापक रूप से उपयोग किया जाने वाला पोस्टल बारकोड है। नीचे दिया गया कोड 100 px‑ऊँचा Planet बारकोड बनाता है और इसे PNG के रूप में सहेजता है। + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**यह क्यों काम करता है**: `EncodeTypes.Planet` जेनरेटर को Planet सिम्बोलॉजी उपयोग करने के लिए बताता है। `Save` मेथड निर्दिष्ट पाथ पर PNG फ़ाइल लिखता है, पहले सेट किए गए आयामों को बरकरार रखता है। + +## चरण 5: RM4SCC बारकोड जेनरेट करें + +RM4SCC डच पोस्टल बारकोड मानक है। नीचे दिया गया कोड Planet उदाहरण को दोहराता है, यह दर्शाते हुए **पोस्टल बारकोड कैसे जेनरेट करें** विभिन्न प्रकार के साथ समान आयामों में। + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +दोनों PNG फ़ाइलें अब `Barcodes` फ़ोल्डर में स्थित हैं। उन्हें खोलने पर साफ़, 100 px‑ऊँचे बारकोड दिखेंगे जो प्रिंटिंग या दस्तावेज़ों में एम्बेड करने के लिए तैयार हैं। + +## पूर्ण स्रोत कोड + +नीचे पूर्ण, चलाने योग्य प्रोग्राम है जो दोनों Planet और RM4SCC मानकों के लिए **पोस्टल बारकोड इमेज** फ़ाइलें **बनाता** है। + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### अपेक्षित आउटपुट + +प्रोग्राम चलाने पर फ़ाइल पाथ प्रिंट होते हैं और दो PNG फ़ाइलें बनती हैं: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +प्रत्येक इमेज 100 px ऊँची है, 4‑पिक्सेल संकीर्ण बार चौड़ाई के साथ, जो हमने सेट किए हुए आयामों से मेल खाती है। + +## व्यावहारिक टिप्स और सामान्य समस्याएँ + +* **फ़ोल्डर अनुमतियाँ** – यदि प्रोग्राम प्रतिबंधित खाते के तहत चलता है, तो सुनिश्चित करें कि लक्ष्य फ़ोल्डर लिखने योग्य हो। +* **विभिन्न आयाम** – अधिक ऊँचा बारकोड बनाने के लिए `barHeightPixels` बढ़ाएँ। बेहतर रेज़ोल्यूशन के लिए `xDimensionPixels` घटाएँ, लेकिन इसे ≥ 2 रखें ताकि रेंडरिंग आर्टिफैक्ट न हों। +* **अन्य पोस्टल सिम्बोलॉजीज़** – Aspose.BarCode `EncodeTypes.Postnet` और `EncodeTypes.AustralianPost` को भी सपोर्ट करता है। `EncodeTypes` मान बदलें और वही आयाम लॉजिक रखें। +* **इमेज फॉर्मेट** – जब लॉसलेस क्वालिटी आवश्यक न हो तो छोटे फ़ाइल आकार के लिए `BarCodeImageFormat.Jpeg` उपयोग करें। + +## निष्कर्ष + +अब आप जानते हैं कि C# में आयाम कॉन्फ़िगर करके, उचित सिम्बोलॉजी चुनकर, और परिणाम को PNG के रूप में सहेजकर **पोस्टल बारकोड इमेज** फ़ाइलें कैसे **बनाएँ**। ट्यूटोरियल ने **पोस्टल बारकोड कैसे जेनरेट करें**, **Planet बारकोड जेनरेट करना** दिखाया, और स्थिर आउटपुट के लिए **बारकोड आयाम कैसे सेट करें** समझाया। + +अगले चरण में, **बारकोड रंगों को कस्टमाइज़ करना**, **मानव‑पठनीय टेक्स्ट** जोड़ना, या इमेज को PDF इनवॉइस में इंटीग्रेट करना एक्सप्लोर करें। वही पैटर्न Aspose.BarCode द्वारा समर्थित किसी भी अन्य बारकोड प्रकार पर लागू होता है, जिससे आप इस समाधान को पूर्ण पोस्टल ऑटोमेशन वर्कफ़्लो में विस्तारित कर सकते हैं। + +## अगले क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोचेज़ को एक्सप्लोर करने में मदद करेंगे। + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to generate barcode java – Australia Post Barcode with Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/hindi/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..d962c7a6c --- /dev/null +++ b/barcode/hindi/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-08-03 +description: C# में बारकोड को कैसे सहेजें, चरण‑दर‑चरण बारकोड जेनरेटर उदाहरण के साथ। + प्लैनेट बारकोड बनाना सीखें, आयाम सेट करें, और PNG छवियों को निर्यात करें। +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: hi +lastmod: 2026-08-03 +og_description: C# में बारकोड जेनरेटर उदाहरण का उपयोग करके बारकोड कैसे सहेजें। यह + ट्यूटोरियल दिखाता है कि प्लैनेट बारकोड कैसे जेनरेट करें, X‑डायमेंशन को कॉन्फ़िगर + करें, और PNG फ़ाइलें एक्सपोर्ट करें। +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: C# में बारकोड कैसे सहेजें – चरण-दर-चरण गाइड +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: C# में बारकोड कैसे सहेजें – पूर्ण बारकोड जेनरेटर गाइड +url: /hi/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में बारकोड कैसे सहेजें – पूर्ण बारकोड जनरेटर गाइड + +C# में बारकोड इमेजेस को सहेजना एक सामान्य आवश्यकता है जब आपको इनवॉइस, शिपिंग लेबल, या इन्वेंटरी टैग में पोस्टल बारकोड एम्बेड करने की जरूरत होती है। यह गाइड आपको व्यावहारिक **c# barcode generator** वर्कफ़्लो के माध्यम से ले जाता है, जिसमें Planet बारकोड बनाना और filled‑bars तथा empty‑bars PNG फ़ाइलें एक्सपोर्ट करना शामिल है। + +आप सीखेंगे कि बार की चौड़ाई कैसे सेट करें, filled bars को टॉगल करें, और आउटपुट फ़ोल्डर्स को विश्वसनीय रूप से कैसे हैंडल करें। ट्यूटोरियल के अंत तक आपके पास एक पूर्ण कार्यात्मक **barcode generator example** होगा जिसे आप किसी भी .NET प्रोजेक्ट में कॉपी कर सकते हैं। + +## आपको क्या चाहिए + +- .NET 6.0 SDK या बाद का (उदाहरण .NET Core और .NET Framework के साथ काम करता है) +- Visual Studio 2022 या कोई भी C#‑compatible IDE +- The **Aspose.BarCode** NuGet पैकेज (या कोई अन्य लाइब्रेरी जो `EncodeTypes.Planet` को सपोर्ट करती है)। इसे इस तरह इंस्टॉल करें: + +```bash +dotnet add package Aspose.BarCode +``` + +यह लाइब्रेरी `BarcodeGenerator` क्लास प्रदान करती है जिसका उपयोग इस ट्यूटोरियल में पूरे किया गया है। + +## विकास वातावरण सेटअप करना + +एक नया कंसोल प्रोजेक्ट बनाएं और आवश्यक नेमस्पेस जोड़ें: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +`System.IO` नेमस्पेस हमें `Directory.CreateDirectory` देता है, जो फाइलें लिखने से पहले सुनिश्चित करता है कि आउटपुट फ़ोल्डर मौजूद है। + +## C# बारकोड जनरेटर के साथ बारकोड इमेजेस कैसे सहेजें + +समाधान का मूल भाग कुछ छोटे कदमों का सेट है जो **Planet barcode** को कॉन्फ़िगर करता है और फिर इमेज को डिस्क पर सहेजता है। निम्नलिखित सेक्शन प्रक्रिया को प्रबंधनीय भागों में विभाजित करते हैं। + +### चरण 1: आउटपुट फ़ोल्डर परिभाषित करें + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**क्यों?** +पाथ को हार्ड‑कोड करने से उन मशीनों पर `DirectoryNotFoundException` हो सकता है जहाँ फ़ोल्डर मौजूद नहीं होता। `CreateDirectory` इडेम्पोटेंट है—यह केवल तब डायरेक्टरी बनाता है जब वह गायब हो, जिससे कोड कई बार चलाने पर भी सुरक्षित रहता है। + +### चरण 2: Planet बारकोड जनरेटर बनाएं (filled bars) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**क्यों?** +`EncodeTypes.Planet` लाइब्रेरी को बताता है कि वह एक पोस्टल Planet बारकोड उत्पन्न करे, जो मेल सर्विसेज़ में व्यापक रूप से उपयोग होता है। स्ट्रिंग `"123456"` एक नमूना पेलोड है; इसे अपने बिजनेस लॉजिक के अनुसार आवश्यक किसी भी संख्यात्मक डेटा से बदलें। + +### चरण 3: बार की चौड़ाई (X‑dimension) कॉन्फ़िगर करें और डिफ़ॉल्ट filled bars रखें + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**क्यों?** +X‑dimension प्रत्येक बार की भौतिक चौड़ाई नियंत्रित करता है। `4` पिक्सेल का मान मानक 300 dpi प्रिंटरों पर पढ़ने योग्य बारकोड देता है। `FilledBars` को `true` (डिफ़ॉल्ट) रखने से क्लासिक सॉलिड‑बार लुक बनता है। + +### चरण 4: filled‑bars बारकोड इमेज सहेजें + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**क्यों?** +PNG के रूप में सहेजने से लॉसलेस इमेज क्वालिटी बनी रहती है, जो स्कैनिंग की सटीकता के लिए महत्वपूर्ण है। `Save` मेथड स्वचालित रूप से इमेज फ़ाइल बनाता है; आपको केवल पूरा पाथ और वांछित फ़ॉर्मेट देना होता है। + +### चरण 5: empty‑bars संस्करण के लिए दूसरा जनरेटर बनाएं + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +एक नया इंस्टेंस बनाने से यह सुनिश्चित होता है कि empty‑bars संस्करण के लिए किए गए परिवर्तन पहले से सहेजे गए filled‑bars इमेज को प्रभावित न करें। + +### चरण 6: वही X‑dimension रखते हुए filled bars को डिसेबल करें + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**क्यों?** +`FilledBars = false` सेट करने से बारकोड केवल प्रत्येक बार की रूपरेखा के साथ रेंडर होता है, जो कुछ पोस्टल मानकों में विज़ुअल वेरिफिकेशन के लिए आवश्यक है। + +### चरण 7: empty‑bars बारकोड इमेज सहेजें + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +अब आपके पास दो PNG फ़ाइलें हैं—एक filled bars के साथ और एक empty bars के साथ—जो PDFs, HTML ईमेल या प्रिंटेड लेबल्स में शामिल करने के लिए तैयार हैं। + +## पूर्ण चलाने योग्य प्रोग्राम + +नीचे पूरा कोड दिया गया है जिसे आप `Program.cs` में कॉपी कर सकते हैं। यह बिना किसी संशोधन के कंपाइल और रन हो जाता है (मान लेते हैं कि Aspose.BarCode पैकेज इंस्टॉल है)। + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### अपेक्षित आउटपुट + +प्रोग्राम चलाने पर दो लाइनों जैसा आउटपुट मिलता है: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +`Barcodes` फ़ोल्डर खोलें और आप दो PNG फ़ाइलें देखेंगे। दोनों इमेजेज़ को किसी भी इमेज व्यूअर में खोला जा सकता है या सीधे दस्तावेज़ों में एम्बेड किया जा सकता है। + +![बारकोड सहेजने का उदाहरण](barcode-example.png){: .align-center alt="बारकोड सहेजने का उदाहरण"} + +## सामान्य विविधताएँ और किनारे के मामलों + +| परिदृश्य | समायोजन | +|----------|------------| +| **विभिन्न इमेज फ़ॉर्मेट** | आवश्यकतानुसार `BarCodeImageFormat.Png` को `Jpeg`, `Gif`, या `Bmp` में बदलें। | +| **कस्टम आउटपुट साइज** | विशिष्ट पिक्सेल डाइमेंशन को मजबूर करने के लिए `filled.Parameters.Image.Width` और `Height` का उपयोग करें। | +| **डायनामिक डेटा** | स्थिर `"123456"` को एक वैरिएबल से बदलें जो ऑर्डर नंबर, ट्रैकिंग आईडी आदि रखता हो। | +| **गैर‑मौजूद फ़ोल्डर** | `Directory.CreateDirectory` पहले से ही गायब डायरेक्टरी को संभालता है; अतिरिक्त कोड की आवश्यकता नहीं। | +| **हाई‑रेज़ोल्यूशन प्रिंटिंग** | 600 dpi प्रिंटरों के लिए `XDimension.Pixels` को 6–8 तक बढ़ाएँ, लेकिन स्कैनर संगतता की जाँच करें। | + +**Pro tip:** यदि आपको लूप में कई बारकोड जनरेट करने की जरूरत है, तो एक ही `BarcodeGenerator` इंस्टेंस को पुनः उपयोग करें और प्रत्येक `Save` से पहले केवल `CodeText` प्रॉपर्टी बदलें। इससे ऑब्जेक्ट अलोकेशन ओवरहेड कम होता है। + +## अन्य मानकों के लिए बारकोड कैसे जनरेट करें + +एक ही पैटर्न अन्य `EncodeTypes` जैसे `Code128`, `QR`, या `DataMatrix` के लिए भी काम करता है। बस `EncodeTypes.Planet` को इच्छित प्रकार से बदलें और किसी भी प्रकार‑विशिष्ट पैरामीटर को समायोजित करें (जैसे, `QRCodeVersion` + +## अब आपको क्या सीखना चाहिए? + +निम्नलिखित ट्यूटोरियल्स उन निकट-संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण-दर-चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोचेज़ को एक्सप्लोर करने में मदद करेंगे। + +- [Aspose.BarCode के साथ DataMatrix C40 का उपयोग करके PNG कैसे सहेजें](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Aspose.BarCode for .NET के साथ DataMatrix बारकोड (ECC 200) कैसे जनरेट करें](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Aspose.BarCode के साथ बारकोड जनरेट करें – Code 39 कॉन्फ़िगरेशन](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/hongkong/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..671029cea --- /dev/null +++ b/barcode/hongkong/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-08-03 +description: 條碼產生器 C# 教學,示範如何使用 Aspose.BarCode 建立 Planet 條碼、設定 X 尺寸,並儲存為 PNG 圖像。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: zh-hant +lastmod: 2026-08-03 +og_description: 條碼產生器 C# 教學一步步教你建立 Planet 條碼、調整 X 尺寸,並使用 Aspose.BarCode 儲存為 PNG。 +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: 條碼產生器 C# – 一步一步建立 Planet 條碼 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: 條碼產生器 C# – 建立 Planet 條碼與 RM4SCC 範例 +url: /zh-hant/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – create Planet barcode and RM4SCC example + +如果你需要一個 **barcode generator C#** 能產生郵政專用符號,本教學將示範如何使用 Aspose.BarCode **建立 Planet barcode** 圖片。你會看到如何設定 X‑dimension、產生相對應的 RM4SCC 條碼,並將兩者儲存為 PNG 檔案——只需幾個簡潔步驟。 + +本教學涵蓋在 .NET 6 或更新版本上執行程式碼所需的一切,說明每個設定的意義,並指出常見的陷阱(例如模組寬度設定錯誤或目錄權限不足)。完成後,你將得到兩張符合 Planet 與 RM4SCC 標準的可直接列印條碼圖檔。 + +## Prerequisites + +開始之前,請確保你已具備: + +* .NET 6 SDK(或任何 Aspose.BarCode 支援的 .NET 版本) +* Visual Studio 2022 或你慣用的 C# IDE +* 已加入 **Aspose.BarCode** 的 NuGet 參考(`Install-Package Aspose.BarCode`) +* 對欲存放 PNG 檔案的資料夾具備寫入權限 + +不需要額外的外部服務;所有編碼皆在本機函式庫內完成。 + +## Step 1: Initialise the barcode generator C# object + +第一步是建立 `BarcodeGenerator` 的實例。建構子接受條碼類型(`EncodeTypes.Planet`)與要編碼的資料。 + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Why this step?* +`BarcodeGenerator` 是產生任何條碼的入口。選擇 `EncodeTypes.Planet` 會讓函式庫依照多數郵政服務使用的 ISO/IEC 24723 規範來產生條碼。 + +## Step 2: Set the X‑dimension (module width) for the Planet barcode + +X‑dimension 定義單一條碼模組(最小的條或空白)的寬度。**4 像素** 的設定對大多數標籤印表機來說相當合適。 + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Why this matters* +若模組太窄,條碼可能無法被辨識;若太寬則會不必要地增大標籤尺寸。調整 `Pixels` 可讓你依印表機解析度微調條碼。 + +## Step 3: Save the Planet barcode as a PNG image + +Aspose.BarCode 會根據所選的條碼類型自動計算條碼高度,你只需要提供檔案路徑與格式。 + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tip* +將 `YOUR_DIRECTORY` 替換為本機上已存在的絕對或相對路徑。若資料夾不存在,`Save` 方法會拋出 `DirectoryNotFoundException`。 + +**Expected output** – 一個 PNG 檔案,外觀類似下圖(此處不顯示實際圖像,但你會看到一個帶有數字 `123456` 的標準 Planet 條碼)。 + +## Step 4: Initialise a second generator for the RM4SCC barcode + +許多郵政系統要求在同一封信件上同時印製 Planet 與 RM4SCC 符號。為 RM4SCC 類型再建立一個 `BarcodeGenerator` 實例。 + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Why a separate instance?* +每種條碼類型都有自己的參數集合。重複使用同一個產生器可能會不小心帶入不適用於第二條碼的設定(例如 X‑dimension)。 + +## Step 5: Configure the X‑dimension for the RM4SCC barcode + +RM4SCC 同樣遵循 X‑dimension 設定,我們使用相同的像素寬度以保持視覺一致性。 + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +若需要較高的條碼(例如較大的標籤),也可以設定 `Height.Pixels`。不設定時,函式庫會自動計算最適高度。 + +## Step 6: Save the RM4SCC barcode as a PNG image + +最後,將 RM4SCC 條碼寫入磁碟。 + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +現在你已擁有兩個 PNG 檔案——`PostalPlanetBarHeightNone.png` 與 `PostalRM4SCCBarHeightNone.png`——可嵌入郵件標籤、列印於信封,或交給第三方列印服務。 + +## Optional: Adjusting height or using other image formats + +如果工作流程需要特定的條碼高度或其他影像格式(例如 JPEG 或 BMP),可在呼叫 `Save` 前調整參數: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Edge case** – 設定自訂高度時,請確保該值符合 ISO 標準規定的最小高度;否則條碼可能無法通過驗證。 + +## Common pitfalls and how to avoid them + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| `DirectoryNotFoundException` | 目標資料夾不存在或拼寫錯誤。 | 先建立資料夾,或使用 `Path.Combine` 搭配 `Environment.CurrentDirectory`。 | +| Barcode unreadable on low‑resolution printers | X‑dimension 對印表機 DPI 來說太小。 | 將 `XDimension.Pixels` 提升至 5 – 6(適用於 203 dpi 印表機),或先用樣本標籤測試。 | +| Wrong symbology used | 傳入 `EncodeTypes.Code128` 而非 `EncodeTypes.Planet`。 | 再次確認 `EncodeTypes` 列舉值與所需的郵政標準相符。 | +| Null reference on `Parameters` | 使用較舊版本的 Aspose.BarCode,API 不同。 | 升級至最新的 NuGet 套件(v23.12 或以上)。 | + +## Full runnable example + +以下是完整程式碼,你可以直接複製、貼上並執行。程式碼包含 `using` 陳述式、錯誤處理與說明每一行功能的註解。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +執行後會在執行檔旁建立 `Barcodes` 資料夾,並將兩個 PNG 檔案放入其中。使用任何影像檢視器開啟即可驗證結果。 + +## Conclusion + +現在你已擁有一套 **barcode generator C#** 解決方案,能 **create Planet barcode** 圖片、調整 X‑dimension 以獲得最佳列印效果,並產生相對應的 RM4SCC 條碼——只需幾行程式碼。此方法適用於 .NET 6 以上版本,只需 Aspose.BarCode NuGet 套件,亦可透過更換 `EncodeTypes` 值擴充至 Code128、QR、DataMatrix 等其他條碼類型。 + +### What’s next? + +* 嘗試不同的 `XDimension.Pixels` 數值,以配合你的印表機 DPI。 +* 透過變更 `BarCodeImageFormat` 列舉,產生 PDF、SVG 等其他格式。 +* 使用 **SkiaSharp** 等圖形函式庫將兩張 PNG 合併成單一標籤。 +* 探索完整的 Aspose.BarCode API,了解校驗碼驗證或自訂字型等進階功能。 + +歡迎將程式碼改寫為批次處理,或整合至 ASP.NET Core Web 服務,讓它在需要時即時回傳條碼圖像。祝開發順利! + +## What Should You Learn Next? + +以下教學與本指南的技術緊密相關,能幫助你進一步掌握 API 功能並探索其他實作方式: + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/hongkong/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..b82cc398a --- /dev/null +++ b/barcode/hongkong/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-08-03 +description: 條碼產生器 C# 教學示範如何使用 Aspose.BarCode 產生條碼圖像、設定列與行,並將 DataBar Expanded Stacked + 儲存為 PNG 檔案。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: zh-hant +lastmod: 2026-08-03 +og_description: 條碼產生器 C# 教學說明如何使用 Aspose.BarCode 產生條碼圖像、設定 DataBar Expanded Stacked + 的欄與列,並儲存 PNG 檔案。 +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: 條碼產生器 C# – 逐步指南:生成條碼圖像 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: 條碼產生器 C# – 產生條碼圖片 +url: /zh-hant/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 條碼產生器 C# – 產生條碼圖像 + +如果您需要一個能夠為 DataBar Expanded Stacked 產生條碼圖像的 C# 條碼產生器,本指南將帶您完成完整流程。您將學習如何設定欄與列、將結果儲存為 PNG,以及如何將程式碼套用到其他條碼類型。 + +以程式方式產生條碼圖像可省去手動步驟,確保發票、運送標籤與庫存系統之間的一致性。本教學涵蓋從專案設定到完整原始碼的所有內容,讓您能立即執行範例。 + +## 前置條件 + +在開始之前,請確保您已具備: + +* .NET 6.0 或更新版本已安裝 +* 如 Visual Studio 2022 等 IDE(任何支援 C# 的編輯器皆可) +* **Aspose.BarCode for .NET** 授權 – 可使用免費評估版進行測試 +* 基本的 C# 語法熟悉度 + +若缺少上述任一項目,請前往 dotnet.microsoft.com 下載 .NET SDK,並使用以下指令取得 Aspose.BarCode NuGet 套件: + +```bash +dotnet add package Aspose.BarCode +``` + +## 步驟 1:建立條碼產生器 C# 專案 + +建立一個新的主控台應用程式,並加入必要的 `using` 指示詞: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +`BarcodeGenerator` 類別是條碼產生器 C# API 的核心。它接受條碼類型與要編碼的文字。 + +## 步驟 2:產生 DataBar Expanded Stacked 條碼並設定欄數 + +以下範例建立一個具有四個欄的條碼。調整 `Columns` 屬性會改變 DataBar Expanded Stacked 條碼的視覺密度。 + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**為什麼這很重要:** 欄數會影響在緊湊空間內可儲存的資料量。設定為 4 會產生較寬的條碼,但仍能被大多數掃描器讀取。 + +## 步驟 3:產生具有自訂列數的條碼 + +第二個範例示範如何透過設定 `Rows` 屬性來控制垂直佈局。三列配置在水平空間受限時,可產生較高的條碼。 + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**為什麼這很重要:** 調整列數可讓條碼適應窄欄位,同時保持可讀性。條碼產生器 C# 會自動重新計算模組大小以符合規格。 + +## 步驟 4:完整、可執行的範例 + +以下是一個結合前述步驟的獨立程式。將程式碼複製到 `Program.cs`,將 `YOUR_DIRECTORY` 替換為實際的資料夾路徑,然後執行應用程式。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### 預期輸出 + +執行程式後,目標目錄會出現兩個 PNG 檔案: + +* **DatabarCols4.png** – 具有四個欄的 DataBar Expanded Stacked 條碼 +* **DatabarRows3.png** – 同樣資料以三列方式編碼 + +使用任何圖像檢視器開啟這些檔案,即可看到清晰、可掃描的條碼,適合列印或嵌入 PDF 中。 + +## 如何使用自訂尺寸產生條碼圖像 + +若需要特定的圖像大小,可在呼叫 `Save` 之前調整 `ImageHeight` 與 `ImageWidth` 屬性: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +變更尺寸不會影響編碼資料;僅會調整視覺呈現的比例。此技巧在將條碼整合至具有固定版面限制的 UI 元件時特別有用。 + +## 常見陷阱與專業提示 + +* **路徑分隔符號:** 使用逐字字串 (`@"C:\Path\file.png"`) 或 `Path.Combine` 以避免 Windows 上的跳脫字元問題。 +* **授權強制執行:** 若未使用有效授權,產生的圖像會帶有浮水印。請於應用程式啟動時盡早載入授權: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **編碼限制:** DataBar Expanded Stacked 最多支援 74 個數字字元。超過此上限會拋出例外。請在建立產生器前驗證輸入長度。 +* **效能考量:** 重複使用同一個 `BarcodeGenerator` 實例進行多次儲存,可減少記憶體配置。若編碼文字相同,只需在儲存間變更 `Rows` 或 `Columns` 屬性。 + +## 後續步驟 + +現在您已能使用條碼產生器 C# 產生條碼圖像,建議進一步探索: + +* **不同條碼類型** – 嘗試 `EncodeTypes.QR`、`EncodeTypes.Code128` 或 `EncodeTypes.Pdf417`。 +* **顏色客製化** – 設定 `Parameters.Barcode.ForeColor` 與 `BackColor` 以符合品牌色彩。 +* **嵌入 PDF** – 結合產生的 PNG 與 Aspose.PDF,建立可列印的文件。 + +透過這些延伸功能,您可以打造完整的條碼解決方案,應用於庫存、物流或零售等領域。 + +--- + + +## 接下來應該學什麼? + +以下教學與本指南所示技術緊密相關,提供完整可執行的程式碼範例與逐步說明,協助您掌握更多 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 產生 DataMatrix 條碼 (ECC 200)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/hongkong/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..25e9f3be8 --- /dev/null +++ b/barcode/hongkong/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-08-03 +description: C# 條碼產生器範例,示範如何設定寬度、調整高度以及產生條碼圖像。請依照步驟說明操作。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: zh-hant +lastmod: 2026-08-03 +og_description: 條碼產生器範例示範設定 X 軸尺寸寬度、變更條碼高度,並以 C# 產生條碼影像。請依照步驟建立 PNG 檔案。 +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: 條碼產生器範例 – C# 寬度與高度指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: C# 條碼產生器範例 – 設定寬度與高度 +url: /zh-hant/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# 條碼產生器範例 – 設定寬度與高度 + +如果你需要 **條碼產生器範例**(C#),本指南將示範如何設定 X‑dimension(寬度)、如何變更條碼高度,以及如何產生條碼影像檔。你將看到一個完整、可執行的程式,會產生兩個 PNG 檔案,分別具有不同的高度。 + +典型的情境是製作產品標籤,條碼尺寸必須符合掃描器規格。完成本教學後,你將能以程式方式調整寬度與高度參數,並將結果儲存為 PNG 影像。 + +## 前置條件 + +在開始之前,請確保你已具備: + +* 已安裝 .NET 6(或更新版本)— 程式碼以 .NET 6 SDK 為目標。 +* 支援 `EncodeTypes.DatabarOmniDirectional` 的條碼函式庫。範例使用 **Aspose.BarCode for .NET**,但任何提供類似屬性的函式庫皆可。 +* 可編譯與執行程式的 IDE 或編輯器(Visual Studio、VS Code、Rider)。 +* 有寫入權限的資料夾,用於儲存 PNG 檔案。 + +> **專業提示:** 在專案根目錄建立名為 `Barcodes` 的資料夾,並以 `Path.Combine` 參照,避免硬編碼絕對路徑。 + +## 條碼產生器範例:初始化與設定 + +第一步是建立 `BarcodeGenerator` 實例,並指定所需的條碼類型與資料字串。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +`EncodeTypes.DatabarOmniDirectional` 列舉會選取 Databar Omni‑directional 條碼類型,而符合 GS1 格式的資料字串 `(01)12345678901231` 代表一個典型的 GTIN‑14 值。只要初始化一次,即可在多張影像間重複使用同一個物件。 + +## 如何設定寬度(X‑dimension) + +X‑dimension 控制條碼模組的寬度。將其設為 2 像素,即每根窄條寬 2 像素,這是高密度列印的常見需求。 + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +為什麼重要:若寬度過小,掃描器可能無法辨識單根條;若寬度過大,條碼可能佔用過多標籤空間。請依列印機 DPI 與目標標籤尺寸調整此像素值。 + +## 如何變更高度 + +條碼高度決定條的高度。範例會產生兩張影像:一張高度為 30 像素,另一張為 60 像素。 + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +`BarHeight.Pixels` 屬性直接影響條的視覺高度。於不同的 `Save` 呼叫間變更它,即可在同一筆資料下產生多種變體,而不必重新建立產生器。 + +### 預期輸出 + +執行程式後,`Barcodes` 資料夾會出現兩個 PNG 檔案: + +* `DatabarBarHeight30Pixels.png` – 條高 30 像素。 +* `DatabarBarHeight60Pixels.png` – 條高 60 像素。 + +兩張影像的寬度相同(由 X‑dimension 決定),且皆編碼相同的 GTIN‑14 資料。 + +![兩個高度不同的條碼 PNG 檔案,由 C# 程式碼產生](barcode-example.png "條碼產生器範例顯示高度變化") + +*上述影像的 alt 文字已包含主要關鍵字,以提升可及性與 SEO。* + +## 如何在 C# 中產生條碼影像 + +`Save` 方法負責將條碼資料轉換為影像檔。你可以傳入不同的 `BarCodeImageFormat` 列舉值,以產生 JPEG、BMP、SVG 等格式。範例使用 PNG,因為它保留無損品質且相容性高。 + +若需直接將條碼嵌入 PDF 或網頁,可將影像以 `byte[]` 形式取得: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +此作法可省去暫存檔,適合高吞吐量服務。 + +## 常見變化與例外情況 + +| 情境 | 調整方式 | +|-----------|------------| +| **不同條碼類型** | 將 `EncodeTypes.DatabarOmniDirectional` 替換為其他列舉值(例如 `EncodeTypes.Code128`)。 | +| **極小標籤** | 將 `XDimension.Pixels` 降至 1 像素,但須確認掃描器可讀性。 | +| **高解析度列印** | 同時按比例提升 X‑dimension 與條高(例如寬 4 px、高 80 px)。 | +| **動態資料** | 在執行時傳入資料字串,可能來自資料庫記錄。 | +| **批次產生** | 迭代資料字串集合,重複使用同一個 `BarcodeGenerator` 實例,同時更新 `generator.Text`。 | + +若遭遇 `ArgumentOutOfRangeException` 等例外,請再次確認像素值為正整數且輸出目錄已存在。 + +## 完整程式碼回顧 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +將程式碼貼入新的 Console 專案,還原 Aspose.BarCode NuGet 套件(`dotnet add package Aspose.BarCode`),然後執行 `dotnet run`。你會在主控台看到確認已儲存檔案的訊息。 + +## 結論 + +本 **條碼產生器範例** 示範了如何設定寬度、變更高度,以及在 C# 中產生條碼影像。透過調整 `XDimension.Pixels` 與 `BarHeight.Pixels`,即可控制條碼的視覺尺寸;`Save` 方法則負責將結果寫入 PNG 檔。建議你嘗試不同的條碼類型、輸出格式與資料字串,以符合實際需求。 + +**後續步驟** + +* 探索 **如何產生條碼** 的其他影像格式(SVG、JPEG),以供網頁使用。 +* 學習 **在 ASP.NET Core 端點中建立條碼影像 C#**,直接將 PNG 回傳給瀏覽器。 +* 結合此程式碼與 PDF 產生函式庫,將條碼嵌入發票或運送標籤。 + +歡迎自行調整範例、分享成果,或在留言區提出問題。祝開發順利! + +## 接下來該學什麼? + +以下教學與本指南的技術緊密相關,能幫助你進一步掌握 API 功能並探索其他實作方式: + +- [如何產生條碼 - 一維條碼類型](/barcode/english/net/one-dimensional-barcode-types/) +- [如何為 ITF-14 條碼設定邊框](/barcode/english/net/itf-14-barcode-customization/) +- [如何使用 Aspose.BarCode for .NET 產生 DataMatrix 條碼(ECC 200)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/hongkong/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..5247123f5 --- /dev/null +++ b/barcode/hongkong/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-03 +description: 在 C# 中建立條碼 PNG,並學習如何調整 DataBar 圖像的長寬比。跟隨此完整範例,內含程式碼與技巧。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: zh-hant +lastmod: 2026-08-03 +og_description: 在 C# 中建立條碼 PNG,並了解如何調整 DataBar 條碼的長寬比。本指南提供可直接執行的程式碼與實用技巧。 +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: 在 C# 中建立條碼 PNG – 完整範例與長寬比控制 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: 在 C# 中建立條碼 PNG – 逐步指南 +url: /zh-hant/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中建立條碼 PNG – 步驟指南 + +如果您需要 **在 C# 中建立條碼 PNG**,本教學會一步一步示範。您將產生一個堆疊式全向 DataBar 條碼,將其儲存為 PNG 檔案,並學習 **如何調整長寬比** 以符合不同的掃描環境。 + +本指南涵蓋您所需的一切:必要的套件、完整可執行的程式碼,以及每個設定為何重要的說明。完成後,您將得到兩個 PNG 檔案——一個長寬比為 15,另一個為 30——可直接用於測試或正式環境。 + +## 前置條件 + +開始之前,請確保您已具備: + +- .NET 6.0 SDK 或更新版本 +- Visual Studio 2022(或任何 C# IDE) +- 已加入 **Aspose.BarCode** 的 NuGet 參考(提供 `BarcodeGenerator` 的函式庫) +- 有寫入 PNG 檔案所在目錄的權限 + +您可以使用以下指令加入 Aspose.BarCode 套件: + +```bash +dotnet add package Aspose.BarCode +``` + +## 步驟 1:建立專案並匯入命名空間 + +建立一個新的主控台應用程式,並匯入產生條碼與檔案 I/O 所需的命名空間。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**為什麼這很重要:** 匯入 `Aspose.BarCode.Generation` 後即可使用 `BarcodeGenerator`。將程式碼寫在 `Main` 內,使範例自成一體且易於執行。 + +## 步驟 2:為堆疊式全向 DataBar 建立條碼產生器 + +以 `EncodeTypes.DatabarStackedOmniDirectional` 類型以及範例 GS1‑128 資料字串實例化 `BarcodeGenerator`。 + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**為什麼這很重要:** 選擇此編碼類型可產生高密度 DataBar,能被大多數現代掃描器讀取。資料字串遵循 GS1 應用識別碼 (01) 格式,常用於商品識別。 + +## 步驟 3:以像素定義 X‑dimension(模組寬度) + +設定模組寬度,以控制條碼的整體尺寸,同時不影響可讀性。 + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**為什麼這很重要:** X‑dimension 設為 2 像素,可讓條碼既不會太小而無法被掃描,也不會太大而佔用過多標籤空間。 + +## 步驟 4:以長寬比 15 儲存第一個 PNG + +調整 DataBar 的長寬比,然後將影像儲存為 PNG 檔案。 + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**為什麼這很重要:** 長寬比決定堆疊 DataBar 的高寬比例。15 是常見的預設值,能在可讀性與標籤高度之間取得平衡。 + +## 步驟 5:將長寬比改為 30 並儲存第二個 PNG + +對同一個產生器實例修改為較大的長寬比,然後儲存第二張影像。 + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**為什麼這很重要:** 提高長寬比會使條碼在垂直方向上拉長,對低解析度裝置或在窄幅媒介上列印的標籤,可提升掃描可靠性。 + +## 預期輸出 + +執行程式後會產生兩個 PNG 檔案: + +| 檔案名稱 | 長寬比 | 大約尺寸(像素) | +|------------------------------------|--------|---------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300(寬 × 高) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600(寬 × 高) | + +兩張影像皆包含清晰且可掃描的 DataBar 條碼,編碼的 GS1 識別碼為 `(01)12345678901231`。 + +## 常見問題與邊緣案例 + +### 如何變更其他視覺屬性? + +您可以透過 `generator.Parameters.Barcode` 物件調整前景色、背景色,或加入可讀文字。例如: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### 若需要其他影像格式該怎麼做? + +將 `BarCodeImageFormat.Png` 替換為 `Jpeg`、`Bmp` 或 `Gif` 即可。PNG 仍是條碼影像的最佳無損選擇。 + +### 長寬比會影響掃描速度嗎? + +較高的長寬比會增加條碼高度,對於難以辨識短堆疊符號的裝置,可提升掃描可靠性。但過高的條碼可能無法放入小尺寸標籤,請以目標硬體進行測試。 + +### 能否在迴圈中產生多筆條碼? + +可以。為每筆資料字串建立新的 `BarcodeGenerator` 實例,或在同一實例上更新 `CodeText` 與 `DataBar.AspectRatio` 後重複使用。此作法可減少物件分配的開銷。 + +## 專業小技巧 + +- **重複使用產生器**:只變更 `CodeText` 或 `AspectRatio`,即可避免重新實例化物件,提升批次處理效能。 +- **驗證輸出**:使用手持掃描器或行動應用程式確認產生的 PNG 能正確讀取,才上線投入正式環境。 +- **檔名命名**:如範例所示,將長寬比寫入檔名,方便在測試期間追蹤不同變體。 + +## 結論 + +現在您已掌握如何在 C# 中 **建立條碼 PNG**,以及如何 **精確調整堆疊式全向 DataBar 的長寬比**。完整範例示範了初始化、X‑dimension 設定、長寬比調整與影像儲存,全部集中於一個可直接執行的程式。 + +接下來,您可以探索其他條碼類型、嘗試顏色變化,或將產生器整合至更大的報表或庫存系統。祝開發順利! + +## 接下來該學什麼? + +以下教學與本指南的技巧密切相關,提供完整可執行的程式碼範例與逐步說明,協助您深入掌握其他 API 功能,或在專案中嘗試不同的實作方式。 + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/hongkong/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..794e0f88f --- /dev/null +++ b/barcode/hongkong/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-08-03 +description: 快速使用本指南建立條碼 PNG。了解如何使用 Aspose.BarCode 產生條碼圖像以及產生 Planet 條碼。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: zh-hant +lastmod: 2026-08-03 +og_description: 即時產生條碼 PNG。本教學示範如何產生條碼圖像以及使用 Aspose.BarCode 產生 Planet 條碼。 +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: 在 Python 中建立條碼 PNG – 完整程式設計指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: 在 Python 中建立條碼 PNG – 步驟教學 +url: /zh-hant/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中建立條碼 PNG – 步驟指南 + +如果你需要從 Python 應用程式 **建立條碼 PNG** 檔案,本教學會精確說明操作步驟。我們將示範如何使用 Aspose.BarCode **產生條碼影像**,並特別 **產生自訂尺寸的 Planet 條碼**。 + +你將學會如何安裝函式庫、設定 Planet 符號、調整尺寸參數,並將結果儲存為高品質 PNG。此指南假設具備基本的 Python 知識,且使用較新版的 Python 3(3.8 或更新)。不需要先前的條碼標準經驗。 + +--- + +## 使用 Aspose.BarCode 建立條碼 PNG 的方法 + +本節包含建立 **條碼 PNG** 所需的核心步驟。每個步驟都附有程式碼片段、說明其重要性,以及可立即套用的實用技巧。 + +### 1. 安裝 Aspose.BarCode 套件 + +Aspose 提供純 Python 套件,封裝其 .NET 核心引擎。使用 `pip` 安裝: + +```bash +pip install aspose-barcode +``` + +*此步驟的重要性:* 此套件提供在範例中使用的 `BarcodeGenerator` 類別。全域安裝可確保直譯器在執行時能找到組件。 + +### 2. 匯入所需類別 + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*提示:* 只匯入必要的符號;這樣可保持命名空間整潔,並加快模組載入速度。 + +### 3. 為 Planet 符號建立條碼產生器 + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*此步驟的重要性:* `EncodeTypes.Planet` 告訴引擎使用 Planet 條碼標準,第二個參數則提供要編碼的資料。變更符號(例如 `EncodeTypes.Code128`)會產生完全不同的視覺圖樣。 + +### 4. 設定 X 維度(模組寬度)像素值 + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*說明:* X 維度控制窄條的寬度。設定為 4 像素可產生適度密集的條碼,且在大多數裝置上仍可掃描。 + +### 5. 定義手動條碼高度(像素) + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*調整原因:* 某些零售印表機需要較高的條碼以確保掃描可靠性。預設高度通常為 50 px;將其提升至 100 px 可提升可讀性,同時不會大幅增加檔案大小。 + +### 6. 將產生的條碼儲存為 PNG 影像 + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*結果:* 會在 `output` 資料夾產生名為 **PlanetBarHeight100.png** 的 PNG 檔案。PNG 為無損格式,適合列印及嵌入網頁。 + +### 7. 驗證輸出(可選) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*提示:* 檢視影像可確認尺寸是否符合設定參數。若條碼顯示扭曲,請重新檢查 X 維度或條碼高度設定。 + +--- + +## 以 PNG 格式產生條碼影像(替代設定) + +如果需要其他影像格式,或稍後想將條碼嵌入 PDF,可變更 `BarCodeImageFormat` 列舉: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*此步驟的重要性:* PNG 保留每個像素,對高對比度條碼至關重要。JPEG 會產生壓縮雜訊,可能影響掃描,而 BMP 則提供與舊工具的相容性。 + +--- + +## 使用自訂顏色產生 Planet 條碼(進階) + +除了尺寸外,還可以自訂前景與背景顏色: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*實用提示:* 高對比度的顏色組合(深色在淺色上)可提升掃描器的可靠性。避免前景與背景使用相近色調。 + +--- + +## 常見陷阱與避免方法 + +| 症狀 | 原因 | 解決方案 | +|---------|-------|-----| +| 條碼無法掃描 | X 維度過小 (≤ 2 px) | 將 `x_dimension.pixels` 提升至至少 3 px | +| 圖像模糊 | PNG 以低 DPI 儲存 | 使用 `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` 指定 300 DPI(若支援) | +| 例外 `ImportError` | 未安裝 Aspose.BarCode | 在與腳本相同的環境執行 `pip install aspose-barcode` | +| 符號錯誤 | 使用 `EncodeTypes.Code128` 而非 `EncodeTypes.Planet` | 建立產生器時改為 `EncodeTypes.Planet` | + +--- + +## 完整解決方案回顧 + +以下為完整、可執行的腳本,從頭到尾 **建立條碼 PNG**: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +執行此腳本會產生清晰的 **Planet 條碼 PNG**,可嵌入 HTML、附加於電子郵件,或列印於產品標籤上。 + +--- + +## 往後步驟與相關主題 + +* **Integrate with Flask or Django** – 直接從 Web 端點提供產生的 PNG。 +* **Batch generation** – 針對產品 ID 清單迴圈,建立包含條碼 PNG 檔案的資料夾。 +* **Combine with PDF generation** – 使用 `aspose-pdf` 將 PNG 放入發票或運送標籤。 +* **Explore other symbologies** – 將 `EncodeTypes.Planet` 替換為 `EncodeTypes.QR`、`EncodeTypes.DataMatrix` 或 `EncodeTypes.Code128`,以符合不同業務需求。 + +掌握上述步驟後,你現在已了解如何以程式方式 **產生條碼影像**,且可將此模式擴展至 Aspose.BarCode 支援的任何條碼標準。 + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/hongkong/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..54a97b274 --- /dev/null +++ b/barcode/hongkong/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-08-03 +description: 快速在 C# 中建立郵政條碼圖像。了解如何產生郵政條碼、設定條碼尺寸,並產生 Planet 條碼。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: zh-hant +lastmod: 2026-08-03 +og_description: 使用完整教學在 C# 中建立郵政條碼圖像;了解如何設定條碼尺寸、產生 Planet 條碼以及產生 RM4SCC 條碼。 +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: 在 C# 中建立郵政條碼圖像 – 完整程式設計指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: 在 C# 中建立郵政條碼圖像 – 步驟指南 +url: /zh-hant/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中建立郵政條碼圖像 – 步驟指南 + +如果您需要在 C# 中 **建立郵政條碼圖像**,本指南將逐步說明。我們將涵蓋 **如何產生郵政條碼**、**如何設定條碼尺寸**,以及 **如何產生 Planet 條碼** 以符合常見的郵政標準。 + +您將得到兩個即用的 PNG 檔案——一個 Planet 條碼和一個 RM4SCC 條碼——每個皆為 100 px 高。除了 Aspose.BarCode for .NET 函式庫外,無需其他工具。 + +## 前置條件 + +* .NET 6 SDK 或更新版本(此程式碼亦適用於 .NET Framework 4.7+) +* Visual Studio 2022 或任何 C# IDE +* NuGet 套件 **Aspose.BarCode**(提供 `BarcodeGenerator` 的函式庫) + +## 步驟 1:安裝條碼函式庫 + +在專案資料夾中開啟終端機並執行以下指令: + +```bash +dotnet add package Aspose.BarCode +``` + +此套件會加入 `Aspose.BarCode` 命名空間,內含產生郵政條碼所需的 `BarcodeGenerator` 與 `EncodeTypes` 列舉。 + +## 步驟 2:定義輸出資料夾 + +建立可靠的輸出路徑可避免在資料夾不存在時發生執行時錯誤。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*為何重要*:`Directory.CreateDirectory` 為冪等操作——僅在資料夾尚未存在時才會建立,避免在後續執行時拋出例外。 + +## 步驟 3:設定通用條碼尺寸 + +設定 X‑dimension(單根條的寬度)與整體條碼高度,可控制產生圖像的視覺尺寸。 + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**如何設定條碼尺寸**:`Parameters.Barcode.XDimension.Pixels` 屬性定義窄條寬度,而 `Parameters.Barcode.BarHeight.Pixels` 定義完整高度。請依照您的郵寄服務規格調整這些數值。 + +## 步驟 4:產生 Planet 條碼 + +Planet 是英國廣泛使用的郵政條碼。以下程式碼會產生一個 100 px 高的 Planet 條碼,並以 PNG 格式儲存。 + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**為何此程式碼可行**:`EncodeTypes.Planet` 告訴產生器使用 Planet 符號。`Save` 方法會將 PNG 檔寫入指定路徑,保留先前設定的尺寸。 + +## 步驟 5:產生 RM4SCC 條碼 + +RM4SCC 是荷蘭的郵政條碼標準。以下程式碼與 Planet 範例相同,示範 **如何產生不同類型的郵政條碼**,且尺寸相同。 + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +兩個 PNG 檔案現在皆位於 `Barcodes` 資料夾。開啟後會看到乾淨、100 px 高的條碼,可直接列印或嵌入文件中。 + +## 完整原始碼 + +以下為完整、可執行的程式,**建立郵政條碼圖像** 檔案,支援 Planet 與 RM4SCC 兩種標準。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### 預期輸出 + +執行程式會列印檔案路徑,並產生兩個 PNG 檔案: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +每張影像皆為 100 px 高,窄條寬度為 4 像素,符合我們設定的尺寸。 + +## 實用技巧與常見陷阱 + +* **資料夾權限** – 若程式在受限帳號下執行,請確保目標資料夾具備寫入權限。 +* **不同尺寸** – 若要產生較高的條碼,請增加 `barHeightPixels`。若需更細緻的解析度,降低 `xDimensionPixels`,但須保持 ≥ 2 以避免渲染瑕疵。 +* **其他郵政符號** – Aspose.BarCode 亦支援 `EncodeTypes.Postnet` 與 `EncodeTypes.AustralianPost`。只要交換 `EncodeTypes` 的值,並保留相同的尺寸邏輯即可。 +* **影像格式** – 若不需要無損品質,可使用 `BarCodeImageFormat.Jpeg` 以減小檔案大小。 + +## 結論 + +現在您已了解如何在 C# 中 **建立郵政條碼圖像** 檔案,透過設定尺寸、選擇正確的符號,並將結果儲存為 PNG。本教學說明了 **如何產生郵政條碼**,示範了 **產生 Planet 條碼**,並解釋了 **如何設定條碼尺寸** 以確保輸出一致。 + +接下來,您可以探索 **自訂條碼顏色**、加入 **可讀文字**,或將影像整合至 PDF 發票中。同樣的模式適用於 Aspose.BarCode 支援的任何其他條碼類型,讓您將此解決方案擴展為完整的郵政自動化工作流程。 + +## 接下來您應該學習什麼? + +以下教學涵蓋與本指南緊密相關的主題,建立在本教學示範的技術之上。每個資源皆提供完整的可執行程式碼範例與逐步說明,協助您精通其他 API 功能,並在專案中探索替代實作方式。 + +- [如何產生條碼 - 一維條碼類型](/barcode/english/net/one-dimensional-barcode-types/) +- [如何使用 Aspose.BarCode for .NET 產生自訂長寬比的 Aztec 條碼](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [如何產生 Java 條碼 – 使用 Aspose 的澳洲郵政條碼](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/hongkong/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..7e2d4f9ee --- /dev/null +++ b/barcode/hongkong/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-08-03 +description: 如何在 C# 中儲存條碼,並提供一步一步的條碼產生器範例。學習產生 Planet 條碼、設定尺寸以及匯出 PNG 圖片。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: zh-hant +lastmod: 2026-08-03 +og_description: 如何在 C# 中使用條碼產生器範例儲存條碼。本教學示範如何產生 Planet 條碼、設定 X 尺寸,並匯出 PNG 檔案。 +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: 如何在 C# 中儲存條碼 – 步驟指南 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: 如何在 C# 中儲存條碼 – 完整條碼產生器指南 +url: /zh-hant/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中儲存條碼 – 完整條碼產生器指南 + +在需要將郵政條碼嵌入發票、運送標籤或庫存標籤時,**在 C# 中儲存條碼圖像** 是常見需求。本指南將帶您完成實用的 **c# barcode generator** 工作流程,從建立 Planet 條碼到匯出實條(filled‑bars)與空條(empty‑bars)PNG 檔案。 + +您將學會設定條寬、切換實條模式,以及可靠地處理輸出資料夾。完成教學後,您將擁有一個完整可運作的 **barcode generator example**,可直接複製到任何 .NET 專案中。 + +## 您需要的條件 + +在撰寫程式碼之前,請確保您已具備: + +- .NET 6.0 SDK 或更新版本(範例同時支援 .NET Core 與 .NET Framework) +- Visual Studio 2022 或任何相容 C# 的 IDE +- **Aspose.BarCode** NuGet 套件(或其他支援 `EncodeTypes.Planet` 的函式庫)。使用以下指令安裝: + +```bash +dotnet add package Aspose.BarCode +``` + +此函式庫提供本教學中會不斷使用的 `BarcodeGenerator` 類別。 + +## 設定開發環境 + +建立一個新的主控台專案,並加入必要的命名空間: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +`System.IO` 命名空間提供 `Directory.CreateDirectory`,可在寫入檔案前確保輸出資料夾已存在。 + +## 使用 C# 條碼產生器儲存條碼圖像的方法 + +解決方案的核心是一組簡短步驟:設定 **Planet 條碼**,然後將圖像寫入磁碟。以下各節將此流程拆解為易於管理的片段。 + +### 步驟 1:定義輸出資料夾 + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**為什麼?** +硬編碼路徑在資料夾不存在的機器上會拋出 `DirectoryNotFoundException`。`CreateDirectory` 為冪等操作——只有在資料夾缺失時才會建立,讓程式在重複執行時更安全。 + +### 步驟 2:建立 Planet 條碼產生器(實條) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**為什麼?** +`EncodeTypes.Planet` 告訴函式庫產生郵政 Planet 條碼,這是郵件服務常用的格式。字串 `"123456"` 為示範用的資料,請依您的業務需求替換為任意數字資料。 + +### 步驟 3:設定條寬(X‑dimension)並保留預設實條 + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**為什麼?** +X‑dimension 控制每根條的實體寬度。`4` 像素在標準 300 dpi 印表機上即可產生可讀的條碼。保持 `FilledBars` 為 `true`(預設值)即可得到傳統的實條外觀。 + +### 步驟 4:儲存實條條碼圖像 + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**為什麼?** +以 PNG 格式儲存可保留無損影像品質,對掃描準確度相當重要。`Save` 方法會自動建立圖檔,只需提供完整路徑與目標格式。 + +### 步驟 5:為空條版本建立第二個產生器 + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +建立新實例可避免對已儲存的實條圖像產生影響,確保空條版本的設定獨立。 + +### 步驟 6:關閉實條,同時保留相同的 X‑dimension + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**為什麼?** +將 `FilledBars = false` 會只繪製每根條的輪廓,某些郵政標準要求以此方式進行目視驗證。 + +### 步驟 7:儲存空條條碼圖像 + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +現在您已擁有兩個 PNG 檔案——一個實條、一個空條——可直接嵌入 PDF、HTML 電子郵件或列印標籤中。 + +## 完整可執行程式 + +以下是可直接貼入 `Program.cs` 的完整程式碼。只要已安裝 Aspose.BarCode 套件,即可編譯執行,無需其他修改。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### 預期輸出 + +執行程式後會在主控台印出類似以下兩行文字: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +打開 `Barcodes` 資料夾,即可看到兩個 PNG 檔案。兩張圖皆可用任何影像檢視器開啟,或直接嵌入文件中。 + +![how to save barcode example](barcode-example.png){: .align-center alt="如何儲存條碼範例"} + +## 常見變化與邊緣案例 + +| 情境 | 調整方式 | +|----------|------------| +| **不同的影像格式** | 將 `BarCodeImageFormat.Png` 改為 `Jpeg`、`Gif` 或 `Bmp`。 | +| **自訂輸出尺寸** | 使用 `filled.Parameters.Image.Width` 與 `Height` 強制指定像素大小。 | +| **動態資料** | 將靜態的 `"123456"` 替換為儲存訂單編號、追蹤 ID 等的變數。 | +| **資料夾不存在** | `Directory.CreateDirectory` 已自行處理缺失的資料夾,無需額外程式碼。 | +| **高解析度列印** | 將 `XDimension.Pixels` 提升至 6–8 以因應 600 dpi 印表機,但請先驗證掃描器相容性。 | + +**專業小技巧:** 若需在迴圈中大量產生條碼,請重複使用同一個 `BarcodeGenerator` 實例,僅在每次 `Save` 前變更 `CodeText` 屬性,這樣可減少物件分配的開銷。 + +## 如何產生其他標準的條碼 + +相同的模式同樣適用於其他 `EncodeTypes`,例如 `Code128`、`QR` 或 `DataMatrix`。只要將 `EncodeTypes.Planet` 替換為目標類型,並依需求調整特定參數(例如 `QRCodeVersion`)即可。 + +## 接下來該學什麼? + +以下教學與本指南內容緊密相關,提供完整的程式碼範例與逐步說明,協助您掌握更多 API 功能,並在專案中探索其他實作方式。 + +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/hungarian/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..006584996 --- /dev/null +++ b/barcode/hungarian/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-08-03 +description: C#-os vonalkódgenerátor oktatóanyag, amely bemutatja, hogyan hozhatunk + létre Planet vonalkódot az Aspose.BarCode segítségével, beállíthatjuk az X-dimenziót, + és menthetjük PNG képként. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: hu +lastmod: 2026-08-03 +og_description: A C#-os vonalkód-generátor oktatóanyag végigvezet a Planet vonalkód + létrehozásán, az X‑dimenzió beállításán és az Aspose.BarCode használatával PNG formátumba + mentésen. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Vonalkód generátor C# – Planet vonalkód létrehozása lépésről lépésre +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Vonalkód generátor C# – Planet vonalkód és RM4SCC példa létrehozása +url: /hu/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – Planet vonalkód és RM4SCC példa létrehozása + +Ha szüksége van egy **barcode generator C#**-ra, amely képes postai specifikus szimbólumokat előállítani, ez az útmutató pontosan megmutatja, hogyan **hozzon létre Planet vonalkód** képeket az Aspose.BarCode segítségével. Meg fogja látni, hogyan állítsa be az X‑dimenziót, hogyan generáljon egy megfelelő RM4SCC vonalkódot, és hogyan mentse mindkettőt PNG fájlként – mindezt néhány tömör lépésben. + +Az útmutató mindent lefed, ami a kód .NET 6 vagy újabb verzión történő futtatásához szükséges, elmagyarázza, miért fontos minden beállítás, és kiemeli a gyakori hibákat, például a helytelen modul szélességet vagy a hiányzó könyvtárengedélyeket. A végére két nyomtatásra kész vonalkód képet kap, amelyek megfelelnek a Planet és RM4SCC szabványoknak. + +## Előfeltételek + +* .NET 6 SDK (vagy bármely, az Aspose.BarCode által támogatott .NET verzió) +* Visual Studio 2022 vagy bármely kedvelt C# IDE +* NuGet hivatkozás a **Aspose.BarCode**-ra (`Install-Package Aspose.BarCode`) +* Írási jogosultság a mappához, ahol a PNG fájlokat tárolni kívánja + +Nem szükséges további külső szolgáltatás; a könyvtár helyben kezeli az összes kódolást. + +## 1. lépés: A barcode generator C# objektum inicializálása + +Az első feladat egy `BarcodeGenerator` példány létrehozása. A konstruktor a vonalkód szimbólumát (`EncodeTypes.Planet`) és a kódolandó adatot veszi át. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Miért ez a lépés?* +`BarcodeGenerator` a belépési pont minden általad generált vonalkódhoz. Az `EncodeTypes.Planet` kiválasztása azt mondja a könyvtárnak, hogy kövesse a sok postai szolgáltató által használt ISO/IEC 24723 specifikációt. + +## 2. lépés: Az X‑dimenzió (modul szélesség) beállítása a Planet vonalkódhoz + +Az X‑dimenzió egyetlen vonalkód modul (a legkisebb vonal vagy szóköz) szélességét határozza meg. A **4 pixel** érték a legtöbb címkenyomtatóhoz jól működik. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Miért fontos ez* +Ha a modul túl keskeny, a vonalkód olvashatatlanná válhat; ha túl széles, a címke mérete indokolatlanul nő. A `Pixels` beállítása lehetővé teszi a vonalkód finomhangolását a konkrét nyomtató felbontásához. + +## 3. lépés: A Planet vonalkód mentése PNG képként + +Az Aspose.BarCode automatikusan kiszámítja a vonalkód magasságát a kiválasztott szimbólum alapján, így csak a fájl útvonalát és formátumát kell megadnia. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tipp* +Cserélje le a `YOUR_DIRECTORY`-t egy abszolút vagy relatív útvonalra, amely létezik a gépén. Ha a könyvtár nem létezik, a `Save` metódus `DirectoryNotFoundException`-t dob. + +**Várható kimenet** – egy PNG fájl, amely hasonló a lenti ábrához (a tényleges kép itt nincs megjelenítve, de egy klasszikus Planet vonalkódot fog látni `123456` numerikus payload-del). + +## 4. lépés: Második generátor inicializálása az RM4SCC vonalkódhoz + +Sok postai rendszer megköveteli, hogy a Planet és az RM4SCC szimbólumok egyaránt jelen legyenek ugyanazon a levélen. Hozzon létre egy új `BarcodeGenerator` példányt az RM4SCC szimbólumhoz. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Miért külön példány?* +Minden szimbólumnak saját paraméterkészlete van. Ugyanannak a generátornak az újrafelhasználása véletlenül átviheti a beállításokat (például az X‑dimenziót), amelyek nem optimálisak a második vonalkódhoz. + +## 5. lépés: Az X‑dimenzió beállítása az RM4SCC vonalkódhoz + +Az RM4SCC is szintén figyelembe veszi az X‑dimenzió beállítást, ezért ugyanazt a pixel szélességet alkalmazzuk a vizuális konzisztencia érdekében. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tipp* +Ha magasabb vonalkódra van szüksége (például nagyobb címkékhez), beállíthatja a `Height.Pixels`-t is. Ha nincs beállítva, a könyvtár automatikusan kiszámítja az ideális magasságot. + +## 6. lépés: Az RM4SCC vonalkód mentése PNG képként + +Végül mentse el az RM4SCC vonalkódot a lemezre. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Most már két PNG fájlja van – `PostalPlanetBarHeightNone.png` és `PostalRM4SCCBarHeightNone.png` – amelyeket beágyazhat a postacímkékbe, nyomtathat borítékokra, vagy elküldhet egy harmadik fél nyomtatási szolgáltatásának. + +## Opcionális: Magasság beállítása vagy más képformátumok használata + +Ha a munkafolyamatának egy adott vonalkód magasságra vagy más képformátumra (például JPEG vagy BMP) van szüksége, módosíthatja a paramétereket a `Save` hívása előtt: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Szélsőséges eset** – Ha egyedi magasságot állít be, győződjön meg róla, hogy az érték megfelel az ISO szabvány által előírt minimális magasságnak; ellenkező esetben a vonalkód nem felel meg az ellenőrzésnek. + +## Gyakori hibák és elkerülésük módjai + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| `DirectoryNotFoundException` | A célkönyvtár nem létezik vagy el van gépelve. | Hozza létre a könyvtárat először, vagy használja a `Path.Combine`-t az `Environment.CurrentDirectory`-val. | +| Barcode unreadable on low‑resolution printers | Az X‑dimenzió túl kicsi a nyomtató DPI-jéhez képest. | Növelje a `XDimension.Pixels` értékét 5‑6-ra 203 dpi nyomtatók esetén, vagy teszteljen egy mintacímkével. | +| Wrong symbology used | `EncodeTypes.Code128` átadása `EncodeTypes.Planet` helyett. | Ellenőrizze, hogy a `EncodeTypes` enum értéke megfelel a szükséges postai szabványnak. | +| Null reference on `Parameters` | Régebbi Aspose.BarCode verzió használata, ahol az API eltér. | Frissítsen a legújabb NuGet csomagra (v23.12 vagy újabb). | + +## Teljes futtatható példa + +Az alábbiakban a teljes program található, amelyet másolhat, beilleszthet és futtathat. Tartalmaz `using` utasításokat, hibakezelést és megjegyzéseket, amelyek minden sort magyaráznak. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +A program futtatása létrehoz egy `Barcodes` mappát a végrehajtható fájl mellett, és elhelyezi benne a két PNG fájlt. Nyissa meg őket bármely képnézővel a kimenet ellenőrzéséhez. + +## Következtetés + +Most már rendelkezik egy **barcode generator C#** megoldással, amely képes **Planet vonalkód** képeket létrehozni, az X‑dimenziót az optimális nyomtatáshoz beállítani, és egy megfelelő RM4SCC vonalkódot előállítani – mindezt néhány kódsorral. A megközelítés .NET 6+ környezetben működik, csak az Aspose.BarCode NuGet csomagra van szükség, és más szimbólumokra, például Code128, QR vagy DataMatrix kiterjeszthető az `EncodeTypes` érték cseréjével. + +### Mi a következő? + +* Kísérletezzen különböző `XDimension.Pixels` értékekkel, hogy megfeleljenek a nyomtató DPI-jének. +* Generáljon vonalkódokat más formátumokban (PDF, SVG) a `BarCodeImageFormat` enum módosításával. +* Kombinálja a két PNG fájlt egyetlen címkévé egy grafikus könyvtár, például a **SkiaSharp** használatával. +* Fedezze fel az Aspose.BarCode teljes API-ját fejlett funkciókhoz, például ellenőrzőösszeg validáláshoz vagy egyedi betűtípusokhoz. + +## Mit érdemes még 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 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 saját projektjeiben. + +- [Barcode PNG létrehozása – DataMatrix képarány – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [PNG mentése DataMatrix C40 használatával az Aspose.BarCode segítségével](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Code 16K vonalkód képarányainak testreszabása az Aspose.BarCode for .NET segítségével](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/hungarian/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..e4e7d9e42 --- /dev/null +++ b/barcode/hungarian/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-08-03 +description: A C#-os vonalkód-generátor oktatóanyag bemutatja, hogyan lehet vonalkódképet + generálni az Aspose.BarCode segítségével, beállítani az oszlopokat és sorokat, valamint + PNG fájlokként menteni a DataBar Expanded Stacked típusú vonalkódot. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: hu +lastmod: 2026-08-03 +og_description: A C# vonalkód-generátor oktatóanyag elmagyarázza, hogyan lehet vonalkód + képet generálni az Aspose.BarCode segítségével, beállítani a DataBar Expanded Stacked + oszlopokat és sorokat, valamint PNG fájlokként menteni. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: C# vonalkód generátor – lépésről lépésre útmutató a vonalkód kép generálásához +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Vonalkód generátor C# – vonalkód kép generálása +url: /hu/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – vonalkód kép generálása + +Ha szükséged van egy barcode generator C#-ra, amely képes DataBar Expanded Stacked vonalkód képet generálni, ez az útmutató végigvezet a teljes folyamaton. Megtanulod, hogyan konfigurálhatod az oszlop- és sorbeállításokat, mentheted az eredményt PNG-ként, és hogyan adaptálhatod a kódot más szimbólumokra. + +A vonalkód képek programozott generálása eltávolítja a manuális lépéseket és biztosítja a konzisztenciát a számlák, szállítási címkék és készletkezelő rendszerek között. Ez az oktatóanyag mindent lefed, ami szükséges, a projekt beállításától a teljes forráskódig, így azonnal futtathatod a példát. + +## Előkövetelmények + +* .NET 6.0 vagy újabb telepítve +* IDE, például Visual Studio 2022 (bármely C#-t támogató szerkesztő megfelelő) +* **Aspose.BarCode for .NET** licenc – az ingyenes értékelés teszteléshez megfelelő +* Alapvető ismeretek a C# szintaxisról + +Ha bármelyik elem hiányzik, telepítsd a .NET SDK-t a dotnet.microsoft.com oldalról, és szerezd be az Aspose.BarCode NuGet csomagot a következővel: + +```bash +dotnet add package Aspose.BarCode +``` + +## 1. lépés: Barcode generator C# projekt létrehozása + +Hozz létre egy új konzolos alkalmazást, és add hozzá a szükséges `using` direktívákat: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +A `BarcodeGenerator` osztály a barcode generator C# API központja. Fogadja a szimbólum típusát és a kódolandó szöveget. + +## 2. lépés: DataBar Expanded Stacked vonalkód generálása és oszlopok beállítása + +Az első példa négy oszlopos vonalkódot hoz létre. A `Columns` tulajdonság módosítása megváltoztatja a DataBar Expanded Stacked szimbólum vizuális sűrűségét. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Miért fontos:** Az oszlopszám befolyásolja a kompakt térben tárolható adatmennyiséget. 4‑re állítva szélesebb vonalkódot eredményez, amely a legtöbb szkenner számára olvasható marad. + +## 3. lépés: Vonalkód generálása egyedi sorok számával + +A második példa bemutatja, hogyan szabályozhatod a függőleges elrendezést a `Rows` tulajdonság beállításával. Három soros konfiguráció akkor hasznos, ha korlátozott vízszintes hely miatt magasabb vonalkódra van szükség. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Miért fontos:** A sorok módosítása lehetővé teszi, hogy a vonalkódot egy keskeny oszlopba illeszd, miközben megőrzöd az olvashatóságot. A barcode generator C# automatikusan újraszámolja a modulméretet a specifikáció teljesítéséhez. + +## 4. lépés: Teljes, futtatható példa + +Az alábbi önálló program egyesíti az előző lépéseket. Másold a kódot a `Program.cs` fájlba, cseréld le a `YOUR_DIRECTORY`-t egy létező mappára, és futtasd az alkalmazást. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Várt kimenet + +A program futtatásakor két PNG fájl jelenik meg a célkönyvtárban: + +* **DatabarCols4.png** – egy DataBar Expanded Stacked vonalkód négy oszloppal +* **DatabarRows3.png** – ugyanaz az adat három sorban kódolva + +Nyisd meg a képeket bármely képnézővel; éles, beolvasható vonalkódokat mutatnak, készen állva nyomtatásra vagy PDF-ekbe ágyazásra. + +## Hogyan generáljunk vonalkód képet egyedi méretekkel + +Ha egy adott képméretre van szükséged, állítsd be a `ImageHeight` és `ImageWidth` tulajdonságokat a `Save` hívása előtt: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +A méretek módosítása nem befolyásolja a kódolt adatot; csak a vizuális ábrázolást méretezi át. Ez a technika akkor hasznos, amikor a vonalkódokat rögzített elrendezésű UI komponensekbe integrálod. + +## Gyakori buktatók és profi tippek + +* **Útvonal elválasztók:** Használj verbatim stringeket (`@"C:\Path\file.png"`) vagy `Path.Combine`-t a Windows-on előforduló escape‑karakter problémák elkerüléséhez. +* **Licenc érvényesítés:** Érvényes licenc nélkül a generált képek vízjelét tartalmazzák. Alkalmazd a licencet a program elején: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Kódolási korlátok:** A DataBar Expanded Stacked legfeljebb 74 numerikus karaktert támogat. Ennek a korlátnak a túllépése kivételt dob. Ellenőrizd a bemenet hosszát a generátor létrehozása előtt. +* **Teljesítmény:** Egyetlen `BarcodeGenerator` példány újrahasználata több mentéshez csökkenti a memóriafoglalást. Csak akkor módosítsd a `Rows` vagy `Columns` tulajdonságokat a mentések között, ha a kódolt szöveg változatlan marad. + +## Következő lépések + +Most, hogy képes vagy vonalkód képeket generálni a barcode generator C#-val, fontold meg a következőket: + +* **Különböző szimbólumok** – próbáld ki a `EncodeTypes.QR`, `EncodeTypes.Code128` vagy `EncodeTypes.Pdf417` értékeket. +* **Szín testreszabás** – állítsd be a `Parameters.Barcode.ForeColor` és `BackColor` értékeket a márka színeinek megfelelően. +* **PDF-be ágyazás** – kombináld a generált PNG-t az Aspose.PDF-vel nyomtatható dokumentumok létrehozásához. + +Ezek a kiegészítések lehetővé teszik, hogy teljes körű vonalkód megoldást építs ki készletkezeléshez, logisztikához vagy kiskereskedelmi alkalmazásokhoz. + +--- + +## Mit érdemes még megtanulni? + +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 teljes, 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. + +- [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 generáljunk DataMatrix vonalkódokat (ECC 200) az Aspose.BarCode for .NET használatával](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/hungarian/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..f15734080 --- /dev/null +++ b/barcode/hungarian/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: C#-ban írt vonalkód-generátor példa, amely bemutatja, hogyan állítsuk + be a szélességet, hogyan változtassuk meg a magasságot, és hogyan generáljunk vonalkód + képet. Kövesse a lépésről‑lépésre útmutatót. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: hu +lastmod: 2026-08-03 +og_description: A vonalkód-generátor példa bemutatja az X‑dimenzió szélességének beállítását, + a vonalmagasság módosítását, és a vonalkód kép generálását C#‑ban. Kövesse a lépéseket + PNG fájlok létrehozásához. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Vonalkód-generátor példa – C# szélesség és magasság útmutató +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Vonalkód-generátor példa C#-ban – szélesség és magasság beállítása +url: /hu/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vonalkód-generátor példa C#-ban – szélesség és magasság beállítása + +Ha **barcode generator example**-ra van szükséged C#-ban, ez az útmutató megmutatja, hogyan állítsd be az X‑dimenzió szélességét, hogyan változtasd meg a vonal magasságát, és hogyan generálj vonalkód képfájlt. Egy teljes, futtatható programot láthatsz, amely két különböző magasságú PNG fájlt hoz létre. + +Egy tipikus eset a termékcímkék létrehozása, ahol a vonalkód méretének meg kell felelnie a szkenner specifikációinak. A tutorial végére képes leszel programozottan beállítani a szélesség és magasság paramétereket, és PNG képként menteni az eredményt. + +## Előkövetelmények + +* .NET 6 (vagy újabb) telepítve – a kód a .NET 6 SDK-ra céloz. +* Egy vonalkód könyvtár, amely támogatja a `EncodeTypes.DatabarOmniDirectional` értéket. A példa a **Aspose.BarCode for .NET**-et használja, de bármely hasonló tulajdonságokkal rendelkező könyvtár ugyanígy működik. +* Egy IDE vagy szerkesztő (Visual Studio, VS Code, Rider) a program fordításához és futtatásához. +* Írási jogosultság egy olyan könyvtárban, ahová a PNG fájlok mentésre kerülnek. + +> **Pro tip:** Hozz létre egy `Barcodes` nevű mappát a projekt gyökerében, és hivatkozz rá a `Path.Combine` segítségével, hogy elkerüld az abszolút útvonalak kézi kódolását. + +## Vonalkód-generátor példa: inicializálás és konfigurálás + +Az első lépés egy `BarcodeGenerator` példány létrehozása a kívánt szimbólummal és adatkarakterlánccal. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +A `EncodeTypes.DatabarOmniDirectional` enum a Databar Omni‑directional szimbólumot választja, és a GS1‑formátumú adatkarakterlánc `(01)12345678901231` egy tipikus GTIN‑14 értéket képvisel. A generátor egyszeri inicializálása lehetővé teszi, hogy ugyanazt az objektumot több képhez is újrahasználjuk. + +## Hogyan állítsuk be a szélességet (X‑dimenzió) + +Az X‑dimenzió szabályozza a vonalkód modul szélességét. 2 pixelre állítva minden keskeny vonal 2 pixel széles lesz, ami gyakori követelmény a nagy sűrűségű nyomtatásnál. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Miért fontos: Ha a szélesség túl kicsi, a szkennerek nem tudják feloldani az egyes vonalakat; ha túl nagy, a vonalkód meghaladhatja a címke helyét. Állítsd a pixel értéket a nyomtató DPI-jához és a célcímke méretéhez. + +## Hogyan változtassuk meg a magasságot + +A vonal magassága határozza meg, milyen magasak a vonalak. A példa két képet hoz létre: egyet 30 pixel magassággal, a másikat 60 pixel magassággal. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +A `BarHeight.Pixels` tulajdonság közvetlenül befolyásolja a vonalak vizuális magasságát. A mentések között történő módosítása lehetővé teszi, hogy ugyanabból az adatcsomagból több változatot generálj a generátor újra létrehozása nélkül. + +### Várható kimenet + +A program futtatása két PNG fájlt hoz létre a `Barcodes` mappában: + +* `DatabarBarHeight30Pixels.png` – a vonalak 30 pixel magasak. +* `DatabarBarHeight60Pixels.png` – a vonalak 60 pixel magasak. + +Mindkét kép ugyanazzal a szélességgel rendelkezik (az X‑dimenzió által meghatározott) és azonos GTIN‑14 adatot kódol. + +![Two barcode PNG files with different heights generated by C# code](barcode-example.png "Barcode generator example showing height variations") + +*A fenti kép alt szövege tartalmazza az elsődleges kulcsszót a hozzáférhetőség és SEO érdekében.* + +## Hogyan generáljunk vonalkód képet C#-ban + +A `Save` metódus kezeli a vonalkód adat átalakítását képfájlba. Más formátumokat (JPEG, BMP, SVG) választhatsz egy másik `BarCodeImageFormat` enum érték átadásával. A példa PNG-t használ, mivel veszteségmentes minőséget őriz meg és széles körben támogatott. + +Ha a vonalkódot közvetlenül PDF-be vagy weboldalra szeretnéd beágyazni, kérd le a képet `byte[]`-ként: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Ez a megközelítés megszünteti az ideiglenes fájlok szükségességét, és hasznos nagy áteresztőképességű szolgáltatásoknál. + +## Gyakori variációk és szélsőséges esetek + +| Situation | Adjustment | +|-----------|------------| +| **Más szimbólum** | Cseréld le a `EncodeTypes.DatabarOmniDirectional`-t egy másik enum értékre (pl. `EncodeTypes.Code128`). | +| **Nagyon kis címkék** | Csökkentsd a `XDimension.Pixels`-t 1 pixelre, de ellenőrizd a szkenner olvashatóságát. | +| **Nagy felbontású nyomtatás** | Növeld mind az X‑dimenziót, mind a vonal magasságát arányosan (pl. 4 px szélesség, 80 px magasság). | +| **Dinamikus adatok** | Add át az adatkarakterláncot futásidőben, esetleg egy adatbázis rekordból. | +| **Kötegelt generálás** | Iterálj egy adatkarakterlánc-gyűjteményen, újrahasználva ugyanazt a `BarcodeGenerator` példányt, miközben frissíted a `generator.Text`-et. | + +Ha olyan kivételt kapsz, mint a `ArgumentOutOfRangeException`, ellenőrizd, hogy a pixel értékek pozitív egész számok-e, és hogy a kimeneti könyvtár létezik-e. + +## Teljes forráskód összefoglaló + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Másold a kódot egy új konzolos projektbe, állítsd vissza az Aspose.BarCode NuGet csomagot (`dotnet add package Aspose.BarCode`), és futtasd a `dotnet run` parancsot. Konzolüzeneteket látsz, amelyek megerősítik a mentett fájlokat. + +## Következtetés + +Ez a **barcode generator example** bemutatja, hogyan állítsuk be a szélességet, hogyan változtassuk meg a magasságot, és hogyan generáljunk vonalkód képet C#-ban. Az `XDimension.Pixels` és a `BarHeight.Pixels` beállításával szabályozhatod a vonalkód vizuális méretét, a `Save` metódus pedig PNG fájlokba írja az eredményt. Kísérletezz különböző szimbólumokkal, kimeneti formátumokkal és adatkarakterláncokkal, hogy megfeleljenek az alkalmazásod követelményeinek. + +**Következő lépések** + +* Fedezd fel, hogyan **hogyan generáljunk vonalkódot** más képfájl formátumokban (SVG, JPEG) webes használatra. +* Tanuld meg, hogyan **create barcode image c#** ASP.NET Core végpontokhoz, amelyek közvetlenül a böngészőnek visszaküldik a PNG-t. +* Kombináld ezt a kódot egy PDF generáló könyvtárral, hogy vonalkódokat ágyazz be számlákba vagy szállítási címkékbe. + +Nyugodtan adaptáld a példát, oszd meg az eredményeidet, vagy tegyél fel kérdéseket a megjegyzésekben. Boldog kódolást! + +## Mit érdemes legközelebb megtanulni? + +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 teljes, működő kódpéldákat 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 – Egy-dimenziós vonalkód típusok](/barcode/english/net/one-dimensional-barcode-types/) +- [Hogyan állítsunk be keretet az ITF-14 vonalkód testreszabásához](/barcode/english/net/itf-14-barcode-customization/) +- [Hogyan generáljunk DataMatrix vonalkódokat (ECC 200) az Aspose.BarCode for .NET segítségével](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/hungarian/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..6a6f87a40 --- /dev/null +++ b/barcode/hungarian/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-03 +description: Készítsen vonalkód PNG-t C#-ban, és tanulja meg, hogyan változtathatja + meg a DataBar képek képarányát. Kövesse ezt a teljes példát kóddal és tippekkel. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: hu +lastmod: 2026-08-03 +og_description: Készítsen vonalkód PNG-t C#-ban, és tekintse meg, hogyan változtatható + a DataBar vonalkódok képaránya. Ez az útmutató kész, futtatható kódot és gyakorlati + tippeket nyújt. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Barcode PNG létrehozása C#‑ban – teljes példa aránykontrollal +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Barcode PNG létrehozása C#‑ban – lépésről‑lépésre útmutató +url: /hu/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode PNG létrehozása C#‑ban – lépésről‑lépésre útmutató + +Ha C#‑ban **barcode PNG**‑t kell létrehoznod, ez a tutorial pontosan megmutatja, hogyan. Generálni fogsz egy stacked omnidirectional DataBar vonalkódot, PNG fájlként mented, és megtanulod, **hogyan változtasd meg az arányt** különböző szkennelési környezetekhez. + +Az útmutató mindent lefed, amire szükséged van: a szükséges csomagok, egy teljes, futtatható program, és magyarázatok arra, hogy miért fontos minden beállítás. A végére két PNG fájlod lesz – egy 15‑ös, a másik 30‑as aránnyal – készen a tesztelésre vagy a termelésre. + +## Előfeltételek + +- .NET 6.0 SDK vagy újabb telepítve +- Visual Studio 2022 (vagy bármely C# IDE) +- NuGet hivatkozás a **Aspose.BarCode**‑ra (a könyvtár, amely biztosítja a `BarcodeGenerator`‑t) +- Írási jogosultság a könyvtárban, ahová a PNG fájlok mentésre kerülnek + +A Aspose.BarCode csomagot a következő paranccsal adhatod hozzá: + +```bash +dotnet add package Aspose.BarCode +``` + +## 1. lépés: A projekt beállítása és a névterek importálása + +Hozz létre egy új konzolos alkalmazást, és importáld a vonalkód generáláshoz és fájl I/O‑hoz szükséges névtereket. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Miért fontos:** Az `Aspose.BarCode.Generation` importálása hozzáférést biztosít a `BarcodeGenerator`‑hez. A kód `Main`‑ben tartása önállóvá és könnyen futtathatóvá teszi a példát. + +## 2. lépés: Vonalkód generátor létrehozása stacked omnidirectional DataBar‑hoz + +Példányosítsd a `BarcodeGenerator`‑t a `EncodeTypes.DatabarStackedOmniDirectional` típussal és egy minta GS1‑128 adatkarakterlánccal. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Miért fontos:** A kiválasztott kódolási típus egy nagy sűrűségű DataBar‑t hoz létre, amelyet a legtöbb modern szkenner be tud olvasni. Az adatkarakterlánc a GS1 Application Identifier (01) formátumot követi, ami gyakori a termékazonosítók esetén. + +## 3. lépés: Az X‑dimenzió (modul szélesség) meghatározása pixelekben + +Állítsd be a modul szélességét, hogy a vonalkód általános méretét szabályozd anélkül, hogy a olvashatóságát befolyásolná. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Miért fontos:** A 2 pixel X‑dimenzió olyan vonalkódot eredményez, amely sem túl kicsi a szkennerekhez, sem túl nagy a tipikus címkehelyekhez. + +## 4. lépés: Az első PNG mentése 15‑ös aránnyal + +Állítsd be a DataBar arányát, majd mentsd el a képet PNG fájlként. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Miért fontos:** Az arány szabályozza a stacked DataBar magasság‑szélesség arányát. A 15‑ös arány egy gyakori alapértelmezett, amely egyensúlyt teremt az olvashatóság és a címke magassága között. + +## 5. lépés: Az arány módosítása 30‑ra és a második PNG mentése + +Módosítsd ugyanazt a generátor példányt, hogy nagyobb arányt használjon, majd mentsd el a második képet. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Miért fontos:** Az arány növelése függőlegesen nyújtja a vonalkódot, ami javíthatja a szkennelés megbízhatóságát alacsony felbontású eszközökön vagy ha a címkét keskeny hordozóra nyomtatják. + +## Várt kimenet + +| Fájl | Arány | Megközelítő méretek (pixel) | +|------------------------------------|-------|-----------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (width × height) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (width × height) | + +Mindkét kép egy tiszta, beolvasható DataBar vonalkódot tartalmaz, amely a GS1 azonosítót `(01)12345678901231` kódolja. + +## Gyakori kérdések és szélhelyzetek + +### Hogyan változtassuk meg a többi vizuális tulajdonságot? + +A `generator.Parameters.Barcode` objektumon keresztül módosíthatod az előtér színét, a háttér színét, vagy hozzáadhatsz ember által olvasható szöveget. Például: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Mi van, ha más képformátumra van szükségem? + +Cseréld le a `BarCodeImageFormat.Png`‑t `Jpeg`-, `Bmp`- vagy `Gif`‑re igény szerint. A PNG marad a legjobb választás veszteségmentes vonalkód képekhez. + +### Befolyásolja az arány a szkennelési sebességet? + +A magasabb arányok növelik a vonalkód magasságát, ami javíthatja a szkennelés megbízhatóságát olyan eszközökön, amelyek nehezen olvassák a rövid stacked szimbólumokat. Azonban a rendkívül magas vonalkódok esetleg nem férnek el kis címkéken, ezért teszteld a célhardverrel. + +### Generálhatok több vonalkódot egy ciklusban? + +Igen. Hozz létre egy új `BarcodeGenerator` példányt minden adatkarakterlánchoz, vagy használd újra ugyanazt a példányt a `CodeText` és a `DataBar.AspectRatio` frissítésével. Ez a megközelítés csökkenti az objektum‑allokáció terhelését. + +## Profi tippek + +- **Használd újra a generátort**: Csak a `CodeText` vagy az `AspectRatio` módosítása elkerüli az objektum újra‑példányosítását, ami felgyorsítja a kötegelt feldolgozást. +- **Ellenőrizd a kimenetet**: Használj kézi szkennert vagy mobilalkalmazást, hogy megerősítsd, a generált PNG helyesen olvasható, mielőtt éles környezetbe helyeznéd. +- **Fájlnevezés**: Tedd bele az arányt a fájlnévbe (ahogy a példában), hogy a tesztelés során nyomon követhesd a változatokat. + +## Összegzés + +Most már tudod, hogyan **hozz létre barcode PNG** fájlokat C#‑ban, és pontosan **hogyan változtasd meg az arányt** stacked omnidirectional DataBar szimbólumoknál. A teljes példa bemutatja a inicializálást, az X‑dimenzió beállítását, az arány módosítását és a kép mentését – mindezt egyetlen, futtatható programban. + +Innen tovább felfedezheted a további vonalkód típusokat, kísérletezhetsz színekkel, vagy integrálhatod a generátort egy nagyobb jelentés- vagy készletkezelő rendszerbe. Boldog kódolást! + +## Mit érdemes még 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 teljes, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy elsajátíthasd a további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Barcode PNG létrehozása – DataMatrix arány – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Hogyan generáljunk Aztec vonalkódot egyedi aránnyal az Aspose.BarCode for .NET használatával](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Hogyan testre szabjuk a vonalkódot – Codablock F arány az Aspose.BarCode for .NET‑tel](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/hungarian/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..a758a2502 --- /dev/null +++ b/barcode/hungarian/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-08-03 +description: Készítsen barcode PNG-t gyorsan ezzel az útmutatóval. Tanulja meg, hogyan + generáljon vonalkód képet az Aspose.BarCode használatával, és hozza létre a planet + vonalkódot. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: hu +lastmod: 2026-08-03 +og_description: Készítsen vonalkód PNG-t azonnal. Ez az útmutató megmutatja, hogyan + lehet vonalkód képet generálni, és hogyan lehet planet vonalkódot létrehozni az + Aspose.BarCode használatával. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Barcode PNG létrehozása Pythonban – teljes programozási útmutató +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Barcode PNG létrehozása Pythonban – lépésről lépésre útmutató +url: /hu/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode PNG létrehozása Pythonban – lépésről‑lépésre útmutató + +Ha **barcode PNG** fájlokat szeretnél létrehozni Python‑alkalmazásodból, ez a tutorial pontosan megmutatja, hogyan. Végigvezetünk a **barcode kép** generálásán az Aspose.BarCode segítségével, és különösen **planet barcode** létrehozásán egyedi méretekkel. + +Megtanulod, hogyan telepítsd a könyvtárat, konfiguráld a Planet szimbólumot, állítsd be a méretparamétereket, és mentsd el az eredményt magas minőségű PNG‑ként. A útmutató alapvető Python‑tudást és a Python 3 (3.8 vagy újabb) friss verzióját feltételezi. Előzetes tapasztalat a vonalkód szabványokból nem szükséges. + +--- + +## Hogyan hozzunk létre barcode PNG-t az Aspose.BarCode-dal + +Ez a szakasz tartalmazza a **barcode PNG** létrehozásához szükséges fő lépéseket. Minden lépéshez tartozik egy kódrészlet, magyarázat, hogy miért fontos, és gyakorlati tippek, amelyeket azonnal alkalmazhatsz. + +### 1. Telepítsd az Aspose.BarCode csomagot + +Az Aspose egy tisztán Python‑os csomagot biztosít, amely a .NET‑core motorját csomagolja. Telepítsd a `pip`‑el: + +```bash +pip install aspose-barcode +``` + +*Miért fontos ez a lépés:* A csomag biztosítja a példában használt `BarcodeGenerator` osztályt. Globális telepítése garantálja, hogy az interpreter a futásidőben megtalálja az assembly‑t. + +### 2. Importáld a szükséges osztályokat + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Tippek:* Importáld csak a szükséges szimbólumokat; ez tisztán tartja a névtér­et és felgyorsítja a modul betöltését. + +### 3. Hozz létre egy barcode generátort a Planet szimbólumhoz + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Miért fontos:* Az `EncodeTypes.Planet` azt mondja a motornak, hogy a Planet vonalkód szabványt használja, míg a második argumentum a kódolandó adatot adja meg. A szimbólum megváltoztatása (pl. `EncodeTypes.Code128`) teljesen más vizuális mintát eredményez. + +### 4. Állítsd be az X dimenziót (modul szélesség) pixelben + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Magyarázat:* Az X dimenzió szabályozza a keskeny vonal szélességét. A 4 pixel érték mérsékelten sűrű vonalkódot eredményez, amely a legtöbb eszközön olvasható marad. + +### 5. Definiálj manuális vonalmagasságot pixelben + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Miért érdemes módosítani:* Egyes kiskereskedelmi nyomtatók magasabb vonalakat igényelnek a megbízható olvasáshoz. Az alapmagasság általában 50 px; 100 px‑re növelve javítja az olvashatóságot anélkül, hogy drámaian megnövelné a fájlméretet. + +### 6. Mentsd el a generált vonalkódot PNG képként + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Eredmény:* Egy **PlanetBarHeight100.png** nevű PNG fájl jelenik meg az `output` mappában. A PNG veszteségmentes, így ideális nyomtatáshoz és weboldalakba ágyazáshoz. + +### 7. Ellenőrizd a kimenetet (opcionális) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Tippek:* A kép megtekintése megerősíti, hogy a méretek megegyeznek a beállított paraméterekkel. Ha a vonalkód torzult, nézd át az X dimenziót vagy a vonalmagasság beállításait. + +--- + +## Hogyan generáljunk barcode képet PNG formátumban (alternatív beállítások) + +Ha más képfájltípust szeretnél, vagy később PDF‑be szeretnéd ágyazni a vonalkódot, módosíthatod a `BarCodeImageFormat` enum‑ot: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Miért fontos:* A PNG minden pixelt megőriz, ami kulcsfontosságú a magas kontrasztú vonalkódoknál. A JPEG tömörítési hibákat vezet be, amelyek zavarhatják a beolvasást, míg a BMP régebbi eszközökkel is kompatibilis. + +--- + +## Planet barcode generálása egyedi színekkel (haladó) + +A méret mellett testreszabhatod az előtér‑ és háttérszíneket is: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Gyakorlati tipp:* A magas kontrasztú színpárok (sötét a világoson) maximalizálják a szkenner megbízhatóságát. Kerüld a hasonló árnyalatok használatát az előtér és a háttér között. + +--- + +## Gyakori hibák és elkerülésük módjai + +| Tünet | Ok | Megoldás | +|-------|----|----------| +| A vonalkód nem olvasható | X dimension túl kicsi (≤ 2 px) | Növeld az `x_dimension.pixels` értékét legalább 3 px‑re | +| A kép elmosódott | PNG alacsony DPI‑vel mentve | Használd a `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` hívást 300 DPI megadásához (ha támogatott) | +| `ImportError` kivétel | Aspose.BarCode nincs telepítve | Futtasd a `pip install aspose-barcode` parancsot ugyanabban a környezetben, ahol a szkriptet futtatod | +| Rossz szimbólum | `EncodeTypes.Code128` lett használva `EncodeTypes.Planet` helyett | Cseréld le `EncodeTypes.Planet`‑ra a generátor létrehozásakor | + +--- + +## A teljes megoldás összefoglalása + +Az alábbiakban megtalálod a teljes, futtatható szkriptet, amely **barcode PNG**‑t hoz létre a kezdetektől a végéig: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +A szkript futtatása egy tiszta **Planet barcode PNG**‑t eredményez, amelyet beágyazhatsz HTML‑be, csatolhatsz e‑mailhez, vagy nyomtathatsz termékcímkékre. + +--- + +## Következő lépések és kapcsolódó témák + +* **Integráció Flask‑kel vagy Django‑val** – szolgáld ki a generált PNG‑t közvetlenül egy web‑endpointból. +* **Kötegelt generálás** – iterálj egy termék‑azonosítók listáján, hogy egy mappát tölts fel barcode PNG fájlokkal. +* **PDF generálással kombinálva** – használd az `aspose-pdf`‑t a PNG‑t számla vagy szállítási címke részeként elhelyezni. +* **Más szimbólumok felfedezése** – cseréld le a `EncodeTypes.Planet`‑t `EncodeTypes.QR`, `EncodeTypes.DataMatrix` vagy `EncodeTypes.Code128` értékekre, hogy különböző üzleti igényeket elégíts ki. + +A fenti lépések elsajátításával most már tudod, **hogyan generálj barcode képet** programozottan, és bővítheted a mintát bármely, az Aspose.BarCode által támogatott vonalkód szabványra. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/hungarian/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..411031db8 --- /dev/null +++ b/barcode/hungarian/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-08-03 +description: Készítsen postai vonalkód képet C#‑ban gyorsan. Tanulja meg, hogyan generáljon + postai vonalkódot, állítsa be a vonalkód méreteit, és generáljon Planet vonalkódot. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: hu +lastmod: 2026-08-03 +og_description: Készíts postai vonalkód képet C#-ban ezzel a teljes útmutatóval; tanuld + meg, hogyan állítsd be a vonalkód méreteit, generálj Planet vonalkódot, és készíts + RM4SCC vonalkódokat. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Postai vonalkód kép létrehozása C#-ban – teljes programozási útmutató +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Postai vonalkód kép létrehozása C#‑ban – lépésről lépésre útmutató +url: /hu/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Postai vonalkód kép létrehozása C#‑ban – lépésről‑lépésre útmutató + +Ha C#‑ban **postai vonalkód képet** kell létrehoznod, ez az útmutató pontosan megmutatja, hogyan. Kitérünk arra, **hogyan generáljunk postai vonalkódot**, **hogyan állítsuk be a vonalkód méreteit**, és arra, **hogyan generáljunk Planet vonalkódot** a gyakori postai szabványokhoz. + +A vége felé két használatra kész PNG fájl lesz – egy Planet vonalkód és egy RM4SCC vonalkód – mindegyik 100 px magas. Nincs szükség további eszközökre az Aspose.BarCode for .NET könyvtáron kívül. + +## Előfeltételek + +* .NET 6 SDK vagy újabb (a kód .NET Framework 4.7+‑vel is működik) +* Visual Studio 2022 vagy bármely C# IDE +* NuGet csomag **Aspose.BarCode** (az a könyvtár, amely biztosítja a `BarcodeGenerator`‑t) + +## 1. lépés: A vonalkód könyvtár telepítése + +Nyiss egy terminált a projekt mappádban, és futtasd: + +```bash +dotnet add package Aspose.BarCode +``` + +A csomag hozzáadja az `Aspose.BarCode` névteret, amely tartalmazza a `BarcodeGenerator`‑t és a postai vonalkódokhoz szükséges `EncodeTypes` felsorolást. + +## 2. lépés: A kimeneti mappa meghatározása + +Megbízható kimeneti útvonal létrehozása megakadályozza a futásidejű hibákat, ha a mappa nem létezik. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Miért fontos*: A `Directory.CreateDirectory` idempotens – csak akkor hozza létre a mappát, ha még nem létezik, így elkerülve a kivételeket a későbbi futtatások során. + +## 3. lépés: Általános vonalkód méretek konfigurálása + +Az X‑dimenzió (egyetlen vonal szélessége) és a teljes vonalmagasság beállítása lehetővé teszi a generált kép vizuális méretének szabályozását. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Hogyan állítsuk be a vonalkód méreteit**: A `Parameters.Barcode.XDimension.Pixels` tulajdonság határozza meg a keskeny vonal szélességét, míg a `Parameters.Barcode.BarHeight.Pixels` a teljes magasságot. Igazítsd ezeket az értékeket a postai szolgáltatód specifikációihoz. + +## 4. lépés: Planet vonalkód generálása + +A Planet egy széles körben használt postai vonalkód az Egyesült Királyságban. Az alábbi kód 100 px magas Planet vonalkódot hoz létre, és PNG‑ként menti. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Miért működik**: Az `EncodeTypes.Planet` megmondja a generátornak, hogy a Planet szimbólumot használja. A `Save` metódus PNG fájlt ír a megadott útvonalra, megőrizve a korábban beállított méreteket. + +## 5. lépés: RM4SCC vonalkód generálása + +Az RM4SCC a holland postai vonalkód szabvány. Az alábbi kód tükrözi a Planet példát, bemutatva, **hogyan generáljunk postai vonalkódot** egy másik típusra azonos méretekkel. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Mindkét PNG fájl most a `Barcodes` mappában található. Megnyitásuk tiszta, 100 px magas vonalkódot mutat, amely nyomtatásra vagy dokumentumokba ágyazásra készen áll. + +## Teljes forráskód + +Az alábbiakban a teljes, futtatható program látható, amely **postai vonalkód képeket** hoz létre mind a Planet, mind az RM4SCC szabványokhoz. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Várt kimenet + +A program futtatása kiírja a fájl útvonalakat, és két PNG fájlt hoz létre: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Minden kép 100 px magas, 4 pixel keskeny vonal szélességgel, megfelelve a beállított méreteknek. + +## Gyakorlati tippek és gyakori buktatók + +* **Mappa jogosultságok** – Ha a program korlátozott fiók alatt fut, győződj meg róla, hogy a célmappa írható. +* **Eltérő méretek** – Magasabb vonalkód létrehozásához növeld a `barHeightPixels` értékét. Finomabb felbontáshoz csökkentsd az `xDimensionPixels`‑t, de tartsd ≥ 2‑nél, hogy elkerüld a renderelési hibákat. +* **Egyéb postai szimbólumok** – Az Aspose.BarCode támogatja a `EncodeTypes.Postnet` és a `EncodeTypes.AustralianPost` értékeket is. Cseréld ki az `EncodeTypes` értékét, és tartsd meg ugyanazt a méretlogikát. +* **Képformátum** – Használd a `BarCodeImageFormat.Jpeg`‑et kisebb fájlmérethez, ha a veszteségmentes minőség nem szükséges. + +## Következtetés + +Most már tudod, hogyan **hozz létre postai vonalkód képeket** C#‑ban a méretek konfigurálásával, a megfelelő szimbólum kiválasztásával, és az eredmény PNG‑ként való mentésével. Az útmutató bemutatta, **hogyan generáljunk postai vonalkódot**, demonstrálta a **Planet vonalkód generálását**, és elmagyarázta, **hogyan állítsuk be a vonalkód méreteit** a konzisztens kimenethez. + +Ezután fedezd fel a **vonalkód színek testreszabását**, a **ember által olvasható szöveg** hozzáadását, vagy a képek PDF‑számlákba való integrálását. Ugyanaz a minta minden más, az Aspose.BarCode által támogatott vonalkód típusra is alkalmazható, lehetővé téve a megoldás kibővítését egy teljes postai automatizálási munkafolyamattá. + +## 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 elsajátíthasd a további API funkciókat, és alternatív megvalósítási megközelítéseket fedezhess fel saját projektjeidben. + +- [Hogyan generáljunk vonalkódot – Egy-dimenziós vonalkód típusok](/barcode/english/net/one-dimensional-barcode-types/) +- [Hogyan generáljunk Aztec vonalkódot egyedi képaránnyal az Aspose.BarCode for .NET használatával](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Hogyan generáljunk vonalkódot Java‑ban – Australia Post vonalkód az Aspose‑val](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/hungarian/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..257ba807c --- /dev/null +++ b/barcode/hungarian/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-08-03 +description: Hogyan mentse el a vonalkódot C#‑ban egy lépésről‑lépésre útmutatóval + a vonalkódgenerátor példával. Tanulja meg, hogyan generáljon Planet vonalkódokat, + állítson be méreteket, és exportáljon PNG képeket. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: hu +lastmod: 2026-08-03 +og_description: Hogyan menthetünk vonalkódot C#-ban egy vonalkód-generátor példával. + Ez az útmutató bemutatja, hogyan generálhatunk Planet vonalkódokat, állíthatjuk + be az X-dimenziót, és exportálhatunk PNG fájlokat. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Hogyan menthetünk vonalkódot C#‑ban – lépésről‑lépésre útmutató +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Hogyan menthetünk vonalkódot C#-ban – teljes vonalkód-generátor útmutató +url: /hu/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan mentse el a vonalkódot C#-ban – teljes vonalkód generátor útmutató + +A vonalkód képek mentése C#-ban gyakori követelmény, amikor postai vonalkódokat kell beágyazni számlákba, szállítási címkékbe vagy készletcímkékbe. Ez az útmutató végigvezet egy gyakorlati **c# barcode generator** munkafolyamaton, a Planet vonalkód létrehozásától a kitöltött és üres sávok PNG fájlok exportálásáig. + +Megtanulja, hogyan állítsa be a sáv szélességét, kapcsolja be vagy ki a kitöltött sávokat, és kezelje megbízhatóan a kimeneti mappákat. A tutorial végére egy teljesen működő **barcode generator example**-t kap, amelyet bármely .NET projektbe beilleszthet. + +## Amire szüksége lesz + +- .NET 6.0 SDK vagy újabb (a példa működik .NET Core és .NET Framework alatt) +- Visual Studio 2022 vagy bármely C#‑kompatibilis IDE +- A **Aspose.BarCode** NuGet csomag (vagy egy másik könyvtár, amely támogatja a `EncodeTypes.Planet`-et). Telepítse a következővel: + +```bash +dotnet add package Aspose.BarCode +``` + +A könyvtár biztosítja a `BarcodeGenerator` osztályt, amelyet a teljes tutorial során használunk. + +## Fejlesztőkörnyezet beállítása + +Hozzon létre egy új konzolos projektet, és adja hozzá a szükséges névteret: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +A `System.IO` névtér biztosítja a `Directory.CreateDirectory` metódust, amely garantálja, hogy a kimeneti mappa létezik, mielőtt fájlok írására próbálkoznánk. + +## Hogyan mentse el a vonalkód képeket a C# vonalkód generátorral + +A megoldás lényege egy kis lépéssorozat, amely beállít egy **Planet barcode**-t, majd lementi a képet a lemezre. A következő szakaszok a folyamatot kezelhető részekre bontják. + +### 1. lépés: A kimeneti mappa meghatározása + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Miért?** +Az útvonal keménykódolása `DirectoryNotFoundException`-t okozhat azon gépeken, ahol a mappa nem létezik. A `CreateDirectory` idempotens – csak akkor hozza létre a könyvtárat, ha hiányzik, így a kód biztonságos többszöri futtatásra. + +### 2. lépés: Planet vonalkód generátor létrehozása (kitöltött sávok) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Miért?** +A `EncodeTypes.Planet` azt mondja a könyvtárnak, hogy postai Planet vonalkódot állítson elő, amelyet széles körben használnak a postai szolgáltatók. A `"123456"` karakterlánc egy mintaadat; cserélje ki bármilyen numerikus adatra, amelyet az üzleti logikája megkövetel. + +### 3. lépés: A sáv szélességének (X‑dimenzió) beállítása és az alapértelmezett kitöltött sávok megtartása + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Miért?** +Az X‑dimenzió szabályozza minden egyes sáv fizikai szélességét. A `4` pixel érték olvasható vonalkódot eredményez a szabványos 300 dpi nyomtatókon. A `FilledBars` `true` (alapértelmezett) állapotának megtartása a klasszikus szilárd sávos megjelenést hozza. + +### 4. lépés: A kitöltött sávok vonalkód kép mentése + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Miért?** +PNG formátumban mentve a kép veszteségmentes minőségét őrzi, ami a beolvasási pontosság szempontjából fontos. A `Save` metódus automatikusan létrehozza a képfájlt; csak a teljes útvonalat és a kívánt formátumot kell megadni. + +### 5. lépés: Második generátor létrehozása az üres sávok verzióhoz + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Új példány létrehozása biztosítja, hogy az üres sávok verzióra végzett módosítások ne érintsék a már mentett kitöltött sávok képet. + +### 6. lépés: Kitöltött sávok letiltása azonos X‑dimenzió megtartásával + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Miért?** +A `FilledBars = false` beállítás csak a sávok körvonalát jeleníti meg, ami egyes postai szabványok szerint szükséges a vizuális ellenőrzéshez. + +### 7. lépés: Az üres sávok vonalkód kép mentése + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Most már két PNG fájlja van – egy kitöltött sávokkal és egy üres sávokkal – készen áll a PDF-ekbe, HTML e-mailekbe vagy nyomtatott címkékbe való beillesztésre. + +## Teljes futtatható program + +Az alábbiakban a teljes kód található, amelyet bemásolhat a `Program.cs` fájlba. Módosítás nélkül lefordítható és futtatható (feltéve, hogy az Aspose.BarCode csomag telepítve van). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Várt kimenet + +A program futtatása két, ehhez hasonló sort ír ki: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Nyissa meg a `Barcodes` mappát, és láthatja a két PNG fájlt. Mindkét kép megnyitható bármely képnézőben, vagy közvetlenül beágyazható dokumentumokba. + +![hogyan mentse el a vonalkód példát](barcode-example.png){: .align-center alt="hogyan mentse el a vonalkód példát"} + +## Gyakori variációk és szélsőséges esetek + +| Forgatókönyv | Módosítás | +|----------|------------| +| **Más képformátum** | Change `BarCodeImageFormat.Png` to `Jpeg`, `Gif`, or `Bmp` as needed. | +| **Egyéni kimeneti méret** | Use `filled.Parameters.Image.Width` and `Height` to force a specific pixel dimension. | +| **Dinamikus adatok** | Replace the static `"123456"` with a variable that holds order numbers, tracking IDs, etc. | +| **Nem létező mappa** | `Directory.CreateDirectory` already handles missing directories; no extra code required. | +| **Nagy felbontású nyomtatás** | Increase `XDimension.Pixels` to 6–8 for 600 dpi printers, but verify scanner compatibility. | + +**Pro tip:** Ha sok vonalkódot kell generálni egy ciklusban, használjon egyetlen `BarcodeGenerator` példányt, és csak a `CodeText` tulajdonságot módosítsa minden egyes `Save` előtt. Ez csökkenti az objektum-allocációs terhelést. + +## Hogyan generáljon vonalkódot más szabványokhoz + +Ugyanez a minta működik más `EncodeTypes` esetén, például `Code128`, `QR` vagy `DataMatrix`. Egyszerűen cserélje le a `EncodeTypes.Planet`-et a kívánt típusra, és állítsa be a típus‑specifikus paramétereket (pl. `QRCodeVersion` + +## Mit kellene legközelebb megtanulnia? + +A következő útmutatók 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 a saját projektjeiben. + +- [Hogyan mentse el a PNG-t DataMatrix C40 használatával az Aspose.BarCode segítségével](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Hogyan generáljon DataMatrix vonalkódokat (ECC 200) az Aspose.BarCode for .NET segítségével](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Hogyan generáljon vonalkódot – Code 39 konfiguráció az Aspose.BarCode segítségével](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/indonesian/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..bef8655b9 --- /dev/null +++ b/barcode/indonesian/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-08-03 +description: Tutorial generator barcode C# yang menunjukkan cara membuat barcode Planet + dengan Aspose.BarCode, mengatur dimensi X, dan menyimpan sebagai gambar PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: id +lastmod: 2026-08-03 +og_description: Tutorial generator barcode C# memandu Anda membuat barcode Planet, + menyesuaikan dimensi X, dan menyimpan sebagai PNG menggunakan Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Generator barcode C# – buat barcode Planet langkah demi langkah +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Generator barcode C# – contoh pembuatan barcode Planet dan RM4SCC +url: /id/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generator barcode C# – contoh pembuatan barcode Planet dan RM4SCC + +Jika Anda membutuhkan **barcode generator C#** yang dapat menghasilkan simbol khusus pos, panduan ini menunjukkan secara tepat cara **membuat barcode Planet** dengan Aspose.BarCode. Anda akan melihat cara mengkonfigurasi X‑dimension, menghasilkan barcode RM4SCC yang cocok, dan menyimpan keduanya sebagai file PNG—semua dalam beberapa langkah singkat. + +Tutorial ini mencakup semua yang Anda perlukan untuk menjalankan kode pada .NET 6 atau yang lebih baru, menjelaskan mengapa setiap pengaturan penting, dan menyoroti jebakan umum seperti lebar modul yang salah atau izin folder yang hilang. Pada akhir tutorial Anda akan memiliki dua gambar barcode siap cetak yang mematuhi standar Planet dan RM4SCC. + +## Prasyarat + +Sebelum memulai, pastikan Anda memiliki: + +* .NET 6 SDK (atau versi .NET apa pun yang didukung oleh Aspose.BarCode) +* Visual Studio 2022 atau IDE C# lain yang Anda sukai +* Referensi NuGet ke **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Izin menulis ke folder tempat Anda berencana menyimpan file PNG + +Tidak ada layanan eksternal tambahan yang diperlukan; perpustakaan menangani semua proses enkoding secara lokal. + +## Langkah 1: Inisialisasi objek barcode generator C# + +Tugas pertama adalah membuat instance `BarcodeGenerator`. Konstruktor menerima symbology barcode (`EncodeTypes.Planet`) dan data yang akan dienkode. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Mengapa langkah ini?* +`BarcodeGenerator` adalah titik masuk untuk setiap barcode yang Anda hasilkan. Memilih `EncodeTypes.Planet` memberi tahu perpustakaan untuk mengikuti spesifikasi ISO/IEC 24723 yang digunakan oleh banyak layanan pos. + +## Langkah 2: Atur X‑dimension (lebar modul) untuk barcode Planet + +X‑dimension mendefinisikan lebar satu modul barcode (garis atau spasi terkecil). Nilai **4 piksel** biasanya cocok untuk sebagian besar printer label. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Mengapa ini penting* +Jika modul terlalu sempit, barcode dapat menjadi tidak terbaca; terlalu lebar dan ukuran label menjadi tidak perlu besar. Menyesuaikan `Pixels` memungkinkan Anda menyetel barcode agar sesuai dengan resolusi printer spesifik Anda. + +## Langkah 3: Simpan barcode Planet sebagai gambar PNG + +Aspose.BarCode secara otomatis menghitung tinggi barcode berdasarkan symbology yang dipilih, jadi Anda hanya perlu menentukan jalur file dan formatnya. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tip* +Ganti `YOUR_DIRECTORY` dengan jalur absolut atau relatif yang ada di mesin Anda. Jika folder tidak ada, metode `Save` akan melempar `DirectoryNotFoundException`. + +**Output yang diharapkan** – sebuah file PNG yang terlihat serupa dengan ilustrasi di bawah (gambar sebenarnya tidak ditampilkan di sini, tetapi Anda akan melihat barcode Planet klasik dengan payload numerik `123456`). + +## Langkah 4: Inisialisasi generator kedua untuk barcode RM4SCC + +Banyak sistem pos memerlukan simbol Planet dan RM4SCC pada satu kiriman surat. Buat instance `BarcodeGenerator` baru untuk symbology RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Mengapa menggunakan instance terpisah?* +Setiap symbology memiliki kumpulan parameter masing‑masing. Menggunakan generator yang sama dapat secara tidak sengaja membawa pengaturan (seperti X‑dimension) yang tidak optimal untuk barcode kedua. + +## Langkah 5: Konfigurasikan X‑dimension untuk barcode RM4SCC + +RM4SCC juga menghormati pengaturan X‑dimension, jadi kami menerapkan lebar piksel yang sama untuk konsistensi visual. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +Jika Anda memerlukan barcode yang lebih tinggi (misalnya, untuk label yang lebih besar), Anda juga dapat mengatur `Height.Pixels`. Membiarkannya tidak diatur akan membuat perpustakaan menghitung tinggi ideal secara otomatis. + +## Langkah 6: Simpan barcode RM4SCC sebagai gambar PNG + +Akhirnya, simpan barcode RM4SCC ke disk. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Sekarang Anda memiliki dua file PNG—`PostalPlanetBarHeightNone.png` dan `PostalRM4SCCBarHeightNone.png`—yang dapat Anda sematkan dalam label pos, mencetak pada amplop, atau mengirim ke layanan cetak pihak ketiga. + +## Opsional: Menyesuaikan tinggi atau menggunakan format gambar lain + +Jika alur kerja Anda memerlukan tinggi barcode tertentu atau format gambar berbeda (misalnya JPEG atau BMP), Anda dapat memodifikasi parameter sebelum memanggil `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Kasus tepi** – Saat Anda menetapkan tinggi khusus, pastikan nilai tersebut memenuhi tinggi minimum yang diwajibkan oleh standar ISO; jika tidak, barcode dapat gagal validasi. + +## Kesalahan umum dan cara menghindarinya + +| Masalah | Mengapa terjadi | Solusi | +|---------|----------------|--------| +| `DirectoryNotFoundException` | Folder target tidak ada atau salah ketik. | Buat folder terlebih dahulu atau gunakan `Path.Combine` dengan `Environment.CurrentDirectory`. | +| Barcode tidak terbaca pada printer beresolusi rendah | X‑dimension terlalu kecil untuk DPI printer. | Tingkatkan `XDimension.Pixels` menjadi 5 – 6 untuk printer 203 dpi, atau uji dengan label contoh. | +| Symbology yang salah digunakan | Mengirim `EncodeTypes.Code128` alih‑alih `EncodeTypes.Planet`. | Periksa kembali nilai enum `EncodeTypes` agar sesuai dengan standar pos yang diperlukan. | +| Null reference pada `Parameters` | Menggunakan versi Aspose.BarCode yang lebih lama dimana API berbeda. | Tingkatkan ke paket NuGet terbaru (v23.12 atau lebih baru). | + +## Contoh lengkap yang dapat dijalankan + +Berikut adalah program lengkap yang dapat Anda salin, tempel, dan jalankan. Termasuk pernyataan `using`, penanganan error, dan komentar yang menjelaskan setiap baris. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Menjalankan program akan membuat folder `Barcodes` di samping executable dan menempatkan dua file PNG di dalamnya. Buka dengan penampil gambar apa pun untuk memverifikasi hasilnya. + +## Kesimpulan + +Anda kini memiliki solusi **barcode generator C#** yang dapat **membuat gambar barcode Planet**, menyesuaikan X‑dimension untuk pencetakan optimal, dan menghasilkan barcode RM4SCC yang cocok—semua dengan beberapa baris kode. Pendekatan ini bekerja dengan .NET 6+, hanya memerlukan paket NuGet Aspose.BarCode, dan dapat diperluas ke symbology lain seperti Code128, QR, atau DataMatrix dengan mengganti nilai `EncodeTypes`. + +### Apa selanjutnya? + +* Bereksperimen dengan nilai `XDimension.Pixels` yang berbeda untuk menyesuaikan DPI printer Anda. +* Hasilkan barcode dalam format lain (PDF, SVG) dengan mengubah enum `BarCodeImageFormat`. +* Gabungkan dua file PNG menjadi satu label menggunakan perpustakaan grafis seperti **SkiaSharp**. +* Jelajahi seluruh API Aspose.BarCode untuk fitur lanjutan seperti validasi checksum atau font khusus. + +Silakan sesuaikan kode untuk pemrosesan batch atau integrasikan ke layanan web ASP.NET Core yang mengembalikan gambar barcode sesuai permintaan. 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 dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Buat Barcode PNG – Rasio Aspek DataMatrix – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Cara Menyimpan PNG menggunakan DataMatrix C40 dengan Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [tutorial generator barcode c# – Kustomisasi Rasio Aspek Barcode Code 16K dengan Aspose.BarCode untuk .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/indonesian/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..9e3a33d5e --- /dev/null +++ b/barcode/indonesian/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-08-03 +description: Tutorial generator barcode C# menunjukkan cara menghasilkan gambar barcode + dengan Aspose.BarCode, mengatur kolom dan baris, serta menyimpan file PNG untuk + DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: id +lastmod: 2026-08-03 +og_description: Tutorial generator barcode C# menjelaskan cara menghasilkan gambar + barcode menggunakan Aspose.BarCode, mengkonfigurasi kolom dan baris DataBar Expanded + Stacked, serta menyimpan file PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Generator Barcode C# – panduan langkah demi langkah untuk membuat gambar + barcode +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Generator Barcode C# – menghasilkan gambar barcode +url: /id/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generator barcode C# – menghasilkan gambar barcode + +Jika Anda membutuhkan barcode generator C# yang dapat menghasilkan gambar barcode untuk DataBar Expanded Stacked, panduan ini akan memandu Anda melalui proses lengkap. Anda akan belajar cara mengonfigurasi pengaturan kolom dan baris, menyimpan hasil sebagai PNG, dan menyesuaikan kode untuk simbol lainnya. + +Menghasilkan gambar barcode secara programatik menghilangkan langkah manual dan memastikan konsistensi di seluruh faktur, label pengiriman, dan sistem inventaris. Tutorial ini mencakup semua yang Anda perlukan, mulai dari penyiapan proyek hingga kode sumber lengkap, sehingga Anda dapat menjalankan contoh segera. + +## Prasyarat + +Sebelum Anda memulai, pastikan Anda memiliki: + +* .NET 6.0 atau yang lebih baru terpasang +* IDE seperti Visual Studio 2022 (editor apa pun yang mendukung C# dapat digunakan) +* Lisensi untuk **Aspose.BarCode for .NET** – evaluasi gratis dapat digunakan untuk pengujian +* Familiaritas dasar dengan sintaks C# + +Jika salah satu hal di atas belum ada, instal .NET SDK dari dotnet.microsoft.com dan dapatkan paket NuGet Aspose.BarCode dengan: + +```bash +dotnet add package Aspose.BarCode +``` + +## Langkah 1: Buat proyek barcode generator C# + +Buat aplikasi console baru dan tambahkan direktif `using` yang diperlukan: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +Kelas `BarcodeGenerator` adalah inti dari API barcode generator C#. Ia menerima tipe simbol dan teks yang akan dienkode. + +## Langkah 2: Hasilkan barcode DataBar Expanded Stacked dan atur kolom + +Contoh pertama membuat barcode dengan empat kolom. Menyesuaikan properti `Columns` mengubah kepadatan visual simbol DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Mengapa ini penting:** Jumlah kolom memengaruhi jumlah data yang dapat disimpan dalam ruang yang kompak. Menetapkannya ke 4 menghasilkan barcode yang lebih lebar namun tetap dapat dibaca oleh sebagian besar pemindai. + +## Langkah 3: Hasilkan barcode dengan jumlah baris khusus + +Contoh kedua menunjukkan cara mengontrol tata letak vertikal dengan mengatur properti `Rows`. Konfigurasi tiga baris berguna ketika Anda memerlukan barcode yang lebih tinggi karena ruang horizontal terbatas. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Mengapa ini penting:** Menyesuaikan baris memungkinkan Anda menempatkan barcode dalam kolom sempit sambil mempertahankan keterbacaan. Barcode generator C# secara otomatis menghitung ulang ukuran modul untuk memenuhi spesifikasi. + +## Langkah 4: Contoh lengkap yang dapat dijalankan + +Berikut adalah program mandiri yang menggabungkan langkah‑langkah sebelumnya. Salin kode ke dalam `Program.cs`, ganti `YOUR_DIRECTORY` dengan jalur folder yang ada, dan jalankan aplikasi. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Output yang diharapkan + +Saat Anda menjalankan program, dua file PNG muncul di direktori target: + +* **DatabarCols4.png** – barcode DataBar Expanded Stacked dengan empat kolom +* **DatabarRows3.png** – data yang sama dienkode dalam tiga baris + +Buka gambar dengan penampil gambar apa pun; mereka menampilkan barcode tajam dan dapat dipindai, siap untuk dicetak atau disematkan dalam PDF. + +## Cara menghasilkan gambar barcode dengan dimensi khusus + +Jika Anda memerlukan ukuran gambar tertentu, sesuaikan properti `ImageHeight` dan `ImageWidth` sebelum memanggil `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Mengubah dimensi tidak memengaruhi data yang dienkode; hanya memperbesar representasi visual. Teknik ini berguna saat mengintegrasikan barcode ke dalam komponen UI dengan batasan tata letak tetap. + +## Kesalahan umum dan tips profesional + +* **Pememisah jalur:** Gunakan string verbatim (`@"C:\Path\file.png"`) atau `Path.Combine` untuk menghindari masalah karakter escape pada Windows. +* **Penegakan lisensi:** Tanpa lisensi yang valid, gambar yang dihasilkan berisi watermark. Terapkan lisensi Anda di awal aplikasi: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Batas enkoding:** DataBar Expanded Stacked mendukung hingga 74 karakter numerik. Melebihi batas ini akan menimbulkan pengecualian. Validasi panjang input sebelum membuat generator. +* **Kinerja:** Menggunakan satu instance `BarcodeGenerator` untuk beberapa penyimpanan mengurangi alokasi memori. Hanya ubah properti `Rows` atau `Columns` di antara penyimpanan jika teks yang dienkode tetap sama. + +## Langkah selanjutnya + +Sekarang Anda dapat menghasilkan gambar barcode dengan barcode generator C#, pertimbangkan untuk menjelajahi: + +* **Simbol berbeda** – coba `EncodeTypes.QR`, `EncodeTypes.Code128`, atau `EncodeTypes.Pdf417`. +* **Kustomisasi warna** – atur `Parameters.Barcode.ForeColor` dan `BackColor` agar sesuai dengan merek. +* **Penyematan dalam PDF** – gabungkan PNG yang dihasilkan dengan Aspose.PDF untuk membuat dokumen yang dapat dicetak. + +Ekstensi ini memungkinkan Anda membangun solusi barcode lengkap untuk aplikasi inventaris, logistik, atau ritel. + +--- + + +## 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 Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/indonesian/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..8b856e546 --- /dev/null +++ b/barcode/indonesian/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: Contoh generator barcode dalam C# yang menunjukkan cara mengatur lebar, + cara mengubah tinggi, dan cara menghasilkan gambar barcode. Ikuti petunjuk langkah + demi langkah. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: id +lastmod: 2026-08-03 +og_description: Contoh generator barcode menunjukkan cara mengatur lebar dimensi X, + mengubah tinggi bar, dan menghasilkan gambar barcode dalam C#. Ikuti langkah-langkah + untuk membuat file PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Contoh generator barcode – Panduan lebar dan tinggi C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Contoh generator barcode di C# – atur lebar dan tinggi +url: /id/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Contoh generator barcode dalam C# – mengatur lebar dan tinggi + +Jika Anda membutuhkan **contoh generator barcode** dalam C#, panduan ini menunjukkan cara mengatur lebar X‑dimension, cara mengubah tinggi bar, dan cara menghasilkan file gambar barcode. Anda akan melihat program lengkap yang dapat dijalankan yang menghasilkan dua file PNG dengan tinggi yang berbeda. + +Skenario umum adalah membuat label produk di mana ukuran barcode harus memenuhi spesifikasi pemindai. Pada akhir tutorial ini Anda akan dapat menyesuaikan parameter lebar dan tinggi secara programatis dan menyimpan hasilnya sebagai gambar PNG. + +## Prasyarat + +* .NET 6 (atau yang lebih baru) terpasang – kode menargetkan .NET 6 SDK. +* Sebuah perpustakaan barcode yang mendukung `EncodeTypes.DatabarOmniDirectional`. Contoh ini menggunakan **Aspose.BarCode for .NET**, tetapi perpustakaan apa pun yang menyediakan properti serupa berfungsi dengan cara yang sama. +* IDE atau editor (Visual Studio, VS Code, Rider) untuk mengompilasi dan menjalankan program. +* Izin menulis ke direktori tempat file PNG akan disimpan. + +> **Pro tip:** Buat folder bernama `Barcodes` di root proyek Anda dan referensikan dengan `Path.Combine` untuk menghindari hard‑coding jalur absolut. + +## Contoh generator barcode: inisialisasi dan konfigurasi + +Langkah pertama adalah membuat instance `BarcodeGenerator` dengan simbolologi dan string data yang diinginkan. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +Enum `EncodeTypes.DatabarOmniDirectional` memilih simbolologi Databar Omni‑directional, dan string data berformat GS1 `(01)12345678901231` mewakili nilai GTIN‑14 yang umum. Menginisialisasi generator sekali memungkinkan Anda menggunakan kembali objek yang sama untuk beberapa gambar. + +## Cara mengatur lebar (X‑dimension) + +X‑dimension mengontrol lebar modul barcode. Menetapkannya menjadi 2 pixel membuat setiap bar tipis berukuran 2 pixel, yang merupakan kebutuhan umum untuk pencetakan ber‑densitas tinggi. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Mengapa ini penting: Jika lebar terlalu kecil, pemindai mungkin tidak dapat membedakan bar individu; jika terlalu besar, barcode dapat melebihi ruang label. Sesuaikan nilai pixel untuk mencocokkan DPI printer dan ukuran label target. + +## Cara mengubah tinggi + +Tinggi bar menentukan seberapa tinggi bar muncul. Contoh ini membuat dua gambar: satu dengan tinggi 30 pixel dan satu lagi dengan tinggi 60 pixel. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Properti `BarHeight.Pixels` secara langsung memengaruhi tinggi visual bar. Mengubahnya di antara penyimpanan memungkinkan Anda menghasilkan beberapa varian dari payload data yang sama tanpa membuat ulang generator. + +### Output yang diharapkan + +Menjalankan program menghasilkan dua file PNG di folder `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – bar setinggi 30 pixel. +* `DatabarBarHeight60Pixels.png` – bar setinggi 60 pixel. + +Kedua gambar memiliki lebar yang sama (ditentukan oleh X‑dimension) dan mengkodekan data GTIN‑14 yang identik. + +![Dua file PNG barcode dengan tinggi berbeda yang dihasilkan oleh kode C#](barcode-example.png "Contoh generator barcode yang menunjukkan variasi tinggi") + +*Teks alt gambar di atas berisi kata kunci utama untuk aksesibilitas dan SEO.* + +## Cara menghasilkan gambar barcode dalam C# + +Metode `Save` menangani konversi dari data barcode ke file gambar. Anda dapat memilih format lain (JPEG, BMP, SVG) dengan memberikan nilai enum `BarCodeImageFormat` yang berbeda. Contoh ini menggunakan PNG karena mempertahankan kualitas lossless dan didukung secara luas. + +Jika Anda perlu menyematkan barcode langsung ke PDF atau halaman web, ambil gambar sebagai `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Pendekatan ini menghilangkan kebutuhan akan file sementara dan berguna untuk layanan dengan throughput tinggi. + +## Variasi umum dan kasus tepi + +| Situasi | Penyesuaian | +|-----------|------------| +| **Simbolologi berbeda** | Ganti `EncodeTypes.DatabarOmniDirectional` dengan nilai enum lain (misalnya, `EncodeTypes.Code128`). | +| **Label sangat kecil** | Kurangi `XDimension.Pixels` menjadi 1 pixel, tetapi verifikasi keterbacaan oleh pemindai. | +| **Pencetakan resolusi tinggi** | Tingkatkan baik X‑dimension maupun tinggi bar secara proporsional (misalnya, lebar 4 px, tinggi 80 px). | +| **Data dinamis** | Berikan string data pada waktu runtime, mungkin dari catatan basis data. | +| **Generasi batch** | Lakukan loop pada koleksi string data, menggunakan kembali instance `BarcodeGenerator` yang sama sambil memperbarui `generator.Text`. | + +Ketika Anda menemui pengecualian seperti `ArgumentOutOfRangeException`, periksa kembali bahwa nilai pixel adalah bilangan bulat positif dan bahwa direktori output ada. + +## Ringkasan kode sumber lengkap + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Salin kode ke dalam proyek console baru, pulihkan paket NuGet Aspose.BarCode (`dotnet add package Aspose.BarCode`), dan jalankan `dotnet run`. Anda akan melihat pesan konsol yang mengonfirmasi file yang disimpan. + +## Kesimpulan + +Contoh **generator barcode** ini menunjukkan cara mengatur lebar, cara mengubah tinggi, dan cara menghasilkan gambar barcode dalam C#. Dengan menyesuaikan `XDimension.Pixels` dan `BarHeight.Pixels` Anda mengontrol ukuran visual barcode, dan metode `Save` menulis hasilnya ke file PNG. Bereksperimenlah dengan simbolologi berbeda, format output, dan string data untuk menyesuaikan kebutuhan aplikasi Anda. + +**Langkah selanjutnya** + +* Jelajahi **cara menghasilkan barcode** dalam format gambar lain (SVG, JPEG) untuk penggunaan web. +* Pelajari **cara membuat gambar barcode c#** untuk endpoint ASP.NET Core yang mengembalikan PNG langsung ke browser. +* Gabungkan kode ini dengan perpustakaan pembuatan PDF untuk menyematkan barcode ke faktur atau label pengiriman. + +Silakan sesuaikan contoh ini, bagikan hasil Anda, atau ajukan pertanyaan di komentar. Selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya 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 - Jenis Barcode Satu Dimensi](/barcode/english/net/one-dimensional-barcode-types/) +- [Cara Mengatur Border untuk Kustomisasi Barcode ITF-14](/barcode/english/net/itf-14-barcode-customization/) +- [Cara Menghasilkan Barcode DataMatrix (ECC 200) dengan Aspose.BarCode untuk .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/indonesian/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..0ed5b8d6a --- /dev/null +++ b/barcode/indonesian/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-08-03 +description: Buat PNG barcode dalam C# dan pelajari cara mengubah rasio aspek untuk + gambar DataBar. Ikuti contoh lengkap ini dengan kode dan tips. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: id +lastmod: 2026-08-03 +og_description: Buat barcode PNG dengan C# dan pelajari cara mengubah rasio aspek + untuk barcode DataBar. Panduan ini menyediakan kode siap‑jalankan dan tips praktis. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Buat barcode PNG di C# – contoh lengkap dengan kontrol rasio aspek +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Buat barcode PNG di C# – panduan langkah demi langkah +url: /id/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Membuat barcode PNG di C# – panduan langkah demi langkah + +Jika Anda perlu **membuat barcode PNG** di C#, tutorial ini menunjukkan secara tepat caranya. Anda akan menghasilkan barcode DataBar omnidirectional bertumpuk, menyimpannya sebagai file PNG, dan mempelajari **cara mengubah rasio aspek** untuk menyesuaikan dengan berbagai lingkungan pemindaian. + +Panduan ini mencakup semua yang Anda perlukan: paket yang diperlukan, program lengkap yang dapat dijalankan, dan penjelasan mengapa setiap pengaturan penting. Pada akhir tutorial Anda akan memiliki dua file PNG—satu dengan rasio aspek 15 dan satu lagi dengan 30—siap untuk pengujian atau penggunaan produksi. + +## Prasyarat + +Sebelum memulai, pastikan Anda memiliki: + +- .NET 6.0 SDK atau yang lebih baru terpasang +- Visual Studio 2022 (atau IDE C# apa pun) +- Referensi NuGet ke **Aspose.BarCode** (perpustakaan yang menyediakan `BarcodeGenerator`) +- Izin menulis ke direktori tempat file PNG akan disimpan + +Anda dapat menambahkan paket Aspose.BarCode dengan perintah berikut: + +```bash +dotnet add package Aspose.BarCode +``` + +## Langkah 1: Siapkan proyek dan impor namespace + +Buat aplikasi konsol baru dan impor namespace yang diperlukan untuk pembuatan barcode serta I/O file. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Mengapa ini penting:** Mengimpor `Aspose.BarCode.Generation` memberi Anda akses ke `BarcodeGenerator`. Menjaga kode di dalam `Main` membuat contoh ini mandiri dan mudah dijalankan. + +## Langkah 2: Buat generator barcode untuk DataBar omnidirectional bertumpuk + +Instansiasi `BarcodeGenerator` dengan tipe `EncodeTypes.DatabarStackedOmniDirectional` dan string data contoh GS1‑128. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Mengapa ini penting:** Tipe enkode yang dipilih menghasilkan DataBar berkapasitas tinggi yang dapat dibaca oleh sebagian besar pemindai modern. String data mengikuti format GS1 Application Identifier (01), yang umum untuk pengidentifikasi produk. + +## Langkah 3: Tentukan dimensi X (lebar modul) dalam piksel + +Atur lebar modul untuk mengendalikan ukuran keseluruhan barcode tanpa memengaruhi keterbacaannya. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Mengapa ini penting:** Dimensi X sebesar 2 piksel menghasilkan barcode yang tidak terlalu kecil bagi pemindai maupun tidak terlalu besar untuk ruang label tipikal. + +## Langkah 4: Simpan PNG pertama dengan rasio aspek 15 + +Sesuaikan rasio aspek DataBar, lalu simpan gambar sebagai file PNG. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Mengapa ini penting:** Rasio aspek mengontrol hubungan tinggi‑dengan‑lebar dari DataBar bertumpuk. Rasio 15 adalah nilai default umum yang menyeimbangkan keterbacaan dan tinggi label. + +## Langkah 5: Ubah rasio aspek menjadi 30 dan simpan PNG kedua + +Modifikasi instance generator yang sama untuk menggunakan rasio aspek yang lebih besar, lalu simpan gambar kedua. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Mengapa ini penting:** Meningkatkan rasio aspek memperpanjang barcode secara vertikal, yang dapat meningkatkan keandalan pemindaian pada perangkat beresolusi rendah atau ketika label dicetak pada media sempit. + +## Output yang diharapkan + +Menjalankan program akan membuat dua file PNG: + +| File | Rasio Aspek | Dimensi perkiraan (piksel) | +|------------------------------------|-------------|----------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (lebar × tinggi) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (lebar × tinggi) | + +Kedua gambar berisi barcode DataBar yang jelas dan dapat dipindai, yang mengenkode identifier GS1 `(01)12345678901231`. + +## Pertanyaan umum dan kasus tepi + +### Bagaimana cara mengubah properti visual lainnya? + +Anda dapat menyesuaikan warna latar depan, warna latar belakang, atau menambahkan teks yang dapat dibaca manusia melalui objek `generator.Parameters.Barcode`. Contohnya: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Bagaimana jika saya membutuhkan format gambar yang berbeda? + +Ganti `BarCodeImageFormat.Png` dengan `Jpeg`, `Bmp`, atau `Gif` sesuai kebutuhan. PNG tetap pilihan terbaik untuk gambar barcode tanpa kehilangan kualitas. + +### Apakah rasio aspek memengaruhi kecepatan pemindaian? + +Rasio aspek yang lebih tinggi meningkatkan tinggi barcode, yang dapat memperbaiki keandalan pemindaian pada perangkat yang kesulitan dengan simbol bertumpuk pendek. Namun, barcode yang sangat tinggi mungkin tidak muat pada label kecil, jadi lakukan pengujian dengan perangkat target Anda. + +### Bisakah saya menghasilkan beberapa barcode dalam sebuah loop? + +Ya. Buat instance `BarcodeGenerator` baru untuk setiap string data atau gunakan kembali instance yang sama sambil memperbarui `CodeText` dan `DataBar.AspectRatio`. Pendekatan ini mengurangi beban alokasi objek. + +## Tips profesional + +- **Gunakan kembali generator**: Mengubah hanya `CodeText` atau `AspectRatio` menghindari pembuatan ulang objek, yang mempercepat pemrosesan batch. +- **Validasi output**: Gunakan pemindai genggam atau aplikasi seluler untuk memastikan PNG yang dihasilkan dapat dibaca dengan benar sebelum diterapkan ke produksi. +- **Penamaan file**: Sertakan rasio aspek dalam nama file (seperti yang ditunjukkan) untuk melacak variasi selama pengujian. + +## Kesimpulan + +Anda kini tahu cara **membuat barcode PNG** di C# dan secara tepat **mengubah rasio aspek** untuk simbol DataBar omnidirectional bertumpuk. Contoh lengkap menunjukkan inisialisasi, pengaturan dimensi X, manipulasi rasio aspek, dan penyimpanan gambar—semua dalam satu program yang dapat dijalankan. + +Dari sini Anda dapat menjelajahi tipe barcode tambahan, bereksperimen dengan warna, atau mengintegrasikan generator ke dalam sistem pelaporan atau inventaris yang lebih besar. 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. + +- [Buat Barcode PNG – Rasio Aspek DataMatrix – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Cara menghasilkan barcode Aztec dengan rasio aspek khusus menggunakan Aspose.BarCode untuk .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cara Menyesuaikan Barcode - Rasio Aspek Codablock F dengan Aspose.BarCode untuk .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/indonesian/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..ae8691308 --- /dev/null +++ b/barcode/indonesian/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-08-03 +description: Buat PNG barcode dengan cepat menggunakan panduan ini. Pelajari cara + menghasilkan gambar barcode menggunakan Aspose.BarCode dan buat barcode planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: id +lastmod: 2026-08-03 +og_description: Buat PNG barcode secara instan. Tutorial ini menunjukkan cara menghasilkan + gambar barcode dan membuat barcode planet dengan Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Buat barcode PNG di Python – panduan pemrograman lengkap +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Buat barcode PNG di Python – panduan langkah demi langkah +url: /id/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Membuat barcode PNG di Python – panduan langkah‑demi‑langkah + +Jika Anda perlu **membuat file barcode PNG** dari aplikasi Python Anda, tutorial ini menunjukkan cara melakukannya secara tepat. Kami akan membahas **cara menghasilkan gambar barcode** menggunakan Aspose.BarCode dan secara khusus **menghasilkan barcode planet** dengan dimensi khusus. + +Anda akan belajar cara menginstal pustaka, mengonfigurasi simbol Planet, menyesuaikan parameter ukuran, dan menyimpan hasilnya sebagai PNG berkualitas tinggi. Panduan ini mengasumsikan pengetahuan dasar Python dan versi Python 3 terbaru (3.8 atau lebih baru). Tidak diperlukan pengalaman sebelumnya dengan standar barcode. + +--- + +## Cara membuat barcode PNG dengan Aspose.BarCode + +Bagian ini berisi langkah‑langkah inti yang diperlukan untuk **membuat barcode PNG**. Setiap langkah menyertakan cuplikan kode, penjelasan mengapa langkah tersebut penting, dan tip praktis yang dapat Anda terapkan segera. + +### 1. Instal paket Aspose.BarCode + +Aspose menyediakan paket pure‑Python yang membungkus mesin .NET core-nya. Instal dengan `pip`: + +```bash +pip install aspose-barcode +``` + +*Mengapa langkah ini penting:* Paket menyediakan kelas `BarcodeGenerator` yang digunakan sepanjang contoh. Menginstalnya secara global memastikan interpreter dapat menemukan assembly pada saat runtime. + +### 2. Impor kelas yang diperlukan + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Tip:* Impor hanya simbol yang Anda perlukan; ini menjaga namespace tetap bersih dan mempercepat pemuatan modul. + +### 3. Buat generator barcode untuk simbol Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Mengapa ini penting:* `EncodeTypes.Planet` memberi tahu mesin untuk menggunakan standar barcode Planet, sementara argumen kedua menyediakan data yang akan dienkode. Mengubah simbol (misalnya, `EncodeTypes.Code128`) akan menghasilkan pola visual yang sama sekali berbeda. + +### 4. Atur dimensi X (lebar modul) dalam piksel + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Penjelasan:* Dimensi X mengontrol lebar bar sempit. Nilai 4 piksel menghasilkan barcode dengan kepadatan sedang yang tetap dapat dipindai pada kebanyakan perangkat. + +### 5. Tentukan tinggi bar manual dalam piksel + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Mengapa Anda mungkin menyesuaikannya:* Beberapa printer ritel memerlukan bar yang lebih tinggi untuk pemindaian yang andal. Tinggi default biasanya 50 px; meningkatkan menjadi 100 px meningkatkan keterbacaan tanpa memperbesar ukuran file secara dramatis. + +### 6. Simpan barcode yang dihasilkan sebagai gambar PNG + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Hasil:* File PNG bernama **PlanetBarHeight100.png** muncul di folder `output`. PNG bersifat loss‑less, menjadikannya ideal untuk pencetakan dan penyematan di halaman web. + +### 7. Verifikasi output (opsional) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Tip:* Melihat gambar memastikan dimensi sesuai dengan parameter yang Anda atur. Jika barcode tampak terdistorsi, tinjau kembali pengaturan dimensi X atau tinggi bar. + +--- + +## Cara menghasilkan gambar barcode dalam format PNG (pengaturan alternatif) + +Jika Anda memerlukan format gambar lain atau ingin menyematkan barcode ke PDF nanti, Anda dapat mengubah enum `BarCodeImageFormat`: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Mengapa ini penting:* PNG mempertahankan setiap piksel, yang krusial untuk barcode dengan kontras tinggi. JPEG menambahkan artefak kompresi yang dapat mengganggu pemindaian, sementara BMP menawarkan kompatibilitas dengan alat yang lebih lama. + +--- + +## Menghasilkan barcode planet dengan warna khusus (lanjutan) + +Selain ukuran, Anda dapat menyesuaikan warna latar depan dan latar belakang: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Tip praktis:* Pasangan warna kontras tinggi (gelap di atas terang) memaksimalkan keandalan pemindai. Hindari menggunakan nuansa serupa untuk latar depan dan latar belakang. + +--- + +## Kesalahan umum dan cara menghindarinya + +| Gejala | Penyebab | Solusi | +|--------|----------|--------| +| Barcode tidak dapat dipindai | Dimensi X terlalu kecil (≤ 2 px) | Tingkatkan `x_dimension.pixels` menjadi setidaknya 3 px | +| Gambar terlihat buram | PNG disimpan dengan DPI rendah | Gunakan `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` untuk menentukan 300 DPI (jika didukung) | +| Exception `ImportError` | Aspose.BarCode belum diinstal | Jalankan `pip install aspose-barcode` di lingkungan yang sama dengan skrip Anda | +| Simbol salah | Menggunakan `EncodeTypes.Code128` alih‑alih `EncodeTypes.Planet` | Ganti dengan `EncodeTypes.Planet` saat membuat generator | + +--- + +## Ringkasan solusi lengkap + +Berikut adalah skrip lengkap yang dapat dijalankan untuk **membuat barcode PNG** dari awal hingga akhir: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Menjalankan skrip ini menghasilkan **barcode Planet PNG** yang tajam, yang dapat Anda sematkan di HTML, lampirkan pada email, atau cetak pada label produk. + +--- + +## Langkah selanjutnya dan topik terkait + +* **Integrasi dengan Flask atau Django** – layani PNG yang dihasilkan langsung dari endpoint web. +* **Generasi batch** – iterasi daftar ID produk untuk membuat folder berisi file barcode PNG. +* **Kombinasi dengan pembuatan PDF** – gunakan `aspose-pdf` untuk menempatkan PNG ke dalam faktur atau label pengiriman. +* **Jelajahi simbol lain** – ganti `EncodeTypes.Planet` dengan `EncodeTypes.QR`, `EncodeTypes.DataMatrix`, atau `EncodeTypes.Code128` untuk memenuhi kebutuhan bisnis yang berbeda. + +Dengan menguasai langkah‑langkah di atas, Anda kini tahu **cara menghasilkan gambar barcode** secara programatis dan dapat memperluas pola tersebut ke standar barcode apa pun yang didukung oleh Aspose.BarCode. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/indonesian/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..be14c78b1 --- /dev/null +++ b/barcode/indonesian/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-08-03 +description: Buat gambar barcode pos dengan cepat menggunakan C#. Pelajari cara menghasilkan + barcode pos, mengatur dimensi barcode, dan menghasilkan barcode Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: id +lastmod: 2026-08-03 +og_description: Buat gambar barcode pos di C# dengan tutorial lengkap ini; pelajari + cara mengatur dimensi barcode, menghasilkan barcode Planet, dan membuat barcode + RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Buat gambar kode batang pos di C# – panduan pemrograman lengkap +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Buat gambar kode batang pos di C# – panduan langkah demi langkah +url: /id/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat gambar barcode pos di C# – panduan langkah demi langkah + +Jika Anda perlu **membuat gambar barcode pos** di C#, panduan ini menunjukkan cara melakukannya secara tepat. Kami akan membahas **cara menghasilkan barcode pos**, **cara mengatur dimensi barcode**, dan cara **menghasilkan barcode planet** untuk standar pos yang umum. + +Anda akan selesai dengan dua file PNG siap pakai—satu barcode Planet dan satu barcode RM4SCC—masing‑masing setinggi 100 px. Tidak diperlukan alat tambahan selain pustaka Aspose.BarCode untuk .NET. + +## Prasyarat + +* .NET 6 SDK atau yang lebih baru (kode juga berfungsi dengan .NET Framework 4.7+) +* Visual Studio 2022 atau IDE C# apa pun +* Paket NuGet **Aspose.BarCode** (pustaka yang menyediakan `BarcodeGenerator`) + +## Langkah 1: Instal pustaka barcode + +Buka terminal di folder proyek Anda dan jalankan: + +```bash +dotnet add package Aspose.BarCode +``` + +Paket ini menambahkan namespace `Aspose.BarCode`, yang berisi `BarcodeGenerator` dan enumerasi `EncodeTypes` yang diperlukan untuk barcode pos. + +## Langkah 2: Tentukan folder output + +Membuat jalur output yang dapat diandalkan mencegah kesalahan runtime ketika folder belum ada. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Mengapa ini penting*: `Directory.CreateDirectory` bersifat idempotent—hanya membuat folder jika belum ada, sehingga menghindari pengecualian pada eksekusi berikutnya. + +## Langkah 3: Konfigurasikan dimensi barcode umum + +Menetapkan X‑dimension (lebar satu bar) dan tinggi bar keseluruhan memungkinkan Anda mengontrol ukuran visual gambar yang dihasilkan. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Cara mengatur dimensi barcode**: Properti `Parameters.Barcode.XDimension.Pixels` menentukan lebar bar sempit, sementara `Parameters.Barcode.BarHeight.Pixels` menentukan tinggi penuh. Sesuaikan nilai‑nilai ini agar memenuhi spesifikasi layanan pengiriman Anda. + +## Langkah 4: Hasilkan barcode Planet + +Planet adalah barcode pos yang banyak digunakan di Britania Raya. Kode berikut membuat barcode Planet setinggi 100 px dan menyimpannya sebagai PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Mengapa ini berhasil**: `EncodeTypes.Planet` memberi tahu generator untuk menggunakan simbol Planet. Metode `Save` menulis file PNG ke jalur yang ditentukan, mempertahankan dimensi yang telah kita setel sebelumnya. + +## Langkah 5: Hasilkan barcode RM4SCC + +RM4SCC adalah standar barcode pos Belanda. Kode di bawah ini meniru contoh Planet, memperlihatkan **cara menghasilkan barcode pos** dengan tipe berbeda namun dengan dimensi yang sama. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Kedua file PNG kini berada di folder `Barcodes`. Membukanya akan menampilkan barcode bersih setinggi 100 px siap untuk dicetak atau disisipkan dalam dokumen. + +## Kode sumber lengkap + +Berikut adalah program lengkap yang dapat dijalankan untuk **membuat file gambar barcode pos** bagi standar Planet dan RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Output yang diharapkan + +Menjalankan program akan mencetak jalur file dan membuat dua file PNG: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Setiap gambar setinggi 100 px, dengan lebar bar sempit 4 pixel, sesuai dengan dimensi yang telah kita setel. + +## Tips praktis dan jebakan umum + +* **Izin folder** – Jika program dijalankan dengan akun terbatas, pastikan folder target dapat ditulisi. +* **Dimensi berbeda** – Untuk membuat barcode yang lebih tinggi, tingkatkan `barHeightPixels`. Untuk resolusi lebih halus, turunkan `xDimensionPixels`, tetapi pertahankan ≥ 2 agar tidak muncul artefak rendering. +* **Simbolologi pos lainnya** – Aspose.BarCode juga mendukung `EncodeTypes.Postnet` dan `EncodeTypes.AustralianPost`. Ganti nilai `EncodeTypes` dan pertahankan logika dimensi yang sama. +* **Format gambar** – Gunakan `BarCodeImageFormat.Jpeg` untuk ukuran file lebih kecil bila kualitas lossless tidak diperlukan. + +## Kesimpulan + +Anda kini tahu cara **membuat file gambar barcode pos** di C# dengan mengonfigurasi dimensi, memilih simbolologi yang tepat, dan menyimpan hasilnya sebagai PNG. Tutorial ini mencakup **cara menghasilkan barcode pos**, memperlihatkan **menghasilkan barcode planet**, dan menjelaskan **cara mengatur dimensi barcode** untuk output yang konsisten. + +Selanjutnya, jelajahi **penyesuaian warna barcode**, menambahkan **teks yang dapat dibaca manusia**, atau mengintegrasikan gambar ke dalam faktur PDF. Pola yang sama berlaku untuk tipe barcode lain yang didukung Aspose.BarCode, memungkinkan Anda memperluas solusi ini menjadi alur kerja otomatisasi pos yang lengkap. + +## 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 dapat dijalankan dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to generate barcode java – Australia Post Barcode with Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/indonesian/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..2a4138587 --- /dev/null +++ b/barcode/indonesian/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-08-03 +description: Cara menyimpan barcode di C# dengan contoh generator barcode langkah + demi langkah. Pelajari cara menghasilkan barcode Planet, mengatur dimensi, dan mengekspor + gambar PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: id +lastmod: 2026-08-03 +og_description: Cara menyimpan barcode di C# menggunakan contoh generator barcode. + Tutorial ini menunjukkan cara menghasilkan barcode Planet, mengatur dimensi X, dan + mengekspor file PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Cara menyimpan barcode di C# – panduan langkah demi langkah +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Cara menyimpan barcode di C# – panduan lengkap generator barcode +url: /id/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara menyimpan barcode di C# – panduan lengkap generator barcode + +Menyimpan gambar barcode di C# adalah kebutuhan umum ketika Anda perlu menyematkan barcode pos ke dalam faktur, label pengiriman, atau tag inventaris. Panduan ini memandu Anda melalui alur kerja **c# barcode generator** yang praktis, mulai dari membuat barcode Planet hingga mengekspor file PNG dengan bar terisi dan bar kosong. + +Anda akan belajar cara mengatur lebar bar, mengaktifkan/menonaktifkan bar terisi, dan menangani folder output dengan andal. Pada akhir tutorial Anda akan memiliki **barcode generator example** yang berfungsi penuh yang dapat Anda salin ke proyek .NET mana pun. + +## Apa yang Anda butuhkan + +- .NET 6.0 SDK atau lebih baru (contoh ini bekerja dengan .NET Core dan .NET Framework) +- Visual Studio 2022 atau IDE kompatibel C# apa pun +- Paket NuGet **Aspose.BarCode** (atau perpustakaan lain yang mendukung `EncodeTypes.Planet`). Instal dengan: + +```bash +dotnet add package Aspose.BarCode +``` + +Perpustakaan ini menyediakan kelas `BarcodeGenerator` yang digunakan sepanjang tutorial ini. + +## Menyiapkan lingkungan pengembangan + +Buat proyek konsol baru dan tambahkan namespace yang diperlukan: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +Namespace `System.IO` memberi kita `Directory.CreateDirectory`, yang memastikan folder output ada sebelum kita mencoba menulis file. + +## Cara menyimpan gambar barcode dengan generator barcode C# + +Inti solusi adalah serangkaian langkah kecil yang mengonfigurasi **Planet barcode** dan kemudian menyimpan gambar ke disk. Bagian berikut memecah proses menjadi bagian‑bagian yang dapat dikelola. + +### Langkah 1: Tentukan folder output + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Mengapa?** +Menetapkan jalur secara hard‑code dapat menyebabkan `DirectoryNotFoundException` pada mesin di mana folder tidak ada. `CreateDirectory` bersifat idempotent—hanya membuat direktori jika belum ada, sehingga kode aman untuk dijalankan berulang kali. + +### Langkah 2: Buat generator Planet barcode (bar terisi) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Mengapa?** +`EncodeTypes.Planet` memberi tahu perpustakaan untuk menghasilkan barcode Planet pos, yang banyak digunakan oleh layanan pos. String `"123456"` adalah contoh payload; ganti dengan data numerik apa pun yang diperlukan oleh logika bisnis Anda. + +### Langkah 3: Konfigurasikan lebar bar (dimensi X) dan pertahankan bar terisi default + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Mengapa?** +Dimensi X mengontrol lebar fisik setiap bar. Nilai `4` piksel menghasilkan barcode yang dapat dibaca pada printer standar 300 dpi. Membiarkan `FilledBars` sebagai `true` (default) menghasilkan tampilan bar solid klasik. + +### Langkah 4: Simpan gambar barcode bar terisi + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Mengapa?** +Menyimpan sebagai PNG mempertahankan kualitas gambar lossless, yang penting untuk akurasi pemindaian. Metode `Save` secara otomatis membuat file gambar; Anda hanya perlu menyediakan jalur lengkap dan format yang diinginkan. + +### Langkah 5: Buat generator kedua untuk versi bar kosong + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Membuat instance baru memastikan bahwa perubahan yang dibuat untuk versi bar kosong tidak memengaruhi gambar bar terisi yang sudah disimpan. + +### Langkah 6: Nonaktifkan bar terisi sambil mempertahankan dimensi X yang sama + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Mengapa?** +Mengatur `FilledBars = false` menghasilkan barcode hanya dengan outline setiap bar, yang beberapa standar pos butuhkan untuk verifikasi visual. + +### Langkah 7: Simpan gambar barcode bar kosong + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Sekarang Anda memiliki dua file PNG—satu dengan bar terisi dan satu dengan bar kosong—siap untuk dimasukkan ke dalam PDF, email HTML, atau label cetak. + +## Program lengkap yang dapat dijalankan + +Berikut adalah kode lengkap yang dapat Anda salin ke `Program.cs`. Kode ini dapat dikompilasi dan dijalankan tanpa modifikasi (asumsi paket Aspose.BarCode telah terinstal). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Output yang diharapkan + +Menjalankan program mencetak dua baris serupa dengan: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Buka folder `Barcodes` dan Anda akan melihat dua file PNG. Kedua gambar dapat dibuka di penampil gambar apa pun atau disematkan langsung ke dalam dokumen. + +![contoh cara menyimpan barcode](barcode-example.png){: .align-center alt="contoh cara menyimpan barcode"} + +## Variasi umum dan kasus tepi + +| Skenario | Penyesuaian | +|----------|------------| +| **Format gambar berbeda** | Ubah `BarCodeImageFormat.Png` menjadi `Jpeg`, `Gif`, atau `Bmp` sesuai kebutuhan. | +| **Ukuran output khusus** | Gunakan `filled.Parameters.Image.Width` dan `Height` untuk memaksa dimensi piksel tertentu. | +| **Data dinamis** | Ganti `"123456"` statis dengan variabel yang berisi nomor pesanan, ID pelacakan, dll. | +| **Folder tidak ada** | `Directory.CreateDirectory` sudah menangani folder yang tidak ada; tidak diperlukan kode tambahan. | +| **Pencetakan resolusi tinggi** | Tingkatkan `XDimension.Pixels` menjadi 6–8 untuk printer 600 dpi, tetapi verifikasi kompatibilitas pemindai. | + +**Tips pro:** Jika Anda perlu menghasilkan banyak barcode dalam loop, gunakan kembali satu instance `BarcodeGenerator` dan hanya ubah properti `CodeText` sebelum setiap `Save`. Ini mengurangi overhead alokasi objek. + +## Cara menghasilkan barcode untuk standar lain + +Pola yang sama bekerja untuk `EncodeTypes` lain seperti `Code128`, `QR`, atau `DataMatrix`. Cukup ganti `EncodeTypes.Planet` dengan tipe yang diinginkan dan sesuaikan parameter khusus tipe apa pun (mis., `QRCodeVersion`). + +## 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 menjelajahi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [Cara Menyimpan PNG menggunakan DataMatrix C40 dengan Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Cara Menghasilkan Barcode DataMatrix (ECC 200) dengan Aspose.BarCode untuk .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Cara Menghasilkan Barcode – Konfigurasi Code 39 dengan Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/italian/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..5848dca91 --- /dev/null +++ b/barcode/italian/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-08-03 +description: Tutorial C# per generatore di codici a barre che mostra come creare un + codice a barre Planet con Aspose.BarCode, impostare la dimensione X e salvare come + immagini PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: it +lastmod: 2026-08-03 +og_description: Il tutorial del generatore di codici a barre C# ti guida nella creazione + di un codice a barre Planet, nella regolazione della dimensione X e nel salvataggio + come PNG usando Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Generatore di codici a barre C# – crea il codice a barre Planet passo dopo + passo +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Generatore di codici a barre C# – crea esempio di codice Planet e RM4SCC +url: /it/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generatore di codici a barre C# – creare esempio di Planet barcode e RM4SCC + +Se hai bisogno di un **barcode generator C#** che possa produrre simboli specifici per la posta, questa guida ti mostra esattamente come **creare Planet barcode** con Aspose.BarCode. Vedrai come configurare la X‑dimension, generare un RM4SCC barcode corrispondente e salvare entrambi come file PNG—tutto in pochi passaggi concisi. + +Il tutorial copre tutto ciò di cui hai bisogno per eseguire il codice su .NET 6 o versioni successive, spiega perché ogni impostazione è importante e segnala le insidie comuni, come larghezza del modulo errata o permessi di directory mancanti. Alla fine avrai due immagini di codici a barre pronte per la stampa che rispettano gli standard Planet e RM4SCC. + +## Prerequisiti + +* .NET 6 SDK (o qualsiasi versione .NET supportata da Aspose.BarCode) +* Visual Studio 2022 o qualsiasi IDE C# che preferisci +* Un riferimento NuGet a **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Permesso di scrittura sulla cartella in cui prevedi di memorizzare i file PNG + +Non sono richiesti servizi esterni aggiuntivi; la libreria gestisce tutta la codifica localmente. + +## Passo 1: Inizializzare l'oggetto barcode generator C# + +Il primo compito è creare un'istanza di `BarcodeGenerator`. Il costruttore accetta la simbologia del codice a barre (`EncodeTypes.Planet`) e i dati da codificare. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Perché questo passo?* +`BarcodeGenerator` è il punto di ingresso per ogni codice a barre che generi. Selezionare `EncodeTypes.Planet` indica alla libreria di seguire la specifica ISO/IEC 24723 utilizzata da molti servizi postali. + +## Passo 2: Impostare la X‑dimension (larghezza del modulo) per il Planet barcode + +La X‑dimension definisce la larghezza di un singolo modulo del codice a barre (la barra o lo spazio più piccolo). Un valore di **4 pixel** funziona bene per la maggior parte delle stampanti di etichette. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Perché è importante* +Se il modulo è troppo stretto, il codice a barre potrebbe diventare illeggibile; se è troppo largo, la dimensione dell'etichetta aumenta inutilmente. Regolare `Pixels` ti consente di perfezionare il codice a barre per la risoluzione specifica della tua stampante. + +## Passo 3: Salvare il Planet barcode come immagine PNG + +Aspose.BarCode calcola automaticamente l'altezza del codice a barre in base alla simbologia selezionata, quindi devi solo specificare il percorso del file e il formato. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Suggerimento* +Sostituisci `YOUR_DIRECTORY` con un percorso assoluto o relativo che esiste sulla tua macchina. Se la directory non esiste, il metodo `Save` genera una `DirectoryNotFoundException`. + +**Output previsto** – un file PNG che appare simile all'illustrazione qui sotto (l'immagine reale non è mostrata, ma vedrai un classico Planet barcode con un payload numerico di `123456`). + +## Passo 4: Inizializzare un secondo generatore per il RM4SCC barcode + +Molti sistemi postali richiedono sia i simboli Planet sia RM4SCC sullo stesso pezzo di posta. Crea una nuova istanza di `BarcodeGenerator` per la simbologia RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Perché un'istanza separata?* +Ogni simbologia ha il proprio set di parametri. Riutilizzare lo stesso generatore potrebbe trasferire involontariamente impostazioni (come la X‑dimension) che non sono ottimali per il secondo codice a barre. + +## Passo 5: Configurare la X‑dimension per il RM4SCC barcode + +Anche RM4SCC rispetta l'impostazione della X‑dimension, quindi applichiamo la stessa larghezza in pixel per coerenza visiva. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Consiglio professionale* +Se ti serve un codice a barre più alto (ad esempio per etichette più grandi), puoi anche impostare `Height.Pixels`. Lasciandolo non impostato, la libreria calcola automaticamente l'altezza ideale. + +## Passo 6: Salvare il RM4SCC barcode come immagine PNG + +Infine, salva il RM4SCC barcode su disco. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Ora hai due file PNG—`PostalPlanetBarHeightNone.png` e `PostalRM4SCCBarHeightNone.png`—che puoi incorporare nelle etichette di spedizione, stampare su buste o inviare a un servizio di stampa di terze parti. + +## Opzionale: Regolare l'altezza o utilizzare altri formati immagine + +Se il tuo flusso di lavoro richiede un'altezza specifica del codice a barre o un formato immagine diverso (ad esempio JPEG o BMP), puoi modificare i parametri prima di chiamare `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Caso limite** – Quando imposti un'altezza personalizzata, assicurati che il valore rispetti l'altezza minima richiesta dallo standard ISO; altrimenti il codice a barre potrebbe non superare la validazione. + +## Problemi comuni e come evitarli + +| Problema | Perché succede | Soluzione | +|----------|----------------|-----------| +| `DirectoryNotFoundException` | La cartella di destinazione non esiste o è scritta in modo errato. | Crea prima la cartella o usa `Path.Combine` con `Environment.CurrentDirectory`. | +| Codice a barre illeggibile su stampanti a bassa risoluzione | X‑dimension troppo piccola per i DPI della stampante. | Aumenta `XDimension.Pixels` a 5 – 6 per stampanti a 203 dpi, oppure testa con un'etichetta di esempio. | +| Simbologia errata utilizzata | Passare `EncodeTypes.Code128` invece di `EncodeTypes.Planet`. | Verifica che il valore dell'enum `EncodeTypes` corrisponda allo standard postale richiesto. | +| Riferimento nullo su `Parameters` | Utilizzare una versione più vecchia di Aspose.BarCode in cui l'API è diversa. | Aggiorna all'ultima versione del pacchetto NuGet (v23.12 o successiva). | + +## Esempio completo eseguibile + +Di seguito trovi il programma completo che puoi copiare, incollare ed eseguire. Include le istruzioni `using`, la gestione degli errori e i commenti che spiegano ogni riga. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Eseguendo il programma viene creata una cartella `Barcodes` accanto all'eseguibile e vengono inseriti i due file PNG al suo interno. Aprili con qualsiasi visualizzatore di immagini per verificare il risultato. + +## Conclusione + +Ora disponi di una soluzione **barcode generator C#** che può **creare Planet barcode** immagini, regolare la X‑dimension per una stampa ottimale e produrre un codice a barre RM4SCC corrispondente—tutto con poche righe di codice. L'approccio funziona con .NET 6+, richiede solo il pacchetto NuGet Aspose.BarCode e può essere esteso ad altre simbologie come Code128, QR o DataMatrix cambiando il valore di `EncodeTypes`. + +### Cosa fare dopo? + +* Sperimenta con diversi valori di `XDimension.Pixels` per adeguarli ai DPI della tua stampante. +* Genera codici a barre in altri formati (PDF, SVG) modificando l'enum `BarCodeImageFormat`. +* Combina i due file PNG in un'unica etichetta usando una libreria grafica come **SkiaSharp**. +* Esplora l'intera API di Aspose.BarCode per funzionalità avanzate come la validazione del checksum o i font personalizzati. + +Sentiti libero di adattare il codice per l'elaborazione batch o integrarlo in un servizio web ASP.NET Core che restituisce immagini di codici a barre su richiesta. Buon coding! + +## 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 ulteriori funzionalità dell'API ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Crea Barcode PNG – Rapporto d'Aspetto DataMatrix – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Come salvare PNG usando DataMatrix C40 con Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Personalizza i rapporti d'aspetto del Code 16K Barcode con Aspose.BarCode per .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/italian/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..d20ab56d7 --- /dev/null +++ b/barcode/italian/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: Il tutorial del generatore di codici a barre C# mostra come generare + un'immagine di codice a barre con Aspose.BarCode, impostare colonne e righe e salvare + file PNG per DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: it +lastmod: 2026-08-03 +og_description: Il tutorial di Barcode generator C# spiega come generare un'immagine + di codice a barre usando Aspose.BarCode, configurare le colonne e le righe DataBar + Expanded Stacked e salvare file PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Generatore di codici a barre C# – guida passo passo per generare l'immagine + del codice a barre +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Generatore di codici a barre C# – genera immagine del codice a barre +url: /it/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generatore di codici a barre C# – generare immagine del codice a barre + +Se hai bisogno di un generatore di codici a barre C# che possa generare un'immagine di codice a barre per DataBar Expanded Stacked, questa guida ti accompagna passo passo nel processo completo. Imparerai come configurare le impostazioni di colonne e righe, salvare il risultato come PNG e adattare il codice ad altre simbologie. + +Generare programmaticamente immagini di codici a barre elimina le operazioni manuali e garantisce coerenza su fatture, etichette di spedizione e sistemi di inventario. Questo tutorial copre tutto ciò di cui hai bisogno, dalla configurazione del progetto al codice sorgente completo, così potrai eseguire l'esempio subito. + +## Prerequisiti + +Prima di iniziare, assicurati di avere: + +* .NET 6.0 o successivo installato +* Un IDE come Visual Studio 2022 (qualsiasi editor che supporta C# funziona) +* Una licenza per **Aspose.BarCode for .NET** – la valutazione gratuita è sufficiente per i test +* Familiarità di base con la sintassi C# + +Se uno di questi elementi manca, installa il .NET SDK da dotnet.microsoft.com e ottieni il pacchetto NuGet Aspose.BarCode con: + +```bash +dotnet add package Aspose.BarCode +``` + +## Step 1: Create a barcode generator C# project + +Crea una nuova applicazione console e aggiungi le direttive `using` richieste: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +La classe `BarcodeGenerator` è il nucleo dell'API del generatore di codici a barre C#. Riceve il tipo di simbologia e il testo da codificare. + +## Step 2: Generate a DataBar Expanded Stacked barcode and set columns + +Il primo esempio crea un codice a barre con quattro colonne. Modificando la proprietà `Columns` si cambia la densità visiva della simbologia DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Perché è importante:** Il numero di colonne influenza la quantità di dati che può essere memorizzata in uno spazio compatto. Impostandolo a 4 si ottiene un codice a barre più largo che rimane leggibile dalla maggior parte degli scanner. + +## Step 3: Generate a barcode with custom row count + +Il secondo esempio mostra come controllare il layout verticale impostando la proprietà `Rows`. Una configurazione a tre righe è utile quando è necessario un codice a barre più alto per spazio orizzontale limitato. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Perché è importante:** Regolare le righe ti permette di inserire il codice a barre in una colonna stretta mantenendo la leggibilità. Il generatore di codici a barre C# ricalcola automaticamente la dimensione del modulo per rispettare le specifiche. + +## Step 4: Full, runnable example + +Di seguito trovi un programma autonomo che combina i passaggi precedenti. Copia il codice in `Program.cs`, sostituisci `YOUR_DIRECTORY` con un percorso di cartella esistente e avvia l'applicazione. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Expected output + +Quando esegui il programma, due file PNG compaiono nella directory di destinazione: + +* **DatabarCols4.png** – un codice a barre DataBar Expanded Stacked con quattro colonne +* **DatabarRows3.png** – gli stessi dati codificati in tre righe + +Apri le immagini con qualsiasi visualizzatore; mostrano codici a barre nitidi e scansionabili pronti per la stampa o l'inserimento in PDF. + +## How to generate barcode image with custom dimensions + +Se ti serve una dimensione specifica dell'immagine, regola le proprietà `ImageHeight` e `ImageWidth` prima di chiamare `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Modificare le dimensioni non influisce sui dati codificati; scala solo la rappresentazione visiva. Questa tecnica è utile quando si integrano codici a barre in componenti UI con vincoli di layout fissi. + +## Common pitfalls and pro tips + +* **Separatori di percorso:** Usa stringhe verbatim (`@"C:\Path\file.png"`) o `Path.Combine` per evitare problemi di caratteri di escape su Windows. +* **Applicazione della licenza:** Senza una licenza valida, le immagini generate contengono una filigrana. Applica la tua licenza all'inizio dell'applicazione: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Limiti di codifica:** DataBar Expanded Stacked supporta fino a 74 caratteri numerici. Superare questo limite genera un'eccezione. Convalida la lunghezza dell'input prima di creare il generatore. +* **Prestazioni:** Riutilizzare una singola istanza di `BarcodeGenerator` per più salvataggi riduce l'allocazione di memoria. Cambia le proprietà `Rows` o `Columns` tra i salvataggi solo se il testo codificato rimane lo stesso. + +## Next steps + +Ora che puoi generare immagini di codici a barre con il generatore di codici a barre C#, considera di esplorare: + +* **Simbologie diverse** – prova `EncodeTypes.QR`, `EncodeTypes.Code128` o `EncodeTypes.Pdf417`. +* **Personalizzazione del colore** – imposta `Parameters.Barcode.ForeColor` e `BackColor` per corrispondere al brand. +* **Incorporamento in PDF** – combina il PNG generato con Aspose.PDF per creare documenti stampabili. + +Queste estensioni ti consentono di costruire una soluzione di codici a barre completa per applicazioni di inventario, logistica o retail. + +--- + + +## What Should You Learn Next? + +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 funzionalità aggiuntive dell'API ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [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 Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/italian/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..e899f3e87 --- /dev/null +++ b/barcode/italian/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-08-03 +description: Esempio di generatore di codici a barre in C# che mostra come impostare + la larghezza, come modificare l'altezza e come generare l'immagine del codice a + barre. Segui le istruzioni passo passo. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: it +lastmod: 2026-08-03 +og_description: L'esempio di generatore di codici a barre dimostra come impostare + la larghezza della dimensione X, modificare l'altezza delle barre e generare un'immagine + di codice a barre in C#. Segui i passaggi per creare file PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Esempio di generatore di codici a barre – Guida a larghezza e altezza in + C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Esempio di generatore di codici a barre in C# – impostare larghezza e altezza +url: /it/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Esempio di generatore di codici a barre in C# – impostare larghezza e altezza + +Se ti serve un **esempio di generatore di codici a barre** in C#, questa guida ti mostra come impostare la larghezza della X‑dimension, come modificare l’altezza delle barre e come generare un file immagine del codice a barre. Vedrai un programma completo, eseguibile, che produce due file PNG con altezze diverse. + +Uno scenario tipico è la creazione di etichette prodotto dove le dimensioni del codice a barre devono soddisfare le specifiche dello scanner. Alla fine di questo tutorial sarai in grado di regolare i parametri di larghezza e altezza programmaticamente e salvare il risultato come immagine PNG. + +## Prerequisiti + +Prima di iniziare, assicurati di avere: + +* .NET 6 (o successivo) installato – il codice è destinato al .NET 6 SDK. +* Una libreria di codici a barre che supporti `EncodeTypes.DatabarOmniDirectional`. L’esempio utilizza **Aspose.BarCode for .NET**, ma qualsiasi libreria che esponga proprietà simili funziona allo stesso modo. +* Un IDE o editor (Visual Studio, VS Code, Rider) per compilare ed eseguire il programma. +* Permessi di scrittura su una directory dove verranno salvati i file PNG. + +> **Suggerimento:** Crea una cartella chiamata `Barcodes` nella radice del tuo progetto e riferiscila con `Path.Combine` per evitare di codificare percorsi assoluti. + +## Esempio di generatore di codici a barre: inizializzare e configurare + +Il primo passo è creare un’istanza di `BarcodeGenerator` con la simbologia desiderata e la stringa dati. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +L’enum `EncodeTypes.DatabarOmniDirectional` seleziona la simbologia Databar Omni‑directional, e la stringa dati formattata GS1 `(01)12345678901231` rappresenta un tipico valore GTIN‑14. Inizializzare il generatore una sola volta ti permette di riutilizzare lo stesso oggetto per più immagini. + +## Come impostare la larghezza (X‑dimension) + +La X‑dimension controlla la larghezza del modulo del codice a barre. Impostarla a 2 pixel rende ogni barra stretta larga 2 pixel, requisito comune per la stampa ad alta densità. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Perché è importante: se la larghezza è troppo piccola, gli scanner potrebbero non distinguere le singole barre; se è troppo grande, il codice a barre potrebbe superare lo spazio disponibile sull’etichetta. Regola il valore in pixel per corrispondere al DPI della stampante e alle dimensioni dell’etichetta target. + +## Come cambiare l’altezza + +L’altezza della barra determina quanto sono alte le barre. L’esempio crea due immagini: una con altezza di 30 pixel e un’altra con altezza di 60 pixel. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +La proprietà `BarHeight.Pixels` influisce direttamente sull’altezza visiva delle barre. Cambiarla tra le operazioni di salvataggio ti consente di generare più varianti dallo stesso payload di dati senza ricreare il generatore. + +### Output previsto + +L’esecuzione del programma produce due file PNG nella cartella `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – le barre sono alte 30 pixel. +* `DatabarBarHeight60Pixels.png` – le barre sono alte 60 pixel. + +Entrambe le immagini condividono la stessa larghezza (determinata dalla X‑dimension) e codificano gli stessi dati GTIN‑14. + +![Two barcode PNG files with different heights generated by C# code](barcode-example.png "Barcode generator example showing height variations") + +*Il testo alternativo dell’immagine sopra contiene la parola chiave principale per l’accessibilità e la SEO.* + +## Come generare l’immagine del codice a barre in C# + +Il metodo `Save` gestisce la conversione dai dati del codice a barre a un file immagine. Puoi scegliere altri formati (JPEG, BMP, SVG) passando un valore diverso dell’enum `BarCodeImageFormat`. L’esempio utilizza PNG perché preserva la qualità lossless ed è ampiamente supportato. + +Se devi incorporare il codice a barre direttamente in un PDF o in una pagina web, recupera l’immagine come `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Questo approccio elimina la necessità di file temporanei ed è utile per servizi ad alto volume. + +## Variazioni comuni e casi limite + +| Situazione | Regolazione | +|------------|-------------| +| **Simbologia diversa** | Sostituisci `EncodeTypes.DatabarOmniDirectional` con un altro valore enum (ad es., `EncodeTypes.Code128`). | +| **Etichette molto piccole** | Riduci `XDimension.Pixels` a 1 pixel, ma verifica la leggibilità da parte dello scanner. | +| **Stampa ad alta risoluzione** | Aumenta sia la X‑dimension che l’altezza della barra proporzionalmente (ad es., 4 px di larghezza, 80 px di altezza). | +| **Dati dinamici** | Passa la stringa dati a runtime, magari da un record di database. | +| **Generazione batch** | Itera su una collezione di stringhe dati, riutilizzando la stessa istanza di `BarcodeGenerator` aggiornando `generator.Text`. | + +Quando incontri un’eccezione come `ArgumentOutOfRangeException`, ricontrolla che i valori in pixel siano interi positivi e che la directory di output esista. + +## Riepilogo del codice sorgente completo + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Copia il codice in un nuovo progetto console, ripristina il pacchetto NuGet Aspose.BarCode (`dotnet add package Aspose.BarCode`) ed esegui `dotnet run`. Vedrai messaggi nella console che confermano i file salvati. + +## Conclusione + +Questo **esempio di generatore di codici a barre** dimostra come impostare la larghezza, come cambiare l’altezza e come generare un’immagine di codice a barre in C#. Regolando `XDimension.Pixels` e `BarHeight.Pixels` controlli le dimensioni visive del codice a barre, e il metodo `Save` scrive il risultato in file PNG. Sperimenta con simbologie diverse, formati di output e stringhe dati per adattarle ai requisiti della tua applicazione. + +**Passi successivi** + +* Esplora **come generare codici a barre** in altri formati immagine (SVG, JPEG) per l’uso web. +* Impara **creare immagine di codice a barre c#** per endpoint ASP.NET Core che restituiscono direttamente il PNG al browser. +* Combina questo codice con una libreria di generazione PDF per incorporare i codici a barre in fatture o etichette di spedizione. + +Sentiti libero di adattare il campione, condividere i tuoi risultati o porre domande nei commenti. Buona programmazione! + +## 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. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to Set Border for ITF-14 Barcode Customization](/barcode/english/net/itf-14-barcode-customization/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/italian/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..223d3948b --- /dev/null +++ b/barcode/italian/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-08-03 +description: Crea un PNG di codice a barre in C# e impara come modificare il rapporto + d'aspetto per le immagini DataBar. Segui questo esempio completo con codice e consigli. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: it +lastmod: 2026-08-03 +og_description: Crea un PNG di codice a barre in C# e scopri come modificare il rapporto + d'aspetto per i codici a barre DataBar. Questa guida ti fornisce codice pronto all'uso + e consigli pratici. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Crea PNG di codice a barre in C# – esempio completo con controllo del rapporto + d'aspetto +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Crea PNG di codice a barre in C# – guida passo passo +url: /it/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Creare barcode PNG in C# – guida passo‑passo + +Se hai bisogno di **creare barcode PNG** in C#, questo tutorial ti mostra esattamente come fare. Genererai un barcode DataBar omnidirezionale impilato, lo salverai come file PNG e imparerai **come modificare il rapporto d'aspetto** per adattarlo a diversi ambienti di scansione. + +La guida copre tutto ciò di cui hai bisogno: pacchetti richiesti, un programma completo e eseguibile, e spiegazioni sul perché ogni impostazione è importante. Alla fine avrai due file PNG—uno con un rapporto d'aspetto di 15 e un altro con 30—pronti per test o utilizzo in produzione. + +## Prerequisiti + +Prima di iniziare, assicurati di avere: + +- .NET 6.0 SDK o versioni successive installate +- Visual Studio 2022 (o qualsiasi IDE per C#) +- Un riferimento NuGet a **Aspose.BarCode** (la libreria che fornisce `BarcodeGenerator`) +- Permessi di scrittura nella directory in cui verranno salvati i file PNG + +Puoi aggiungere il pacchetto Aspose.BarCode con il seguente comando: + +```bash +dotnet add package Aspose.BarCode +``` + +## Passo 1: Configurare il progetto e importare i namespace + +Crea una nuova applicazione console e importa i namespace necessari per la generazione del barcode e per l'I/O dei file. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Perché è importante:** Importare `Aspose.BarCode.Generation` ti dà accesso a `BarcodeGenerator`. Tenere il codice all'interno di `Main` rende l'esempio autonomo e facile da eseguire. + +## Passo 2: Creare un generatore di barcode per un DataBar omnidirezionale impilato + +Istanzia `BarcodeGenerator` con il tipo `EncodeTypes.DatabarStackedOmniDirectional` e una stringa di dati di esempio GS1‑128. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Perché è importante:** Il tipo di codifica scelto produce un DataBar ad alta densità che può essere letto dalla maggior parte degli scanner moderni. La stringa di dati segue il formato dell'Identificatore di Applicazione GS1 (01), comune per gli identificatori di prodotto. + +## Passo 3: Definire la X‑dimension (larghezza del modulo) in pixel + +Imposta la larghezza del modulo per controllare le dimensioni complessive del barcode senza influire sulla leggibilità. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Perché è importante:** Una X‑dimension di 2 pixel produce un barcode né troppo piccolo per gli scanner né troppo grande per gli spazi tipici delle etichette. + +## Passo 4: Salvare il primo PNG con un rapporto d'aspetto di 15 + +Regola il rapporto d'aspetto del DataBar, quindi salva l'immagine come file PNG. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Perché è importante:** Il rapporto d'aspetto controlla la relazione altezza‑larghezza del DataBar impilato. Un rapporto di 15 è un valore predefinito comune che bilancia leggibilità e altezza dell'etichetta. + +## Passo 5: Cambiare il rapporto d'aspetto a 30 e salvare un secondo PNG + +Modifica la stessa istanza del generatore per utilizzare un rapporto d'aspetto più grande, quindi salva la seconda immagine. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Perché è importante:** Aumentare il rapporto d'aspetto allunga il barcode verticalmente, il che può migliorare l'affidabilità della scansione su dispositivi a bassa risoluzione o quando l'etichetta è stampata su supporti stretti. + +## Output previsto + +L'esecuzione del programma crea due file PNG: + +| File | Rapporto d'aspetto | Dimensioni approssimative (pixel) | +|------------------------------------|--------------------|-----------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (larghezza × altezza) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (larghezza × altezza) | + +Entrambe le immagini contengono un barcode DataBar chiaro e leggibile che codifica l'identificatore GS1 `(01)12345678901231`. + +## Domande comuni e casi limite + +### Come cambiare altre proprietà visive? + +Puoi regolare il colore di primo piano, il colore di sfondo o aggiungere testo leggibile dall'uomo tramite l'oggetto `generator.Parameters.Barcode`. Per esempio: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### E se avessi bisogno di un formato immagine diverso? + +Sostituisci `BarCodeImageFormat.Png` con `Jpeg`, `Bmp` o `Gif` secondo necessità. PNG rimane la scelta migliore per immagini barcode senza perdita. + +### Il rapporto d'aspetto influisce sulla velocità di scansione? + +Rapporti d'aspetto più alti aumentano l'altezza del barcode, il che può migliorare l'affidabilità della scansione su dispositivi che hanno difficoltà con simboli impilati corti. Tuttavia, barcode estremamente alti potrebbero non stare su etichette piccole, quindi è consigliabile testare con l'hardware di destinazione. + +### Posso generare più barcode in un ciclo? + +Sì. Crea una nuova istanza di `BarcodeGenerator` per ogni stringa di dati o riutilizza la stessa istanza aggiornando `CodeText` e `DataBar.AspectRatio`. Questo approccio riduce il sovraccarico di allocazione degli oggetti. + +## Suggerimenti professionali + +- **Riutilizza il generatore**: Modificare solo `CodeText` o `AspectRatio` evita di reinizializzare l'oggetto, velocizzando l'elaborazione in batch. +- **Convalida l'output**: Usa uno scanner portatile o un'app mobile per confermare che il PNG generato venga letto correttamente prima di distribuirlo in produzione. +- **Denominazione dei file**: Includi il rapporto d'aspetto nel nome del file (come mostrato) per tenere traccia delle variazioni durante i test. + +## Conclusione + +Ora sai come **creare barcode PNG** in C# e precisamente **come modificare il rapporto d'aspetto** per i simboli DataBar omnidirezionali impilati. L'esempio completo dimostra l'inizializzazione, l'impostazione della X‑dimension, la manipolazione del rapporto d'aspetto e il salvataggio dell'immagine—tutto in un unico programma eseguibile. + +Da qui puoi esplorare altri tipi di barcode, sperimentare con i colori o integrare il generatore in un sistema più ampio di reporting o gestione inventario. 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à aggiuntive dell'API ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/italian/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..c970638e8 --- /dev/null +++ b/barcode/italian/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-08-03 +description: Crea rapidamente un PNG di codice a barre con questa guida. Scopri come + generare un'immagine di codice a barre usando Aspose.BarCode e genera il codice + a barre Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: it +lastmod: 2026-08-03 +og_description: Crea un PNG di codice a barre istantaneamente. Questo tutorial mostra + come generare un'immagine di codice a barre e generare un codice a barre planet + con Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Crea barcode PNG in Python – guida completa di programmazione +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Crea barcode PNG in Python – guida passo‑passo +url: /it/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea barcode PNG in Python – guida passo‑passo + +Se hai bisogno di **creare file barcode PNG** dalla tua applicazione Python, questo tutorial ti mostra esattamente come fare. Ti guideremo attraverso **come generare un’immagine barcode** usando Aspose.BarCode e, nello specifico, **generare un barcode Planet** con dimensioni personalizzate. + +Imparerai come installare la libreria, configurare la simbologia Planet, regolare i parametri di dimensione e salvare il risultato come PNG di alta qualità. La guida presuppone conoscenze di base di Python e una versione recente di Python 3 (3.8 o successiva). Non è necessaria alcuna esperienza pregressa con gli standard dei barcode. + +--- + +## Come creare barcode PNG con Aspose.BarCode + +Questa sezione contiene i passaggi fondamentali necessari per **creare barcode PNG**. Ogni passo include uno snippet di codice, una spiegazione del perché è importante e consigli pratici che puoi applicare subito. + +### 1. Installa il pacchetto Aspose.BarCode + +Aspose fornisce un pacchetto pure‑Python che avvolge il suo motore .NET core. Installalo con `pip`: + +```bash +pip install aspose-barcode +``` + +*Perché questo passo è importante:* Il pacchetto fornisce la classe `BarcodeGenerator` usata in tutto l’esempio. Installarlo globalmente garantisce che l’interprete possa trovare l’assembly a runtime. + +### 2. Importa le classi necessarie + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Consiglio:* Importa solo i simboli di cui hai bisogno; questo mantiene pulito lo spazio dei nomi e velocizza il caricamento del modulo. + +### 3. Crea un generatore di barcode per la simbologia Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Perché è importante:* `EncodeTypes.Planet` indica al motore di utilizzare lo standard barcode Planet, mentre il secondo argomento fornisce i dati da codificare. Cambiare la simbologia (ad es., `EncodeTypes.Code128`) produrrebbe un pattern visivo completamente diverso. + +### 4. Imposta la dimensione X (larghezza del modulo) in pixel + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Spiegazione:* La dimensione X controlla la larghezza della barra stretta. Un valore di 4 pixel genera un barcode moderatamente denso che rimane leggibile sulla maggior parte dei dispositivi. + +### 5. Definisci un’altezza della barra manuale in pixel + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Perché potresti regolarla:* Alcune stampanti retail richiedono barre più alte per una scansione affidabile. L’altezza predefinita è solitamente 50 px; aumentarla a 100 px migliora la leggibilità senza ingrandire drasticamente la dimensione del file. + +### 6. Salva il barcode generato come immagine PNG + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Risultato:* Un file PNG chiamato **PlanetBarHeight100.png** appare nella cartella `output`. PNG è loss‑less, il che lo rende ideale per la stampa e per l’inserimento in pagine web. + +### 7. Verifica l’output (opzionale) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Consiglio:* Visualizzare l’immagine conferma che le dimensioni corrispondono ai parametri impostati. Se il barcode appare distorto, rivedi le impostazioni della dimensione X o dell’altezza della barra. + +--- + +## Come generare un’immagine barcode in formato PNG (impostazioni alternative) + +Se ti serve un formato immagine diverso o vuoi incorporare il barcode in un PDF successivamente, puoi cambiare l’enumerazione `BarCodeImageFormat`: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Perché è importante:* PNG conserva ogni pixel, cosa cruciale per barcode ad alto contrasto. JPEG introduce artefatti di compressione che possono interferire con la scansione, mentre BMP offre compatibilità con strumenti più vecchi. + +--- + +## Genera barcode Planet con colori personalizzati (avanzato) + +Oltre alle dimensioni, puoi personalizzare i colori di primo piano e di sfondo: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Consiglio pratico:* Coppie di colori ad alto contrasto (scuro su chiaro) massimizzano l’affidabilità dello scanner. Evita di usare tonalità simili per primo piano e sfondo. + +--- + +## Problemi comuni e come evitarli + +| Sintomo | Causa | Soluzione | +|---------|-------|-----------| +| Il barcode non viene letto | Dimensione X troppo piccola (≤ 2 px) | Aumenta `x_dimension.pixels` ad almeno 3 px | +| L’immagine appare sfocata | PNG salvato a bassa DPI | Usa `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` per specificare 300 DPI (se supportato) | +| Eccezione `ImportError` | Aspose.BarCode non installato | Esegui `pip install aspose-barcode` nello stesso ambiente dello script | +| Simbologia errata | Usato `EncodeTypes.Code128` invece di `EncodeTypes.Planet` | Sostituisci con `EncodeTypes.Planet` quando crei il generatore | + +--- + +## Riepilogo della soluzione completa + +Di seguito lo script completo, eseguibile, che **crea barcode PNG** dall’inizio alla fine: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Eseguendo questo script otterrai un **barcode Planet PNG** nitido che potrai inserire in HTML, allegare a email o stampare su etichette di prodotto. + +--- + +## Prossimi passi e argomenti correlati + +* **Integra con Flask o Django** – servi il PNG generato direttamente da un endpoint web. +* **Generazione batch** – itera su una lista di ID prodotto per creare una cartella di file barcode PNG. +* **Combina con la generazione PDF** – usa `aspose-pdf` per inserire il PNG in una fattura o in un’etichetta di spedizione. +* **Esplora altre simbologie** – sostituisci `EncodeTypes.Planet` con `EncodeTypes.QR`, `EncodeTypes.DataMatrix` o `EncodeTypes.Code128` per soddisfare diverse esigenze aziendali. + +Padroneggiando i passaggi sopra, ora sai **come generare un’immagine barcode** programmaticamente e puoi estendere il modello a qualsiasi standard barcode supportato da Aspose.BarCode. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/italian/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..35107bb7a --- /dev/null +++ b/barcode/italian/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-08-03 +description: Crea rapidamente un'immagine di codice a barre postale in C#. Scopri + come generare un codice a barre postale, impostare le dimensioni del codice a barre + e generare un codice a barre Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: it +lastmod: 2026-08-03 +og_description: Crea un'immagine di codice a barre postale in C# con questo tutorial + completo; impara a impostare le dimensioni del codice a barre, generare un codice + a barre Planet e produrre codici a barre RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Crea immagine di codice a barre postale in C# – guida completa di programmazione +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Crea immagine di codice a barre postale in C# – guida passo passo +url: /it/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea un'immagine di codice a barre postale in C# – guida passo‑paso + +Se hai bisogno di **creare un'immagine di codice a barre postale** in C#, questa guida ti mostra esattamente come fare. Copriremo **come generare un codice a barre postale**, **come impostare le dimensioni del codice a barre** e come **generare il codice a barre Planet** per gli standard postali più comuni. + +Terminerai con due file PNG pronti all'uso — un codice a barre Planet e un codice a barre RM4SCC — entrambi alti 100 px. Non sono necessari strumenti aggiuntivi oltre alla libreria Aspose.BarCode per .NET. + +## Prerequisiti + +* .NET 6 SDK o versioni successive (il codice funziona anche con .NET Framework 4.7+) +* Visual Studio 2022 o qualsiasi IDE C# +* Pacchetto NuGet **Aspose.BarCode** (la libreria che fornisce `BarcodeGenerator`) + +## Passo 1: Installa la libreria per i codici a barre + +Apri un terminale nella cartella del tuo progetto ed esegui: + +```bash +dotnet add package Aspose.BarCode +``` + +Il pacchetto aggiunge lo spazio dei nomi `Aspose.BarCode`, che contiene `BarcodeGenerator` e l'enumerazione `EncodeTypes` necessaria per i codici a barre postali. + +## Passo 2: Definisci la cartella di output + +Creare un percorso di output affidabile evita errori di runtime quando la cartella non esiste. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Perché è importante*: `Directory.CreateDirectory` è idempotente — crea la cartella solo se non è già presente, evitando eccezioni nelle esecuzioni successive. + +## Passo 3: Configura le dimensioni comuni del codice a barre + +Impostare la X‑dimension (larghezza di una singola barra) e l'altezza complessiva della barra ti consente di controllare la dimensione visiva dell'immagine generata. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Come impostare le dimensioni del codice a barre**: la proprietà `Parameters.Barcode.XDimension.Pixels` definisce la larghezza della barra stretta, mentre `Parameters.Barcode.BarHeight.Pixels` definisce l'altezza totale. Regola questi valori per soddisfare le specifiche del tuo servizio postale. + +## Passo 4: Genera un codice a barre Planet + +Planet è un codice a barre postale ampiamente usato nel Regno Unito. Il codice seguente crea un codice a barre Planet alto 100 px e lo salva come PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Perché funziona**: `EncodeTypes.Planet` indica al generatore di utilizzare la simbologia Planet. Il metodo `Save` scrive un file PNG nel percorso specificato, preservando le dimensioni impostate in precedenza. + +## Passo 5: Genera un codice a barre RM4SCC + +RM4SCC è lo standard di codice a barre postale olandese. Il codice qui sotto rispecchia l'esempio Planet, dimostrando **come generare un codice a barre postale** di tipo diverso con le stesse dimensioni. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Entrambi i file PNG ora risiedono nella cartella `Barcodes`. Aprirli mostrerà codici a barre puliti, alti 100 px, pronti per la stampa o per l'inserimento in documenti. + +## Codice sorgente completo + +Di seguito trovi il programma completo, eseguibile, che **crea file immagine di codice a barre postale** per gli standard Planet e RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Output previsto + +L'esecuzione del programma stampa i percorsi dei file e crea due file PNG: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Ogni immagine è alta 100 px, con una larghezza di barra stretta di 4 pixel, corrispondente alle dimensioni impostate. + +## Consigli pratici e problemi comuni + +* **Permessi della cartella** – Se il programma viene eseguito con un account con restrizioni, assicurati che la cartella di destinazione sia scrivibile. +* **Dimensioni diverse** – Per creare un codice a barre più alto, aumenta `barHeightPixels`. Per una risoluzione più fine, diminuisci `xDimensionPixels`, ma mantienila ≥ 2 per evitare artefatti di rendering. +* **Altre simbologie postali** – Aspose.BarCode supporta anche `EncodeTypes.Postnet` e `EncodeTypes.AustralianPost`. Sostituisci il valore di `EncodeTypes` mantenendo la stessa logica delle dimensioni. +* **Formato immagine** – Usa `BarCodeImageFormat.Jpeg` per ridurre le dimensioni del file quando la qualità senza perdita non è necessaria. + +## Conclusione + +Ora sai come **creare file immagine di codice a barre postale** in C# configurando le dimensioni, selezionando la simbologia corretta e salvando il risultato come PNG. Il tutorial ha coperto **come generare un codice a barre postale**, ha mostrato **come generare un codice a barre Planet** e ha spiegato **come impostare le dimensioni del codice a barre** per ottenere un output coerente. + +Successivamente, esplora **la personalizzazione dei colori del codice a barre**, l'aggiunta di **testo leggibile dall'uomo**, o l'integrazione delle immagini in fatture PDF. Lo stesso schema si applica a qualsiasi altro tipo di codice a barre supportato da Aspose.BarCode, permettendoti di estendere questa soluzione a un flusso di lavoro completo di automazione postale. + + +## 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 funzionalità aggiuntive dell'API e a esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to generate barcode java – Australia Post Barcode with Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/italian/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..f34a109b9 --- /dev/null +++ b/barcode/italian/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-08-03 +description: Come salvare un codice a barre in C# con un esempio passo‑passo di generatore + di codici a barre. Impara a generare codici a barre Planet, impostare le dimensioni + e esportare immagini PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: it +lastmod: 2026-08-03 +og_description: Come salvare il codice a barre in C# usando un esempio di generatore + di codici a barre. Questo tutorial mostra come generare codici a barre Planet, configurare + la dimensione X e esportare file PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Come salvare il codice a barre in C# – guida passo passo +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Come salvare il codice a barre in C# – guida completa al generatore di codici + a barre +url: /it/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come salvare un codice a barre in C# – guida completa al generatore di codici a barre + +Come salvare le immagini dei codici a barre in C# è una necessità comune quando è necessario incorporare codici a barre postali in fatture, etichette di spedizione o tag di inventario. Questa guida ti accompagna attraverso un flusso di lavoro pratico di **c# barcode generator**, dalla creazione di un codice a barre Planet all'esportazione di file PNG con barre piene e barre vuote. + +Imparerai a impostare la larghezza delle barre, a alternare le barre piene e a gestire le cartelle di output in modo affidabile. Alla fine del tutorial avrai un **barcode generator example** completamente funzionante che potrai copiare in qualsiasi progetto .NET. + +## Cosa ti serve + +Prima di scrivere codice, assicurati di avere: + +- .NET 6.0 SDK o successivo (l'esempio funziona con .NET Core e .NET Framework) +- Visual Studio 2022 o qualsiasi IDE compatibile con C# +- Il pacchetto NuGet **Aspose.BarCode** (o un'altra libreria che supporta `EncodeTypes.Planet`). Installalo con: + +```bash +dotnet add package Aspose.BarCode +``` + +La libreria fornisce la classe `BarcodeGenerator` utilizzata in tutto questo tutorial. + +## Configurazione dell'ambiente di sviluppo + +Crea un nuovo progetto console e aggiungi lo spazio dei nomi richiesto: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +Lo spazio dei nomi `System.IO` ci fornisce `Directory.CreateDirectory`, che garantisce che la cartella di output esista prima di tentare di scrivere i file. + +## Come salvare le immagini dei codici a barre con il generatore di codici a barre C# + +Il cuore della soluzione è un piccolo insieme di passaggi che configurano un **Planet barcode** e poi salvano l'immagine su disco. Le sezioni seguenti suddividono il processo in parti gestibili. + +### Passo 1: Definire la cartella di output + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Perché?** +Hard‑coding di un percorso può causare `DirectoryNotFoundException` su macchine dove la cartella non esiste. `CreateDirectory` è idempotente—crea la directory solo se manca, rendendo il codice sicuro per esecuzioni ripetute. + +### Passo 2: Creare un generatore di codice a barre Planet (barre piene) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Perché?** +`EncodeTypes.Planet` indica alla libreria di produrre un codice a barre postale Planet, ampiamente usato dai servizi di posta. La stringa `"123456"` è il payload di esempio; sostituiscila con qualsiasi dato numerico richiesto dalla tua logica di business. + +### Passo 3: Configurare la larghezza della barra (dimensione X) e mantenere le barre piene predefinite + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Perché?** +La dimensione X controlla la larghezza fisica di ogni barra. Un valore di `4` pixel produce un codice a barre leggibile su stampanti standard a 300 dpi. Lasciare `FilledBars` a `true` (impostazione predefinita) genera l'aspetto classico a barra solida. + +### Passo 4: Salvare l'immagine del codice a barre con barre piene + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Perché?** +Salvare come PNG preserva la qualità dell'immagine senza perdita, importante per l'accuratezza della scansione. Il metodo `Save` crea automaticamente il file immagine; devi solo fornire il percorso completo e il formato desiderato. + +### Passo 5: Creare un secondo generatore per la versione a barre vuote + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Creare una nuova istanza garantisce che le modifiche apportate per la versione a barre vuote non influenzino l'immagine già salvata con barre piene. + +### Passo 6: Disabilitare le barre piene mantenendo la stessa dimensione X + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Perché?** +Impostare `FilledBars = false` rende il codice a barre con solo il contorno di ogni barra, requisito di alcuni standard postali per la verifica visiva. + +### Passo 7: Salvare l'immagine del codice a barre con barre vuote + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Ora hai due file PNG—uno con barre piene e uno con barre vuote—pronti per l'inclusione in PDF, email HTML o etichette stampate. + +## Programma completo eseguibile + +Di seguito il codice completo che puoi copiare in `Program.cs`. Compila ed esegue senza modifiche (presupponendo che il pacchetto Aspose.BarCode sia installato). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Output previsto + +L'esecuzione del programma stampa due righe simili a: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Apri la cartella `Barcodes` e vedrai i due file PNG. Entrambe le immagini possono essere aperte con qualsiasi visualizzatore di immagini o incorporate direttamente nei documenti. + +![how to save barcode example](barcode-example.png){: .align-center alt="esempio di come salvare il codice a barre"} + +## Variazioni comuni e casi limite + +| Scenario | Adeguamento | +|----------|------------| +| **Formato immagine diverso** | Cambia `BarCodeImageFormat.Png` in `Jpeg`, `Gif` o `Bmp` secondo necessità. | +| **Dimensione di output personalizzata** | Usa `filled.Parameters.Image.Width` e `Height` per forzare una dimensione pixel specifica. | +| **Dati dinamici** | Sostituisci il valore statico `"123456"` con una variabile che contiene numeri d'ordine, ID di tracciamento, ecc. | +| **Cartella inesistente** | `Directory.CreateDirectory` gestisce già le directory mancanti; non è necessario altro codice. | +| **Stampa ad alta risoluzione** | Aumenta `XDimension.Pixels` a 6–8 per stampanti a 600 dpi, ma verifica la compatibilità con lo scanner. | + +**Consiglio esperto:** Se devi generare molti codici a barre in un ciclo, riutilizza una singola istanza di `BarcodeGenerator` e modifica solo la proprietà `CodeText` prima di ogni `Save`. Questo riduce il sovraccarico di allocazione degli oggetti. + +## Come generare codici a barre per altri standard + +Lo stesso schema funziona per altri `EncodeTypes` come `Code128`, `QR` o `DataMatrix`. Basta sostituire `EncodeTypes.Planet` con il tipo desiderato e regolare eventuali parametri specifici del tipo (ad es., `QRCodeVersion`). + +## 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 salvare PNG usando DataMatrix C40 con Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Come generare codici a barre DataMatrix (ECC 200) con Aspose.BarCode per .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Come generare codici a barre – Configurazione Code 39 con Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/japanese/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..46935156b --- /dev/null +++ b/barcode/japanese/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-08-03 +description: Aspose.BarCode を使用して Planet バーコードを作成し、X 次元を設定して PNG 画像として保存する方法を示す C# + バーコードジェネレータチュートリアル。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: ja +lastmod: 2026-08-03 +og_description: BarcodeジェネレーターC#チュートリアルでは、Planetバーコードの作成、X次元の調整、そしてAspose.BarCodeを使用したPNG形式での保存方法を順を追って解説します。 +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: C# バーコードジェネレーター – Planet バーコードをステップバイステップで作成 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: バーコードジェネレーター C# – Planet バーコードと RM4SCC の作成例 +url: /ja/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – create Planet barcode and RM4SCC example + +郵便向けシンボルを生成できる **barcode generator C#** が必要な方へ。本ガイドでは Aspose.BarCode を使用して **Planet barcode** 画像を作成する手順を示します。X‑dimension の設定方法、対応する RM4SCC バーコードの生成、両方を PNG ファイルとして保存する方法を数ステップで解説します。 + +このチュートリアルは .NET 6 以降でコードを実行するために必要なすべてを網羅し、各設定が重要な理由や、モジュール幅の誤設定・ディレクトリ権限不足といった一般的な落とし穴についても説明します。最後には Planet と RM4SCC の規格に準拠した、印刷可能なバーコード画像が 2 枚得られます。 + +## Prerequisites + +開始する前に、以下を用意してください。 + +* .NET 6 SDK(または Aspose.BarCode がサポートする任意の .NET バージョン) +* Visual Studio 2022 もしくはお好みの C# IDE +* **Aspose.BarCode** への NuGet 参照(`Install-Package Aspose.BarCode`) +* PNG ファイルを保存するフォルダーへの書き込み権限 + +追加の外部サービスは不要です。ライブラリがローカルでエンコードをすべて処理します。 + +## Step 1: Initialise the barcode generator C# object + +最初の作業は `BarcodeGenerator` のインスタンスを作成することです。コンストラクタにはバーコードシンボル(`EncodeTypes.Planet`)とエンコードするデータを渡します。 + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Why this step?* +`BarcodeGenerator` は生成するすべてのバーコードのエントリーポイントです。`EncodeTypes.Planet` を選択することで、郵便サービスで広く使用されている ISO/IEC 24723 仕様に従ったバーコードが生成されます。 + +## Step 2: Set the X‑dimension (module width) for the Planet barcode + +X‑dimension は単一モジュール(最小のバーまたはスペース)の幅を定義します。**4 ピクセル** の値は多くのラベルプリンターでうまく機能します。 + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Why this matters* +モジュールが狭すぎるとバーコードが読めなくなり、広すぎるとラベルサイズが不必要に大きくなります。`Pixels` を調整することで、使用するプリンターの解像度に合わせてバーコードを微調整できます。 + +## Step 3: Save the Planet barcode as a PNG image + +Aspose.BarCode は選択したシンボルに基づきバーコードの高さを自動計算するため、ファイルパスとフォーマットだけを指定すれば完了です。 + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tip* +`YOUR_DIRECTORY` を実際に存在する絶対パスまたは相対パスに置き換えてください。ディレクトリが存在しない場合、`Save` メソッドは `DirectoryNotFoundException` をスローします。 + +**Expected output** – 以下のイラストに似た PNG ファイルが生成されます(実際の画像はここでは表示されませんが、数値ペイロード `123456` を持つ典型的な Planet バーコードが出力されます)。 + +## Step 4: Initialise a second generator for the RM4SCC barcode + +多くの郵便システムでは同一郵便物に Planet と RM4SCC の両シンボルが必要です。RM4SCC 用に新しい `BarcodeGenerator` インスタンスを作成します。 + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Why a separate instance?* +シンボルごとに固有のパラメータが存在します。同一インスタンスを再利用すると、X‑dimension などの設定が意図せず引き継がれ、2 番目のバーコードに最適でなくなる可能性があります。 + +## Step 5: Configure the X‑dimension for the RM4SCC barcode + +RM4SCC でも X‑dimension 設定が有効です。視覚的な一貫性を保つため、同じピクセル幅を適用します。 + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +より高いバーコードが必要な場合(例:大きなラベル用)には `Height.Pixels` も設定できます。未設定のままにすると、ライブラリが自動で最適な高さを計算します。 + +## Step 6: Save the RM4SCC barcode as a PNG image + +最後に RM4SCC バーコードをディスクに保存します。 + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +これで 2 つの PNG ファイル、`PostalPlanetBarHeightNone.png` と `PostalRM4SCCBarHeightNone.png` が作成されました。これらは郵便ラベルに埋め込んだり、封筒に印刷したり、サードパーティの印刷サービスに送信したりできます。 + +## Optional: Adjusting height or using other image formats + +ワークフローで特定のバーコード高さや別の画像形式(例:JPEG や BMP)が必要な場合は、`Save` 呼び出し前にパラメータを変更します。 + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Edge case** – カスタム高さを設定する際は、ISO 標準が要求する最小高さを満たすように注意してください。満たさないとバーコードの検証に失敗する可能性があります。 + +## Common pitfalls and how to avoid them + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| `DirectoryNotFoundException` | 対象フォルダーが存在しない、または名前が間違っている。 | 事前にフォルダーを作成するか、`Path.Combine` と `Environment.CurrentDirectory` を使用してください。 | +| Barcode unreadable on low‑resolution printers | プリンターの DPI に対して X‑dimension が小さすぎる。 | 203 dpi プリンターの場合は `XDimension.Pixels` を 5 – 6 に増やす、またはサンプルラベルでテストしてください。 | +| Wrong symbology used | `EncodeTypes.Code128` を指定してしまい、`EncodeTypes.Planet` ではない。 | 必要な郵便規格に合致する `EncodeTypes` 列挙値を再確認してください。 | +| Null reference on `Parameters` | Aspose.BarCode の旧バージョンを使用しており API が異なる。 | 最新の NuGet パッケージ(v23.12 以降)にアップグレードしてください。 | + +## Full runnable example + +以下はそのままコピーして実行できる完全なプログラムです。`using` 文、エラーハンドリング、各行の説明コメントが含まれています。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +プログラムを実行すると、実行ファイルと同じディレクトリに `Barcodes` フォルダーが作成され、2 つの PNG ファイルが格納されます。任意の画像ビューアで開き、出力を確認してください。 + +## Conclusion + +これで **barcode generator C#** ソリューションが完成し、**Planet barcode** 画像の作成、最適な印刷のための X‑dimension 調整、そして対応する RM4SCC バーコードの生成が数行のコードで実現できました。この手法は .NET 6+ で動作し、必要なのは Aspose.BarCode の NuGet パッケージだけです。`EncodeTypes` の値を変更すれば、Code128、QR、DataMatrix など他のシンボルにも簡単に拡張できます。 + +### What’s next? + +* プリンターの DPI に合わせて `XDimension.Pixels` の値を試行錯誤してください。 +* `BarCodeImageFormat` 列挙体を変更して、PDF や SVG など別形式でバーコードを生成してください。 +* **SkiaSharp** などのグラフィックライブラリを使い、2 つの PNG を 1 枚のラベルに結合してください。 +* チェックサム検証やカスタムフォントといった高度な機能は、Aspose.BarCode API 全体を探索してみましょう。 + +コードをバッチ処理向けに改造したり、オンデマンドでバーコード画像を返す ASP.NET Core Web サービスに組み込んだりしても構いません。Happy coding! + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、API の追加機能習得や代替実装アプローチの探求に役立ちます。 + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/japanese/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..b43c6bfe3 --- /dev/null +++ b/barcode/japanese/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-03 +description: Barcode generator C# チュートリアルでは、Aspose.BarCode を使用してバーコード画像を生成し、列と行を設定し、DataBar + Expanded Stacked 用の PNG ファイルを保存する方法を示します。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: ja +lastmod: 2026-08-03 +og_description: Barcode generator C# チュートリアルでは、Aspose.BarCode を使用してバーコード画像を生成し、DataBar + Expanded Stacked の列と行を設定し、PNG ファイルとして保存する方法を解説します。 +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: バーコードジェネレーター C# – バーコード画像を生成するステップバイステップガイド +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: バーコードジェネレーター C# – バーコード画像を生成 +url: /ja/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – バーコード画像の生成 + +DataBar Expanded Stacked 用のバーコード画像を生成できる barcode generator C# が必要な場合、このガイドでは全工程を解説します。列と行の設定方法、PNG への保存方法、他のシンボロジーへのコード適用方法を学べます。 + +バーコード画像をプログラムで生成することで手作業を省き、請求書、出荷ラベル、在庫システム間での一貫性を確保できます。このチュートリアルはプロジェクトのセットアップから完全なソースコードまで、必要なすべてを網羅しているので、すぐにサンプルを実行できます。 + +## 前提条件 + +* .NET 6.0 以降がインストールされていること +* Visual Studio 2022 などの IDE(C# をサポートするエディタならどれでも可) +* **Aspose.BarCode for .NET** のライセンス(無料評価版でテスト可能) +* C# 構文の基本的な知識 + +上記のいずれかが不足している場合は、dotnet.microsoft.com から .NET SDK をインストールし、以下のコマンドで Aspose.BarCode NuGet パッケージを取得してください。 + +```bash +dotnet add package Aspose.BarCode +``` + +## ステップ 1: barcode generator C# プロジェクトの作成 + +新しいコンソール アプリケーションを作成し、必要な `using` ディレクティブを追加します。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +`BarcodeGenerator` クラスは barcode generator C# API の中心です。シンボロジーの種類とエンコードするテキストを受け取ります。 + +## ステップ 2: DataBar Expanded Stacked バーコードを生成し、列数を設定する + +最初の例では、4 列のバーコードを作成します。`Columns` プロパティを調整すると、DataBar Expanded Stacked シンボロジーの視覚的密度が変わります。 + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**重要なポイント:** 列数は、コンパクトなスペースに格納できるデータ量に影響します。4 に設定すると、より幅広いバーコードになり、ほとんどのスキャナで読み取り可能です。 + +## ステップ 3: カスタム行数でバーコードを生成する + +2 番目の例では、`Rows` プロパティを設定して垂直レイアウトを制御する方法を示します。横幅が限られている場合に、より高さのあるバーコードが必要なときは、3 行構成が有用です。 + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**重要なポイント:** 行数を調整することで、狭い列にバーコードを収めつつ可読性を保てます。barcode generator C# は、仕様に合わせてモジュールサイズを自動的に再計算します。 + +## ステップ 4: 完全な実行可能サンプル + +以下は、前述の手順を組み合わせた単体で動作するプログラムです。コードを `Program.cs` に貼り付け、`YOUR_DIRECTORY` を既存のフォルダ パスに置き換えてアプリケーションを実行してください。 + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### 期待される出力 + +プログラムを実行すると、対象ディレクトリに 2 つの PNG ファイルが生成されます。 + +* **DatabarCols4.png** – 4 列の DataBar Expanded Stacked バーコード +* **DatabarRows3.png** – 同じデータを 3 行でエンコードしたもの + +任意の画像ビューアで画像を開くと、印刷や PDF への埋め込みに適した、鮮明でスキャン可能なバーコードが表示されます。 + +## カスタムサイズでバーコード画像を生成する方法 + +特定の画像サイズが必要な場合は、`Save` を呼び出す前に `ImageHeight` と `ImageWidth` プロパティを調整します。 + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +サイズを変更してもエンコードされたデータには影響せず、視覚的な表示だけが拡大・縮小されます。この手法は、固定レイアウトの UI コンポーネントにバーコードを組み込む際に便利です。 + +## よくある落とし穴とプロのコツ + +* **パス区切り文字:** Windows でのエスケープ文字問題を回避するため、逐語的文字列 (`@"C:\Path\file.png"`) または `Path.Combine` を使用してください。 +* **ライセンスの適用:** 有効なライセンスがない場合、生成された画像に透かしが入ります。アプリケーション開始時にライセンスを適用してください: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **エンコード制限:** DataBar Expanded Stacked は最大 74 桁の数字をサポートします。この上限を超えると例外がスローされます。ジェネレータを作成する前に入力長を検証してください。 +* **パフォーマンス:** 複数回保存する際に同一の `BarcodeGenerator` インスタンスを再利用するとメモリ割り当てが削減されます。エンコードするテキストが同じ場合のみ、保存間で `Rows` や `Columns` プロパティを変更してください。 + +## 次のステップ + +barcode generator C# でバーコード画像を生成できるようになったので、以下を検討してみてください。 + +* **異なるシンボロジー** – `EncodeTypes.QR`、`EncodeTypes.Code128`、`EncodeTypes.Pdf417` を試す。 +* **カラーカスタマイズ** – `Parameters.Barcode.ForeColor` と `BackColor` を設定してブランドに合わせる。 +* **PDF への埋め込み** – 生成した PNG を Aspose.PDF と組み合わせて印刷可能な文書を作成する。 + +これらの拡張により、在庫管理、物流、リテール向けのフル機能バーコードソリューションを構築できます。 + +--- + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を応用した関連トピックを扱っています。各リソースには、完全な動作コード例とステップバイステップの解説が含まれており、追加の 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 で DataMatrix バーコード (ECC 200) を生成する方法](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/japanese/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..d2cb4cce2 --- /dev/null +++ b/barcode/japanese/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-08-03 +description: C# のバーコードジェネレータ例です。幅の設定方法、高さの変更方法、バーコード画像の生成方法を示しています。ステップバイステップの手順に従ってください。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: ja +lastmod: 2026-08-03 +og_description: バーコードジェネレータの例では、X 軸の幅を設定し、バーの高さを変更し、C# でバーコード画像を生成する方法を示しています。手順に従って + PNG ファイルを作成してください。 +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: バーコードジェネレータの例 – C# の幅と高さのガイド +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: C# のバーコードジェネレータ例 – 幅と高さを設定 +url: /ja/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# のバーコードジェネレータ例 – 幅と高さの設定 + +C# で **バーコードジェネレータ例** が必要な場合、このガイドでは X‑dimension の幅の設定方法、バーの高さの変更方法、そしてバーコード画像ファイルの生成方法を示します。異なる高さの PNG ファイルを 2 つ生成する、完全に実行可能なプログラムをご覧いただけます。 + +典型的なシナリオは、スキャナの仕様を満たす必要がある製品ラベルの作成です。このチュートリアルの最後までに、幅と高さのパラメータをプログラムで調整し、結果を PNG 画像として保存できるようになります。 + +## 前提条件 + +開始する前に、以下が揃っていることを確認してください。 + +* .NET 6(またはそれ以降)がインストール済み – コードは .NET 6 SDK を対象としています。 +* `EncodeTypes.DatabarOmniDirectional` をサポートするバーコードライブラリ。例では **Aspose.BarCode for .NET** を使用していますが、同様のプロパティを持つ任意のライブラリでも同様に動作します。 +* プログラムをコンパイル・実行できる IDE またはエディタ(Visual Studio、VS Code、Rider など)。 +* PNG ファイルを保存するディレクトリへの書き込み権限。 + +> **プロのコツ:** プロジェクトルートに `Barcodes` フォルダを作成し、`Path.Combine` で参照すると、絶対パスのハードコーディングを回避できます。 + +## バーコードジェネレータ例: 初期化と構成 + +最初のステップは、目的のシンボロジーとデータ文字列で `BarcodeGenerator` インスタンスを作成することです。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +`EncodeTypes.DatabarOmniDirectional` 列挙体は Databar Omni‑directional シンボロジーを選択し、GS1 形式のデータ文字列 `(01)12345678901231` は典型的な GTIN‑14 値を表します。ジェネレータを一度初期化すれば、同じオブジェクトを複数の画像で再利用できます。 + +## 幅 (X‑dimension) の設定方法 + +X‑dimension はバーコードのモジュール幅を制御します。これを 2 ピクセルに設定すると、細いバーが 2 ピクセル幅になります。これは高密度印刷でよく求められる設定です。 + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +なぜ重要かというと、幅が小さすぎるとスキャナが個々のバーを認識できず、逆に大きすぎるとラベルのスペースを超えてしまう可能性があります。プリンタの DPI と対象ラベルサイズに合わせてピクセル値を調整してください。 + +## 高さの変更方法 + +バーの高さはバーがどれだけ高く表示されるかを決定します。例では 30 ピクセルの高さと 60 ピクセルの高さの 2 つの画像を作成します。 + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +`BarHeight.Pixels` プロパティはバーの視覚的な高さに直接影響します。保存のたびにこの値を変更すれば、ジェネレータを再作成せずに同一データから複数のバリエーションを生成できます。 + +### 期待される出力 + +プログラムを実行すると、`Barcodes` フォルダに 2 つの PNG ファイルが生成されます。 + +* `DatabarBarHeight30Pixels.png` – バーの高さが 30 ピクセル。 +* `DatabarBarHeight60Pixels.png` – バーの高さが 60 ピクセル。 + +両画像は同じ幅(X‑dimension によって決定)を共有し、同一の GTIN‑14 データをエンコードしています。 + +![C# コードで生成された高さが異なる 2 つのバーコード PNG ファイル](barcode-example.png "高さのバリエーションを示すバーコードジェネレータ例") + +*上記の画像 alt テキストは、アクセシビリティと SEO のために主要キーワードを含んでいます。* + +## C# でバーコード画像を生成する方法 + +`Save` メソッドはバーコードデータから画像ファイルへの変換を処理します。別の形式(JPEG、BMP、SVG)にしたい場合は、異なる `BarCodeImageFormat` 列挙値を渡すだけです。例では PNG を使用しています。PNG はロスレス品質を保ち、広くサポートされているためです。 + +バーコードを PDF や Web ページに直接埋め込みたい場合は、画像を `byte[]` として取得できます。 + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +この方法により一時ファイルが不要になり、高スループットなサービスで有用です。 + +## よくあるバリエーションとエッジケース + +| 状況 | 調整 | +|-----------|------------| +| **異なるシンボロジー** | `EncodeTypes.DatabarOmniDirectional` を別の列挙値(例: `EncodeTypes.Code128`)に置き換える。 | +| **非常に小さいラベル** | `XDimension.Pixels` を 1 ピクセルに減らす。ただしスキャナの可読性を確認すること。 | +| **高解像度印刷** | X‑dimension とバー高さを比例的に増やす(例: 幅 4 px、高さ 80 px)。 | +| **動的データ** | データ文字列を実行時に渡す。データベースレコードから取得するケースが典型的。 | +| **バッチ生成** | データ文字列のコレクションをループし、`generator.Text` を更新しながら同一 `BarcodeGenerator` インスタンスを再利用する。 | + +`ArgumentOutOfRangeException` などの例外が発生した場合は、ピクセル値が正の整数であること、出力ディレクトリが存在することを再確認してください。 + +## 完全なソースコードまとめ + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +コードを新しいコンソールプロジェクトに貼り付け、Aspose.BarCode NuGet パッケージを復元(`dotnet add package Aspose.BarCode`)し、`dotnet run` を実行してください。保存されたファイルを示すコンソールメッセージが表示されます。 + +## 結論 + +この **バーコードジェネレータ例** は、幅の設定方法、高さの変更方法、そして C# でバーコード画像を生成する手順を示しています。`XDimension.Pixels` と `BarHeight.Pixels` を調整することでバーコードの視覚サイズを制御でき、`Save` メソッドで PNG ファイルとして出力できます。さまざまなシンボロジー、出力形式、データ文字列を試して、アプリケーションの要件に合わせて最適化してください。 + +**次のステップ** + +* Web 用に他の画像形式(SVG、JPEG)で **バーコードを生成する方法** を探求する。 +* ASP.NET Core エンドポイントで PNG を直接ブラウザに返す **C# でバーコード画像を作成する** 方法を学ぶ。 +* このコードを PDF 生成ライブラリと組み合わせ、請求書や出荷ラベルにバーコードを埋め込む。 + +サンプルを自由にカスタマイズし、結果を共有したり、コメントで質問したりしてください。ハッピーコーディング! + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示したテクニックを基にした、密接に関連するトピックをカバーしています。各リソースには、完全な動作コード例とステップバイステップの解説が含まれており、追加の API 機能を習得したり、代替実装アプローチを自分のプロジェクトで試したりするのに役立ちます。 + +- [バーコードの生成方法 - 1 次元バーコードタイプ](/barcode/english/net/one-dimensional-barcode-types/) +- [ITF-14 バーコードのカスタマイズで枠線を設定する方法](/barcode/english/net/itf-14-barcode-customization/) +- [Aspose.BarCode for .NET で DataMatrix バーコード (ECC 200) を生成する方法](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/japanese/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..5d6f47ad5 --- /dev/null +++ b/barcode/japanese/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-08-03 +description: C#でバーコードPNGを作成し、DataBar画像のアスペクト比の変更方法を学びましょう。このコードとヒントが含まれた完全な例に従ってください。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: ja +lastmod: 2026-08-03 +og_description: C#でバーコードPNGを作成し、DataBarバーコードのアスペクト比の変更方法を確認しましょう。このガイドでは、すぐに実行できるコードと実用的なヒントを提供します。 +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: C#でバーコードPNGを作成 – アスペクト比制御付きの完全例 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: C#でバーコードPNGを作成する – ステップバイステップガイド +url: /ja/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# でバーコード PNG を作成 – ステップバイステップ ガイド + +C# で **バーコード PNG を作成** したい場合は、このチュートリアルが手順をすべて示します。スタック型全方向 DataBar バーコードを生成し、PNG ファイルとして保存し、**アスペクト比の変更方法** を学んで、さまざまなスキャン環境に合わせられるようになります。 + +本ガイドでは、必要なパッケージ、完全に実行可能なプログラム、各設定が重要な理由の説明をすべて網羅しています。最後には、アスペクト比が 15 の PNG と 30 の PNG の 2 つのファイルが作成され、テストや本番環境で使用できる状態になります。 + +## 前提条件 + +開始する前に、以下を確認してください。 + +- .NET 6.0 SDK 以降がインストール済み +- Visual Studio 2022(または任意の C# IDE) +- **Aspose.BarCode** への NuGet 参照(`BarcodeGenerator` を提供するライブラリ) +- PNG ファイルを保存するディレクトリへの書き込み権限 + +以下のコマンドで Aspose.BarCode パッケージを追加できます。 + +```bash +dotnet add package Aspose.BarCode +``` + +## 手順 1: プロジェクトの作成と名前空間のインポート + +新しいコンソール アプリケーションを作成し、バーコード生成とファイル I/O に必要な名前空間をインポートします。 + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**ポイント:** `Aspose.BarCode.Generation` をインポートすると `BarcodeGenerator` が利用可能になります。コードを `Main` 内に収めることで、サンプルが自己完結し、実行が容易になります。 + +## 手順 2: スタック型全方向 DataBar 用のバーコードジェネレータを作成 + +`EncodeTypes.DatabarStackedOmniDirectional` タイプとサンプルの GS1‑128 データ文字列で `BarcodeGenerator` をインスタンス化します。 + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**ポイント:** 選択したエンコードタイプは高密度の DataBar を生成し、最新のスキャナで読み取れます。データ文字列は GS1 アプリケーション識別子 (01) 形式で、製品識別子として一般的です。 + +## 手順 3: X‑ディメンション(モジュール幅)をピクセル単位で設定 + +モジュール幅を設定して、バーコード全体のサイズを制御します(可読性には影響しません)。 + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**ポイント:** X‑ディメンションを 2 ピクセルにすると、スキャナに対して小さすぎず、ラベル領域に対して大きすぎないサイズになります。 + +## 手順 4: アスペクト比 15 で最初の PNG を保存 + +DataBar のアスペクト比を調整し、画像を PNG ファイルとして保存します。 + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**ポイント:** アスペクト比はスタック型 DataBar の高さと幅の比率を決めます。比率 15 は可読性とラベル高さのバランスが取れた一般的なデフォルトです。 + +## 手順 5: アスペクト比を 30 に変更し、2 番目の PNG を保存 + +同じジェネレータ インスタンスのアスペクト比を大きくし、2 番目の画像を保存します。 + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**ポイント:** アスペクト比を上げるとバーコードが縦に伸び、低解像度デバイスや狭い媒体に印刷した場合のスキャン信頼性が向上します。 + +## 期待される出力 + +プログラムを実行すると、以下の 2 つの PNG ファイルが作成されます。 + +| ファイル名 | アスペクト比 | おおよそのサイズ(ピクセル) | +|--------------------------------------|--------------|------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300(幅 × 高さ) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600(幅 × 高さ) | + +どちらの画像も、GS1 識別子 `(01)12345678901231` をエンコードした、はっきりと読み取れる DataBar バーコードを含んでいます。 + +## よくある質問とエッジケース + +### 他の視覚プロパティはどう変更する? + +`generator.Parameters.Barcode` オブジェクトを使って前景色、背景色、ヒューマンリーダブルテキストなどを調整できます。例: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### 別の画像形式が必要な場合は? + +`BarCodeImageFormat.Png` を `Jpeg`、`Bmp`、`Gif` などに置き換えてください。PNG はロスレスなバーコード画像として最適です。 + +### アスペクト比はスキャン速度に影響しますか? + +アスペクト比が高いほどバーコードの高さが増し、短いスタックシンボルが苦手なデバイスでのスキャン信頼性が向上します。ただし、極端に高いバーコードは小さなラベルに収まらない可能性があるため、対象ハードウェアでテストしてください。 + +### ループで複数のバーコードを生成できますか? + +可能です。各データ文字列ごとに新しい `BarcodeGenerator` を作成するか、同じインスタンスを再利用しつつ `CodeText` と `DataBar.AspectRatio` を更新します。これによりオブジェクト割り当てのオーバーヘッドが削減されます。 + +## プロのコツ + +- **ジェネレータを再利用**: `CodeText` や `AspectRatio` だけを変更すれば、オブジェクトの再生成を避けられ、バッチ処理が高速化します。 +- **出力を検証**: ハンドヘルドスキャナやモバイルアプリで生成した PNG が正しく読み取れるか確認してから本番環境に展開しましょう。 +- **ファイル名にアスペクト比を含める**: テスト時にバリエーションを管理しやすくするため、例に示したようにファイル名に比率を入れます。 + +## 結論 + +これで C# で **バーコード PNG を作成** し、スタック型全方向 DataBar シンボルの **アスペクト比の変更方法** を正確に理解できました。完全なサンプルは、初期化、X‑ディメンション設定、アスペクト比操作、画像保存をすべて単一の実行可能プログラムで示しています。 + +ここからは、他のバーコードタイプを試したり、色をカスタマイズしたり、ジェネレータをレポートや在庫管理システムに組み込んだりして、さらに活用の幅を広げてください。コーディングを楽しんでください! + + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした、密接に関連するトピックをカバーしています。各リソースには、ステップバイステップの解説と完全なコード例が含まれており、API の追加機能を習得したり、代替実装アプローチを自プロジェクトで試したりするのに役立ちます。 + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/japanese/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..d3646e92f --- /dev/null +++ b/barcode/japanese/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-08-03 +description: このガイドでバーコードPNGをすばやく作成しましょう。Aspose.BarCodeを使用してバーコード画像を生成する方法と、プラネットバーコードの生成方法を学びます。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: ja +lastmod: 2026-08-03 +og_description: バーコードPNGを即座に作成します。このチュートリアルでは、バーコード画像の生成方法と、Aspose.BarCode を使用したプラネットバーコードの生成方法を示します。 +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: PythonでバーコードPNGを作成する – 完全プログラミングガイド +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: PythonでバーコードPNGを作成する – ステップバイステップガイド +url: /ja/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PythonでバーコードPNGを作成する – ステップバイステップガイド + +Pythonアプリケーションから **barcode PNG** ファイルを作成する必要がある場合、このチュートリアルで具体的な方法を示します。Aspose.BarCode を使用して **barcode image** を生成する手順を解説し、特にカスタムサイズで **planet barcode** を生成します。 + +このチュートリアルでは、ライブラリのインストール方法、Planet シンボロジーの設定、サイズパラメータの調整、そして高品質 PNG として保存する方法を学びます。基本的な Python の知識と、Python 3(3.8 以降)の最新バージョンが前提です。バーコード規格の事前知識は不要です。 + +--- + +## Aspose.BarCodeでbarcode PNGを作成する方法 + +このセクションでは **barcode PNG** を作成するための基本手順を示します。各ステップにはコードスニペット、重要性の説明、すぐに活用できる実用的なヒントが含まれています。 + +### 1. Aspose.BarCode パッケージをインストールする + +Aspose は .NET コアエンジンをラップした純粋な Python パッケージを提供しています。`pip` でインストールします: + +```bash +pip install aspose-barcode +``` + +*Why this step matters:* The package supplies the `BarcodeGenerator` class used throughout the example. Installing it globally ensures the interpreter can locate the assembly at runtime. + +### 2. 必要なクラスをインポートする + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Tip:* Import only the symbols you need; this keeps the namespace clean and speeds up module loading. + +### 3. Planet シンボロジー用のバーコードジェネレータを作成する + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Why this matters:* `EncodeTypes.Planet` tells the engine to use the Planet barcode standard, while the second argument supplies the data to encode. Changing the symbology (e.g., `EncodeTypes.Code128`) would produce a completely different visual pattern. + +### 4. X ディメンション(モジュール幅)をピクセル単位で設定する + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Explanation:* The X dimension controls the narrow bar width. A value of 4 pixels yields a moderately dense barcode that remains scannable on most devices. + +### 5. 手動でバーの高さをピクセル単位で定義する + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Why you might adjust this:* Some retail printers require taller bars for reliable scanning. The default height is usually 50 px; increasing it to 100 px improves readability without enlarging the file size dramatically. + +### 6. 生成したバーコードを PNG 画像として保存する + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Result:* A PNG file named **PlanetBarHeight100.png** appears in the `output` folder. PNG is loss‑less, making it ideal for printing and for embedding in web pages. + +### 7. 出力を確認する(オプション) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Tip:* Viewing the image confirms that the dimensions match the parameters you set. If the barcode looks distorted, revisit the X dimension or bar height settings. + +--- + +## PNG 形式でバーコード画像を生成する方法(代替設定) + +別の画像形式が必要、または後で PDF に埋め込みたい場合は、`BarCodeImageFormat` 列挙体を変更できます: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Why this matters:* PNG preserves every pixel, which is crucial for high‑contrast barcodes. JPEG introduces compression artifacts that can interfere with scanning, while BMP offers compatibility with older tools. + +--- + +## カスタムカラーで Planet バーコードを生成する(上級) + +サイズ以外にも、前景色と背景色をカスタマイズできます: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Practical tip:* High‑contrast color pairs (dark on light) maximize scanner reliability. Avoid using similar hues for foreground and background. + +--- + +## よくある落とし穴と回避方法 + +| 症状 | 原因 | 対策 | +|------|------|------| +| バーコードが読み取れない | X ディメンションが小さすぎる(≤ 2 px) | `x_dimension.pixels` を少なくとも 3 px に増やす | +| 画像がぼやけて見える | PNG が低 DPI で保存されている | `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` のように 300 DPI を指定する(サポートされていれば) | +| 例外 `ImportError` | Aspose.BarCode がインストールされていない | スクリプトと同じ環境で `pip install aspose-barcode` を実行する | +| シンボロジーが間違っている | `EncodeTypes.Code128` を使用したため `EncodeTypes.Planet` ではない | ジェネレータ作成時に `EncodeTypes.Planet` に置き換える | + +--- + +## 完全なソリューションのまとめ + +以下は **barcode PNG** を最初から最後まで作成する完全な実行可能スクリプトです: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Running this script produces a crisp **Planet barcode PNG** that you can embed in HTML, attach to emails, or print on product labels. + +--- + +## 次のステップと関連トピック + +* **Integrate with Flask or Django** – serve the generated PNG directly from a web endpoint. +* **Batch generation** – loop over a list of product IDs to create a folder of barcode PNG files. +* **Combine with PDF generation** – use `aspose-pdf` to place the PNG into an invoice or shipping label. +* **Explore other symbologies** – replace `EncodeTypes.Planet` with `EncodeTypes.QR`, `EncodeTypes.DataMatrix`, or `EncodeTypes.Code128` to meet different business needs. + +By mastering the steps above, you now know **how to generate barcode image** programmatically and can extend the pattern to any barcode standard supported by Aspose.BarCode. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/japanese/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..a067f2943 --- /dev/null +++ b/barcode/japanese/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-08-03 +description: C#で郵便バーコード画像を素早く作成します。郵便バーコードの生成方法、バーコードのサイズ設定、そしてPlanetバーコードの生成方法を学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: ja +lastmod: 2026-08-03 +og_description: この完全なチュートリアルでC#を使用して郵便バーコード画像を作成し、バーコードのサイズ設定方法、Planetバーコードの生成、RM4SCCバーコードの作成を学びましょう。 +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: C#で郵便バーコード画像を作成する – 完全プログラミングガイド +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: C#で郵便バーコード画像を作成する – ステップバイステップガイド +url: /ja/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#で郵便バーコード画像を作成 – ステップバイステップガイド + +C#で**郵便バーコード画像を作成**する必要がある場合、このガイドで具体的な手順を示します。**郵便バーコードの生成方法**、**バーコードのサイズ設定方法**、そして一般的な郵便規格向けの**Planetバーコードの生成方法**について解説します。 + +最終的に、使用可能なPNGファイルが2つ作成されます—1つはPlanetバーコード、もう1つはRM4SCCバーコードで、どちらも高さ100 pxです。追加のツールは必要なく、Aspose.BarCode for .NET ライブラリだけで完結します。 + +## 前提条件 + +* .NET 6 SDK 以降(コードは .NET Framework 4.7+ でも動作します) +* Visual Studio 2022 または任意の C# IDE +* NuGet パッケージ **Aspose.BarCode**(`BarcodeGenerator` を提供するライブラリ) + +## 手順 1: バーコードライブラリのインストール + +プロジェクトフォルダーでターミナルを開き、以下を実行します: + +```bash +dotnet add package Aspose.BarCode +``` + +このパッケージにより `Aspose.BarCode` 名前空間が追加され、郵便バーコードに必要な `BarcodeGenerator` と `EncodeTypes` 列挙体が利用可能になります。 + +## 手順 2: 出力フォルダーの定義 + +信頼できる出力パスを作成することで、フォルダーが存在しない場合の実行時エラーを防止できます。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*重要な理由*: `Directory.CreateDirectory` は冪等であり、フォルダーがまだ存在しない場合にのみ作成するため、以降の実行で例外が発生しません。 + +## 手順 3: 共通バーコード寸法の設定 + +X‑ディメンション(単一バーの幅)と全体のバー高さを設定することで、生成される画像の視覚的サイズを制御できます。 + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**バーコード寸法の設定方法**: `Parameters.Barcode.XDimension.Pixels` プロパティは細いバーの幅を、`Parameters.Barcode.BarHeight.Pixels` は全体の高さを定義します。これらの値を調整して、利用する郵便サービスの仕様に合わせてください。 + +## 手順 4: Planet バーコードの生成 + +Planet はイギリスで広く使用されている郵便バーコードです。以下のコードは高さ100 px の Planet バーコードを作成し、PNG として保存します。 + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**このコードが機能する理由**: `EncodeTypes.Planet` はジェネレーターに Planet シンボルを使用させます。`Save` メソッドは指定されたパスに PNG ファイルを書き込み、先に設定した寸法を保持します。 + +## 手順 5: RM4SCC バーコードの生成 + +RM4SCC はオランダの郵便バーコード規格です。以下のコードは Planet の例と同様で、**異なるタイプの郵便バーコードを同一寸法で生成する方法**を示しています。 + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +2つの PNG ファイルは `Barcodes` フォルダーに保存されます。開くと、印刷や文書への埋め込みに適した、きれいな高さ100 px のバーコードが確認できます。 + +## 完全なソースコード + +以下は、Planet と RM4SCC の両規格向けに **郵便バーコード画像を作成**する完全な実行可能プログラムです。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### 期待される出力 + +プログラムを実行すると、ファイルパスが出力され、2つの PNG ファイルが作成されます: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +各画像は高さ100 px、細いバー幅は4 ピクセルで、設定した寸法と一致しています。 + +## 実践的なヒントと一般的な落とし穴 + +* **フォルダー権限** – プログラムが制限されたアカウントで実行される場合、対象フォルダーが書き込み可能であることを確認してください。 +* **異なる寸法** – より高いバーコードを作成するには `barHeightPixels` を増やします。解像度を上げるには `xDimensionPixels` を小さくしますが、レンダリングのアーティファクトを防ぐために 2 以上に保ってください。 +* **他の郵便シンボロジー** – Aspose.BarCode は `EncodeTypes.Postnet` や `EncodeTypes.AustralianPost` もサポートしています。`EncodeTypes` の値を変更し、同じ寸法ロジックを使用してください。 +* **画像形式** – ロスレス品質が不要な場合は、`BarCodeImageFormat.Jpeg` を使用してファイルサイズを小さくできます。 + +## 結論 + +これで、C# で **郵便バーコード画像** を作成する方法—寸法を設定し、適切なシンボロジーを選択し、PNG として保存する—が分かりました。本チュートリアルでは **郵便バーコードの生成方法**、**Planet バーコードの生成**、そして一貫した出力のための **バーコード寸法の設定方法** を解説しました。 + +次のステップとして **バーコードの色カスタマイズ**、**人が読めるテキスト** の追加、または画像を PDF 請求書に組み込むことを検討してください。同じパターンは Aspose.BarCode がサポートする他のすべてのバーコードタイプにも適用でき、郵便自動化ワークフロー全体へと拡張できます。 + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを扱っています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、追加の API 機能を習得し、プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [バーコード生成方法 - 一次元バーコードタイプ](/barcode/english/net/one-dimensional-barcode-types/) +- [Aspose.BarCode for .NET を使用したカスタムアスペクト比の Aztec バーコード生成](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Java でバーコード生成 – Aspose を使用したオーストラリアポストバーコード](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/japanese/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..6c58f0071 --- /dev/null +++ b/barcode/japanese/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-08-03 +description: ステップバイステップのバーコードジェネレーター例を使って、C#でバーコードを保存する方法。Planetバーコードの生成、サイズ設定、PNG画像へのエクスポートを学びましょう。 +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: ja +lastmod: 2026-08-03 +og_description: バーコードジェネレーターの例を使用してC#でバーコードを保存する方法。このチュートリアルでは、Planetバーコードの生成、Xディメンションの設定、PNGファイルへのエクスポート方法を示します。 +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: C#でバーコードを保存する方法 – ステップバイステップガイド +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: C#でバーコードを保存する方法 – 完全なバーコードジェネレーターガイド +url: /ja/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#でバーコードを保存する方法 – 完全なバーコードジェネレータガイド + +C#でバーコード画像を保存することは、請求書、出荷ラベル、在庫タグに郵便バーコードを埋め込む必要がある場合に一般的な要件です。このガイドでは、実用的な **c# barcode generator** ワークフローをステップバイステップで説明します。Planet バーコードの作成から、filled‑bars と empty‑bars の PNG ファイルのエクスポートまでをカバーします。 + +バー幅の設定方法、filled bars の切り替え、出力フォルダーの確実な処理方法を学びます。チュートリアルの最後までに、任意の .NET プロジェクトにコピーできる完全に機能する **barcode generator example** を手に入れることができます。 + +## 必要なもの + +- .NET 6.0 SDK 以上(例は .NET Core と .NET Framework でも動作します) +- Visual Studio 2022 または任意の C# 対応 IDE +- **Aspose.BarCode** NuGet パッケージ(または `EncodeTypes.Planet` をサポートする他のライブラリ)。以下でインストールします: + +```bash +dotnet add package Aspose.BarCode +``` + +このライブラリは、本チュートリアル全体で使用される `BarcodeGenerator` クラスを提供します。 + +## 開発環境の設定 + +新しいコンソールプロジェクトを作成し、必要な名前空間を追加します: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +`System.IO` 名前空間は `Directory.CreateDirectory` を提供し、ファイルを書き込む前に出力フォルダーが存在することを保証します。 + +## C# バーコードジェネレータでバーコード画像を保存する方法 + +このソリューションの核心は、**Planet barcode** を設定し、画像をディスクに保存する一連の手順です。以下のセクションでプロセスを分かりやすく分割しています。 + +### 手順 1: 出力フォルダーの定義 + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**なぜ?** +パスをハードコーディングすると、フォルダーが存在しないマシンで `DirectoryNotFoundException` が発生する可能性があります。`CreateDirectory` は冪等で、フォルダーが存在しない場合にのみ作成するため、コードを繰り返し実行しても安全です。 + +### 手順 2: Planet バーコードジェネレータの作成(filled bars) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**なぜ?** +`EncodeTypes.Planet` はライブラリに郵便用 Planet バーコードを生成させます。これは郵便サービスで広く使用されています。文字列 `"123456"` はサンプルペイロードです。ビジネスロジックで必要な任意の数値データに置き換えてください。 + +### 手順 3: バー幅(X‑dimension)を設定し、デフォルトの filled bars を保持する + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**なぜ?** +X‑dimension は各バーの物理的な幅を制御します。`4` ピクセルの値は標準的な 300 dpi プリンタで読み取り可能なバーコードを生成します。`FilledBars` を `true`(デフォルト)のままにすると、従来の実線バーの外観になります。 + +### 手順 4: filled‑bars バーコード画像を保存する + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**なぜ?** +PNG で保存するとロスレスの画像品質が保たれ、スキャン精度に重要です。`Save` メソッドは自動的に画像ファイルを作成するので、フルパスと希望のフォーマットを指定するだけです。 + +### 手順 5: empty‑bars バージョン用に2つ目のジェネレータを作成する + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +新しいインスタンスを作成することで、empty‑bars バージョン用に行った変更が、すでに保存された filled‑bars 画像に影響しないようにします。 + +### 手順 6: 同じ X‑dimension を保ちつつ filled bars を無効にする + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**なぜ?** +`FilledBars = false` を設定すると、各バーの輪郭だけが描画されます。これは一部の郵便規格で視覚的検証のために要求されます。 + +### 手順 7: empty‑bars バーコード画像を保存する + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +これで、filled bars と empty bars の 2 つの PNG ファイルが作成され、PDF、HTML メール、印刷ラベルへの組み込みが可能になります。 + +## 完全に実行可能なプログラム + +以下は `Program.cs` にコピーできる完全なコードです。Aspose.BarCode パッケージがインストールされていれば、変更せずにコンパイル・実行できます。 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### 期待される出力 + +プログラムを実行すると、以下のような 2 行が出力されます: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +`Barcodes` フォルダーを開くと、2 つの PNG ファイルが確認できます。どちらの画像も任意の画像ビューアで開くか、文書に直接埋め込むことができます。 + +![バーコード保存例](barcode-example.png){: .align-center alt="バーコード保存例"} + +## 一般的なバリエーションとエッジケース + +| シナリオ | 調整 | +|----------|------------| +| **異なる画像形式** | `BarCodeImageFormat.Png` を必要に応じて `Jpeg`、`Gif`、または `Bmp` に変更します。 | +| **カスタム出力サイズ** | 特定のピクセル寸法を強制するには、`filled.Parameters.Image.Width` と `Height` を使用します。 | +| **動的データ** | 静的な `"123456"` を、注文番号や追跡 ID などを保持する変数に置き換えます。 | +| **存在しないフォルダー** | `Directory.CreateDirectory` は既に欠落したディレクトリを処理するので、追加のコードは不要です。 | +| **高解像度印刷** | 600 dpi プリンタ向けに `XDimension.Pixels` を 6〜8 に増やしますが、スキャナとの互換性を確認してください。 | + +**Pro tip:** ループで多数のバーコードを生成する必要がある場合、単一の `BarcodeGenerator` インスタンスを再利用し、各 `Save` 前に `CodeText` プロパティだけを変更してください。これによりオブジェクト割り当てのオーバーヘッドが削減されます。 + +## 他の規格のバーコードを生成する方法 + +同じパターンは `Code128`、`QR`、`DataMatrix` などの他の `EncodeTypes` でも機能します。単に `EncodeTypes.Planet` を目的のタイプに置き換え、タイプ固有のパラメータ(例: `QRCodeVersion`)を調整してください。 + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックを扱っています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [Aspose.BarCode を使用した DataMatrix C40 の PNG 保存方法](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [.NET 用 Aspose.BarCode で DataMatrix バーコード(ECC 200)を生成する方法](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Aspose.BarCode でバーコード – Code 39 の設定方法](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/korean/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..52c85ac0e --- /dev/null +++ b/barcode/korean/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-03 +description: Aspose.BarCode를 사용하여 Planet 바코드를 생성하고 X‑디멘션을 설정한 뒤 PNG 이미지로 저장하는 C# 바코드 + 생성기 튜토리얼. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: ko +lastmod: 2026-08-03 +og_description: Barcode generator C# 튜토리얼은 Planet 바코드를 생성하고 X‑디멘션을 조정하며 Aspose.BarCode를 + 사용해 PNG로 저장하는 과정을 단계별로 안내합니다. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: 바코드 생성기 C# – 플래닛 바코드 단계별 만들기 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: 바코드 생성기 C# – 플래닛 바코드 및 RM4SCC 예제 +url: /ko/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – create Planet barcode and RM4SCC example + +우편 전용 심볼을 생성할 수 있는 **barcode generator C#**가 필요하다면, 이 가이드는 Aspose.BarCode를 사용해 **Planet barcode** 이미지를 만드는 방법을 정확히 보여줍니다. X‑dimension을 설정하고, 일치하는 RM4SCC 바코드를 생성한 뒤, 두 이미지를 PNG 파일로 저장하는 과정을 몇 단계만에 설명합니다. + +이 튜토리얼은 .NET 6 이상에서 코드를 실행하는 데 필요한 모든 사항을 다루며, 각 설정이 왜 중요한지, 모듈 폭이 잘못되었거나 디렉터리 권한이 없을 때 발생할 수 있는 일반적인 함정들을 짚어줍니다. 최종적으로 Planet 및 RM4SCC 표준을 준수하는 두 개의 인쇄 준비된 바코드 이미지를 얻게 됩니다. + +## Prerequisites + +시작하기 전에 다음이 준비되어 있는지 확인하세요: + +* .NET 6 SDK (또는 Aspose.BarCode가 지원하는 .NET 버전) +* Visual Studio 2022 또는 선호하는 C# IDE +* **Aspose.BarCode**에 대한 NuGet 참조 (`Install-Package Aspose.BarCode`) +* PNG 파일을 저장할 폴더에 대한 쓰기 권한 + +추가 외부 서비스는 필요하지 않습니다; 라이브러리가 모든 인코딩을 로컬에서 처리합니다. + +## Step 1: Initialise the barcode generator C# object + +첫 번째 작업은 `BarcodeGenerator` 인스턴스를 만드는 것입니다. 생성자는 바코드 심볼(`EncodeTypes.Planet`)과 인코딩할 데이터를 받습니다. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Why this step?* +`BarcodeGenerator`는 생성하는 모든 바코드의 진입점입니다. `EncodeTypes.Planet`을 선택하면 많은 우편 서비스에서 사용하는 ISO/IEC 24723 사양을 따르게 됩니다. + +## Step 2: Set the X‑dimension (module width) for the Planet barcode + +X‑dimension은 단일 바코드 모듈(가장 작은 바 또는 공백)의 폭을 정의합니다. **4 픽셀** 값은 대부분의 라벨 프린터에 잘 맞습니다. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Why this matters* +모듈이 너무 좁으면 바코드가 읽히지 않을 수 있고, 너무 넓으면 라벨 크기가 불필요하게 커집니다. `Pixels`를 조정하면 프린터 해상도에 맞게 바코드를 미세 조정할 수 있습니다. + +## Step 3: Save the Planet barcode as a PNG image + +Aspose.BarCode는 선택한 심볼에 따라 바코드 높이를 자동으로 계산하므로 파일 경로와 포맷만 지정하면 됩니다. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tip* +`YOUR_DIRECTORY`를 실제 존재하는 절대 경로나 상대 경로로 바꾸세요. 디렉터리가 없으면 `Save` 메서드가 `DirectoryNotFoundException`을 발생시킵니다. + +**Expected output** – 아래 그림과 비슷한 PNG 파일이 생성됩니다(실제 이미지는 표시되지 않지만, `123456`이라는 숫자 페이로드를 가진 클래식 Planet 바코드를 확인할 수 있습니다). + +## Step 4: Initialise a second generator for the RM4SCC barcode + +많은 우편 시스템에서는 동일한 우편물에 Planet과 RM4SCC 두 심볼을 모두 요구합니다. RM4SCC 심볼용으로 새로운 `BarcodeGenerator` 인스턴스를 생성하세요. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Why a separate instance?* +각 심볼마다 고유한 매개변수가 있습니다. 동일한 제너레이터를 재사용하면 (예: X‑dimension) 두 번째 바코드에 최적이 아닌 설정이 그대로 전달될 수 있습니다. + +## Step 5: Configure the X‑dimension for the RM4SCC barcode + +RM4SCC도 X‑dimension 설정을 따르므로, 시각적 일관성을 위해 동일한 픽셀 폭을 적용합니다. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +라벨이 큰 경우 `Height.Pixels`를 설정해 더 높은 바코드를 만들 수 있습니다. 설정하지 않으면 라이브러리가 자동으로 이상적인 높이를 계산합니다. + +## Step 6: Save the RM4SCC barcode as a PNG image + +마지막으로 RM4SCC 바코드를 디스크에 저장합니다. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +이제 두 개의 PNG 파일—`PostalPlanetBarHeightNone.png`와 `PostalRM4SCCBarHeightNone.png`—을 갖게 되었으며, 이를 우편 라벨에 삽입하거나 봉투에 인쇄하거나 제3자 인쇄 서비스에 전달할 수 있습니다. + +## Optional: Adjusting height or using other image formats + +워크플로우에 특정 바코드 높이나 다른 이미지 포맷(JPEG, BMP 등)이 필요하면 `Save` 호출 전에 매개변수를 수정하면 됩니다. + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Edge case** – 사용자 정의 높이를 설정할 때 ISO 표준에서 요구하는 최소 높이를 만족하는지 확인하세요. 그렇지 않으면 바코드 검증에 실패할 수 있습니다. + +## Common pitfalls and how to avoid them + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| `DirectoryNotFoundException` | 대상 폴더가 존재하지 않거나 이름이 잘못되었습니다. | 먼저 폴더를 만들거나 `Path.Combine`과 `Environment.CurrentDirectory`를 사용하세요. | +| Barcode unreadable on low‑resolution printers | X‑dimension이 프린터 DPI에 비해 너무 작습니다. | 203 dpi 프린터의 경우 `XDimension.Pixels`를 5 – 6으로 늘리거나 샘플 라벨로 테스트하세요. | +| Wrong symbology used | `EncodeTypes.Code128`을 사용했지만 `EncodeTypes.Planet`이 필요합니다. | `EncodeTypes` 열거형 값이 요구되는 우편 표준과 일치하는지 다시 확인하세요. | +| Null reference on `Parameters` | API가 다른 이전 버전의 Aspose.BarCode를 사용하고 있습니다. | 최신 NuGet 패키지(v23.12 이상)로 업그레이드하세요. | + +## Full runnable example + +아래는 복사·붙여넣기만 하면 바로 실행할 수 있는 전체 프로그램입니다. `using` 구문, 오류 처리, 각 라인을 설명하는 주석이 포함되어 있습니다. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +프로그램을 실행하면 실행 파일 옆에 `Barcodes` 폴더가 생성되고 두 PNG 파일이 그 안에 저장됩니다. 이미지 뷰어로 열어 결과를 확인하세요. + +## Conclusion + +이제 **barcode generator C#** 솔루션을 통해 **Planet barcode** 이미지를 생성하고, 최적 인쇄를 위한 X‑dimension을 조정하며, 일치하는 RM4SCC 바코드도 함께 만들 수 있습니다. .NET 6+ 환경에서 Aspose.BarCode NuGet 패키지만 있으면 되며, `EncodeTypes` 값을 교체하면 Code128, QR, DataMatrix 등 다른 심볼에도 확장할 수 있습니다. + +### What’s next? + +* 프린터 DPI에 맞게 `XDimension.Pixels` 값을 실험해 보세요. +* `BarCodeImageFormat` 열거형을 변경해 PDF, SVG 등 다른 포맷으로 바코드를 생성해 보세요. +* **SkiaSharp** 같은 그래픽 라이브러리를 사용해 두 PNG 파일을 하나의 라벨로 결합해 보세요. +* 체크섬 검증이나 사용자 정의 폰트와 같은 고급 기능을 위해 Aspose.BarCode 전체 API를 탐색해 보세요. + +코드를 배치 처리에 맞게 조정하거나, 요청 시 바코드 이미지를 반환하는 ASP.NET Core 웹 서비스에 통합해도 좋습니다. 즐거운 코딩 되세요! + + +## What Should You Learn Next? + + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 기반으로 하여 관련 주제를 심도 있게 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 제공하므로, 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하는 데 도움이 됩니다. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/korean/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..4b86c89f9 --- /dev/null +++ b/barcode/korean/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-08-03 +description: Barcode generator C# 튜토리얼은 Aspose.BarCode를 사용하여 바코드 이미지를 생성하고, 열과 행을 + 설정하며, DataBar Expanded Stacked에 대한 PNG 파일을 저장하는 방법을 보여줍니다. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: ko +lastmod: 2026-08-03 +og_description: Barcode generator C# 튜토리얼에서는 Aspose.BarCode를 사용하여 바코드 이미지를 생성하고, DataBar + Expanded Stacked의 열과 행을 구성하며, PNG 파일로 저장하는 방법을 설명합니다. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: 바코드 생성기 C# – 바코드 이미지를 생성하는 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: 바코드 생성기 C# – 바코드 이미지 생성 +url: /ko/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – 바코드 이미지 생성 + +DataBar Expanded Stacked용 바코드 이미지를 생성할 수 있는 barcode generator C#가 필요하다면, 이 가이드는 전체 과정을 단계별로 안내합니다. 열 및 행 설정을 구성하고, 결과를 PNG로 저장하며, 다른 심볼에도 코드를 적용하는 방법을 배울 수 있습니다. + +프로그램matically 바코드 이미지를 생성하면 수동 작업을 없애고 청구서, 배송 라벨 및 재고 시스템 전반에 걸쳐 일관성을 보장합니다. 이 튜토리얼은 프로젝트 설정부터 전체 소스 코드까지 필요한 모든 것을 다루며, 예제를 즉시 실행할 수 있도록 합니다. + +## 전제 조건 + +* .NET 6.0 이상 설치됨 +* Visual Studio 2022와 같은 IDE (C#를 지원하는 편집기면 모두 사용 가능) +* **Aspose.BarCode for .NET** 라이선스 – 무료 평가판으로 테스트 가능 +* C# 구문에 대한 기본적인 이해 + +위 항목 중 하나라도 없으면, dotnet.microsoft.com에서 .NET SDK를 설치하고 다음과 같이 Aspose.BarCode NuGet 패키지를 가져오세요: + +```bash +dotnet add package Aspose.BarCode +``` + +## 1단계: barcode generator C# 프로젝트 만들기 + +새 콘솔 애플리케이션을 만들고 필요한 `using` 지시문을 추가합니다: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +`BarcodeGenerator` 클래스는 barcode generator C# API의 핵심입니다. 심볼 유형과 인코딩할 텍스트를 받습니다. + +## 2단계: DataBar Expanded Stacked 바코드 생성 및 열 설정 + +첫 번째 예제는 네 개의 열을 가진 바코드를 생성합니다. `Columns` 속성을 조정하면 DataBar Expanded Stacked 심볼의 시각적 밀도가 변경됩니다. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**왜 중요한가:** 열 수는 제한된 공간에 저장할 수 있는 데이터 양에 영향을 줍니다. 4로 설정하면 대부분의 스캐너가 읽을 수 있는 더 넓은 바코드가 생성됩니다. + +## 3단계: 사용자 정의 행 수로 바코드 생성 + +두 번째 예제는 `Rows` 속성을 설정하여 수직 레이아웃을 제어하는 방법을 보여줍니다. 가로 공간이 제한된 경우 더 높은 바코드가 필요할 때 3행 구성이 유용합니다. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**왜 중요한가:** 행을 조정하면 좁은 열에 바코드를 맞추면서 가독성을 유지할 수 있습니다. barcode generator C#는 사양에 맞게 모듈 크기를 자동으로 재계산합니다. + +## 4단계: 전체 실행 가능한 예제 + +아래는 이전 단계들을 결합한 독립 실행형 프로그램입니다. 코드를 `Program.cs`에 복사하고 `YOUR_DIRECTORY`를 기존 폴더 경로로 교체한 뒤 애플리케이션을 실행하세요. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### 예상 출력 + +프로그램을 실행하면 대상 디렉터리에 두 개의 PNG 파일이 생성됩니다: + +* **DatabarCols4.png** – 네 개의 열을 가진 DataBar Expanded Stacked 바코드 +* **DatabarRows3.png** – 동일한 데이터를 3행으로 인코딩한 바코드 + +이미지 뷰어로 파일을 열면 선명하고 스캔 가능한 바코드가 표시되며, 인쇄하거나 PDF에 삽입할 준비가 되어 있습니다. + +## 사용자 정의 크기로 바코드 이미지 생성 방법 + +특정 이미지 크기가 필요하면 `Save` 호출 전에 `ImageHeight`와 `ImageWidth` 속성을 조정하세요: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +크기를 변경해도 인코딩된 데이터에는 영향을 주지 않으며, 시각적 표현만 스케일링됩니다. 이 기법은 고정 레이아웃 제약이 있는 UI 구성 요소에 바코드를 통합할 때 유용합니다. + +## 흔히 발생하는 실수와 전문가 팁 + +* **Path separators:** Windows에서 이스케이프 문자 문제를 피하려면 원시 문자열(`@"C:\Path\file.png"`) 또는 `Path.Combine`을 사용하세요. +* **License enforcement:** 유효한 라이선스가 없으면 생성된 이미지에 워터마크가 표시됩니다. 애플리케이션 초기에 라이선스를 적용하세요: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Encoding limits:** DataBar Expanded Stacked은 최대 74개의 숫자 문자까지 지원합니다. 이 한도를 초과하면 예외가 발생합니다. 생성기 생성 전에 입력 길이를 검증하세요. +* **Performance:** 여러 번 저장할 때 단일 `BarcodeGenerator` 인스턴스를 재사용하면 메모리 할당을 줄일 수 있습니다. 인코딩된 텍스트가 동일한 경우 저장 사이에 `Rows` 또는 `Columns` 속성만 변경하세요. + +## 다음 단계 + +이제 barcode generator C#로 바코드 이미지를 생성할 수 있으니, 다음을 살펴보세요: + +* **Different symbologies** – `EncodeTypes.QR`, `EncodeTypes.Code128`, `EncodeTypes.Pdf417` 등을 시도해 보세요. +* **Color customization** – `Parameters.Barcode.ForeColor`와 `BackColor`를 설정하여 브랜드 색상에 맞추세요. +* **Embedding in PDFs** – 생성된 PNG를 Aspose.PDF와 결합하여 인쇄 가능한 문서를 만들 수 있습니다. + +이러한 확장을 통해 재고, 물류 또는 소매 애플리케이션을 위한 완전한 바코드 솔루션을 구축할 수 있습니다. + +--- + + +## 다음에 배워야 할 내용은? + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료에는 단계별 설명과 함께 완전한 동작 코드 예제가 포함되어 있어 추가 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를 사용한 DataMatrix 바코드(ECC 200) 생성 방법](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/korean/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..1af638ee7 --- /dev/null +++ b/barcode/korean/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-08-03 +description: 'C#에서 바코드 생성기 예제: 너비 설정 방법, 높이 변경 방법, 바코드 이미지를 생성하는 방법을 보여줍니다. 단계별 지침을 + 따르세요.' +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: ko +lastmod: 2026-08-03 +og_description: 바코드 생성기 예제는 X‑차원 너비 설정, 바 높이 변경 및 C#에서 바코드 이미지를 생성하는 방법을 보여줍니다. PNG + 파일을 만들기 위한 단계를 따라 주세요. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: 바코드 생성기 예제 – C# 너비 및 높이 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: C# 바코드 생성기 예제 – 너비와 높이 설정 +url: /ko/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 바코드 생성기 예제 – 너비와 높이 설정 + +C#에서 **barcode generator example**이 필요하다면, 이 가이드는 X‑dimension 너비를 설정하는 방법, 바 높이를 변경하는 방법, 그리고 바코드 이미지 파일을 생성하는 방법을 보여줍니다. 서로 다른 높이를 가진 두 개의 PNG 파일을 생성하는 완전한 실행 가능한 프로그램을 확인할 수 있습니다. + +일반적인 시나리오는 바코드 크기가 스캐너 사양을 충족해야 하는 제품 라벨을 만드는 것입니다. 이 튜토리얼을 마치면 너비와 높이 매개변수를 프로그래밍 방식으로 조정하고 결과를 PNG 이미지로 저장할 수 있게 됩니다. + +## 사전 요구 사항 + +* .NET 6(또는 그 이후 버전)이 설치되어 있어야 합니다 – 코드는 .NET 6 SDK를 대상으로 합니다. +* `EncodeTypes.DatabarOmniDirectional`를 지원하는 바코드 라이브러리. 예제에서는 **Aspose.BarCode for .NET**를 사용하지만, 유사한 속성을 제공하는 모든 라이브러리도 동일하게 작동합니다. +* 프로그램을 컴파일하고 실행할 수 있는 IDE 또는 편집기(Visual Studio, VS Code, Rider). +* PNG 파일이 저장될 디렉터리에 대한 쓰기 권한. + +> **Pro tip:** 프로젝트 루트에 `Barcodes`라는 폴더를 만들고 `Path.Combine`을 사용해 참조하면 절대 경로를 하드코딩하는 것을 피할 수 있습니다. + +## Barcode generator example: 초기화 및 구성 + +첫 번째 단계는 원하는 심볼과 데이터 문자열을 사용하여 `BarcodeGenerator` 인스턴스를 만드는 것입니다. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +`EncodeTypes.DatabarOmniDirectional` 열거형은 Databar Omni‑directional 심볼을 선택하고, GS1 형식의 데이터 문자열 `(01)12345678901231`은 일반적인 GTIN‑14 값을 나타냅니다. 생성기를 한 번 초기화하면 동일한 객체를 여러 이미지에 재사용할 수 있습니다. + +## 너비 (X‑dimension) 설정 방법 + +X‑dimension은 바코드 모듈의 너비를 제어합니다. 이를 2 픽셀로 설정하면 각 좁은 바가 2 픽셀 너비가 되며, 이는 고밀도 인쇄에서 일반적인 요구 사항입니다. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +이것이 중요한 이유: 너비가 너무 작으면 스캐너가 개별 바를 구분하지 못할 수 있고, 너무 크면 바코드가 라벨 공간을 초과할 수 있습니다. 픽셀 값을 프린터 DPI와 목표 라벨 크기에 맞게 조정하세요. + +## 높이 변경 방법 + +바 높이는 바가 얼마나 높게 표시되는지를 결정합니다. 예제에서는 30 픽셀 높이와 60 픽셀 높이의 두 이미지를 생성합니다. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +`BarHeight.Pixels` 속성은 바의 시각적 높이에 직접 영향을 줍니다. 저장 사이에 값을 변경하면 생성기를 다시 만들 필요 없이 동일한 데이터 페이로드에서 여러 변형을 생성할 수 있습니다. + +### 예상 출력 + +프로그램을 실행하면 `Barcodes` 폴더에 두 개의 PNG 파일이 생성됩니다: + +* `DatabarBarHeight30Pixels.png` – 바 높이가 30 픽셀입니다. +* `DatabarBarHeight60Pixels.png` – 바 높이가 60 픽셀입니다. + +두 이미지 모두 동일한 너비(X‑dimension에 의해 결정)이며 동일한 GTIN‑14 데이터를 인코딩합니다. + +![C# 코드로 생성된 서로 다른 높이의 두 바코드 PNG 파일](barcode-example.png "높이 변화를 보여주는 바코드 생성기 예제") + +*위 이미지의 alt 텍스트에는 접근성과 SEO를 위한 주요 키워드가 포함되어 있습니다.* + +## C#에서 바코드 이미지 생성 방법 + +`Save` 메서드는 바코드 데이터를 이미지 파일로 변환합니다. 다른 `BarCodeImageFormat` 열거형 값을 전달하면 JPEG, BMP, SVG와 같은 다른 형식을 선택할 수 있습니다. 예제에서는 무손실 품질을 유지하고 널리 지원되는 PNG를 사용합니다. + +바코드를 PDF나 웹 페이지에 직접 삽입해야 하는 경우, 이미지를 `byte[]` 형태로 가져올 수 있습니다: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +이 방법은 임시 파일이 필요 없게 하며, 고처리량 서비스에 유용합니다. + +## 일반적인 변형 및 예외 상황 + +| 상황 | 조정 | +|-----------|------------| +| **Different symbology** | `EncodeTypes.DatabarOmniDirectional`를 다른 열거형 값(예: `EncodeTypes.Code128`)으로 교체합니다. | +| **Very small labels** | `XDimension.Pixels`를 1 픽셀로 감소시키되, 스캐너 가독성을 확인하세요. | +| **High‑resolution printing** | X‑dimension과 바 높이를 비례적으로 증가시킵니다(예: 너비 4 px, 높이 80 px). | +| **Dynamic data** | 런타임에 데이터 문자열을 전달합니다. 예를 들어 데이터베이스 레코드에서 가져올 수 있습니다. | +| **Batch generation** | 데이터 문자열 컬렉션을 반복하면서 `generator.Text`를 업데이트하고 동일한 `BarcodeGenerator` 인스턴스를 재사용합니다. | + +`ArgumentOutOfRangeException`와 같은 예외가 발생하면, 픽셀 값이 양의 정수인지 그리고 출력 디렉터리가 존재하는지 다시 확인하세요. + +## 전체 소스 코드 요약 + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +코드를 새 콘솔 프로젝트에 복사하고, Aspose.BarCode NuGet 패키지를 복원(`dotnet add package Aspose.BarCode`)한 뒤 `dotnet run`을 실행하세요. 저장된 파일을 확인하는 콘솔 메시지가 표시됩니다. + +## 결론 + +이 **barcode generator example**은 너비 설정, 높이 변경, 그리고 C#에서 바코드 이미지를 생성하는 방법을 보여줍니다. `XDimension.Pixels`와 `BarHeight.Pixels`를 조정하면 바코드의 시각적 크기를 제어할 수 있으며, `Save` 메서드는 결과를 PNG 파일로 저장합니다. 다양한 심볼, 출력 형식 및 데이터 문자열을 실험하여 애플리케이션 요구에 맞추세요. + +**다음 단계** + +* 웹 사용을 위해 다른 이미지 형식(SVG, JPEG)으로 **how to generate barcode**를 탐색하세요. +* ASP.NET Core 엔드포인트에서 PNG를 브라우저에 직접 반환하는 **create barcode image c#**를 학습하세요. +* 이 코드를 PDF 생성 라이브러리와 결합하여 청구서나 배송 라벨에 바코드를 삽입하세요. + +샘플을 자유롭게 수정하고, 결과를 공유하거나 댓글로 질문해 주세요. 즐거운 코딩 되세요! + +## 다음에 배워야 할 내용은? + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료에는 단계별 설명과 함께 완전한 작동 코드 예제가 포함되어 있어 추가 API 기능을 숙달하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [바코드 생성 방법 - 일차원 바코드 유형](/barcode/english/net/one-dimensional-barcode-types/) +- [ITF-14 바코드 사용자 정의를 위한 테두리 설정 방법](/barcode/english/net/itf-14-barcode-customization/) +- [Aspose.BarCode for .NET을 사용한 DataMatrix 바코드(ECC 200) 생성 방법](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/korean/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..7da81f652 --- /dev/null +++ b/barcode/korean/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-08-03 +description: C#에서 바코드 PNG를 생성하고 DataBar 이미지의 종횡비를 변경하는 방법을 배워보세요. 코드와 팁이 포함된 전체 예제를 + 따라해 보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: ko +lastmod: 2026-08-03 +og_description: C#에서 바코드 PNG를 생성하고 DataBar 바코드의 종횡비를 변경하는 방법을 확인하세요. 이 가이드는 바로 실행할 + 수 있는 코드와 실용적인 팁을 제공합니다. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: C#에서 바코드 PNG 만들기 – 종횡비 제어가 포함된 전체 예제 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: C#에서 바코드 PNG 만들기 – 단계별 가이드 +url: /ko/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 바코드 PNG 만들기 – 단계별 가이드 + +C#에서 **바코드 PNG**를 만들어야 한다면, 이 튜토리얼이 정확히 방법을 보여줍니다. 스택형 전방향 DataBar 바코드를 생성하고 PNG 파일로 저장하며, 다양한 스캔 환경에 맞게 **종횡비를 변경하는 방법**을 배웁니다. + +이 가이드는 필요한 패키지, 완전한 실행 가능한 프로그램, 각 설정이 중요한 이유에 대한 설명을 모두 포함합니다. 끝까지 따라오면 종횡비가 15인 PNG 파일 하나와 30인 PNG 파일 하나, 총 두 개의 파일을 테스트 또는 프로덕션에 바로 사용할 수 있게 됩니다. + +## 사전 요구 사항 + +시작하기 전에 다음이 준비되어 있어야 합니다: + +- .NET 6.0 SDK 또는 그 이후 버전이 설치되어 있어야 합니다 +- Visual Studio 2022 (또는 기타 C# IDE) +- **Aspose.BarCode**에 대한 NuGet 참조 (`BarcodeGenerator`를 제공하는 라이브러리) +- PNG 파일이 저장될 디렉터리에 대한 쓰기 권한 + +다음 명령으로 Aspose.BarCode 패키지를 추가할 수 있습니다: + +```bash +dotnet add package Aspose.BarCode +``` + +## 단계 1: 프로젝트 설정 및 네임스페이스 가져오기 + +새 콘솔 애플리케이션을 만들고 바코드 생성 및 파일 I/O에 필요한 네임스페이스를 가져옵니다. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Why this matters:** `Aspose.BarCode.Generation`을 가져오면 `BarcodeGenerator`에 접근할 수 있습니다. 코드를 `Main` 내부에 두면 예제가 독립적이고 실행하기 쉬워집니다. + +## 단계 2: 스택형 전방향 DataBar용 바코드 생성기 만들기 + +`EncodeTypes.DatabarStackedOmniDirectional` 타입과 샘플 GS1‑128 데이터 문자열을 사용해 `BarcodeGenerator`를 인스턴스화합니다. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Why this matters:** 선택한 인코드 타입은 대부분의 최신 스캐너가 읽을 수 있는 고밀도 DataBar를 생성합니다. 데이터 문자열은 제품 식별에 일반적인 GS1 애플리케이션 식별자 (01) 형식을 따릅니다. + +## 단계 3: 픽셀 단위 X‑dimension(모듈 폭) 정의하기 + +모듈 폭을 설정해 바코드 전체 크기를 조절하지만 가독성에는 영향을 주지 않도록 합니다. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Why this matters:** X‑dimension을 2 픽셀로 설정하면 스캐너에 너무 작지도, 라벨 공간에 너무 크지도 않은 바코드가 됩니다. + +## 단계 4: 종횡비 15인 첫 번째 PNG 저장하기 + +DataBar 종횡비를 조정한 뒤 이미지를 PNG 파일로 저장합니다. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Why this matters:** 종횡비는 스택형 DataBar의 높이‑너비 비율을 제어합니다. 비율 15는 가독성과 라벨 높이 사이의 균형을 맞추는 일반적인 기본값입니다. + +## 단계 5: 종횡비를 30으로 변경하고 두 번째 PNG 저장하기 + +같은 생성기 인스턴스를 수정해 더 큰 종횡비를 사용하고 두 번째 이미지를 저장합니다. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Why this matters:** 종횡비를 높이면 바코드가 수직으로 늘어나 저해상도 장치나 좁은 매체에 인쇄된 라벨에서 스캔 신뢰성을 높일 수 있습니다. + +## 예상 출력 + +프로그램을 실행하면 두 개의 PNG 파일이 생성됩니다: + +| 파일 | 종횡비 | 대략적인 크기 (픽셀) | +|------------------------------------|-------|----------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (width × height) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (width × height) | + +두 이미지 모두 GS1 식별자 `(01)12345678901231`을 인코딩한 명확하고 스캔 가능한 DataBar 바코드를 포함합니다. + +## 일반적인 질문 및 엣지 케이스 + +### 다른 시각적 속성을 어떻게 변경하나요? + +`generator.Parameters.Barcode` 객체를 통해 전경색, 배경색 또는 인간이 읽을 수 있는 텍스트를 조정할 수 있습니다. 예시: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### 다른 이미지 형식이 필요하면 어떻게 하나요? + +필요에 따라 `BarCodeImageFormat.Png`를 `Jpeg`, `Bmp`, `Gif` 등으로 교체하면 됩니다. PNG는 무손실 바코드 이미지에 가장 적합한 선택입니다. + +### 종횡비가 스캔 속도에 영향을 미치나요? + +높은 종횡비는 바코드 높이를 증가시켜 짧은 스택형 심볼을 읽기 어려워하는 장치에서 스캔 신뢰성을 높일 수 있습니다. 하지만 지나치게 높은 바코드는 작은 라벨에 들어가지 않을 수 있으니 목표 하드웨어에서 테스트하세요. + +### 루프에서 여러 바코드를 생성할 수 있나요? + +예. 각 데이터 문자열마다 새 `BarcodeGenerator` 인스턴스를 만들거나, 동일 인스턴스를 재사용하면서 `CodeText`와 `DataBar.AspectRatio`만 업데이트하면 됩니다. 이렇게 하면 객체 할당 오버헤드를 줄일 수 있습니다. + +## 전문가 팁 + +- **생성기 재사용**: `CodeText` 또는 `AspectRatio`만 변경하면 객체를 다시 인스턴스화할 필요가 없어 배치 처리 속도가 빨라집니다. +- **출력 검증**: 핸드헬드 스캐너나 모바일 앱을 사용해 생성된 PNG가 올바르게 읽히는지 확인한 뒤 프로덕션에 배포하세요. +- **파일 명명**: 파일 이름에 종횡비를 포함시키면(예시와 같이) 테스트 중 다양한 변형을 쉽게 추적할 수 있습니다. + +## 결론 + +이제 C#에서 **바코드 PNG** 파일을 만드는 방법과 스택형 전방향 DataBar 심볼의 **종횡비를 정확히 변경하는 방법**을 알게 되었습니다. 전체 예제는 초기화, X‑dimension 설정, 종횡비 조정, 이미지 저장을 모두 하나의 실행 가능한 프로그램으로 보여줍니다. + +앞으로 추가 바코드 유형을 탐색하거나 색상을 실험하고, 생성기를 더 큰 보고서나 재고 시스템에 통합할 수 있습니다. 즐거운 코딩 되세요! + +## 다음에 배워야 할 내용 + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 리소스는 단계별 설명과 완전한 코드 예제를 제공하여 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용할 수 있도록 돕습니다. + +- [바코드 PNG 만들기 – DataMatrix 종횡비 – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [.NET용 Aspose.BarCode를 사용하여 사용자 정의 종횡비로 Aztec 바코드 생성 방법](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [.NET용 Aspose.BarCode로 Codablock F 종횡비 맞춤 설정 방법](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/korean/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..3d6d8655b --- /dev/null +++ b/barcode/korean/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-08-03 +description: 이 가이드를 통해 바코드 PNG를 빠르게 만들 수 있습니다. Aspose.BarCode를 사용하여 바코드 이미지를 생성하고 + 플래닛 바코드를 만드는 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: ko +lastmod: 2026-08-03 +og_description: 바코드 PNG를 즉시 생성하세요. 이 튜토리얼에서는 바코드 이미지를 생성하고 Aspose.BarCode를 사용해 플래닛 + 바코드를 만드는 방법을 보여줍니다. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Python에서 바코드 PNG 만들기 – 완전한 프로그래밍 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Python으로 바코드 PNG 만들기 – 단계별 가이드 +url: /ko/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python에서 바코드 PNG 생성 – 단계별 가이드 + +Python 애플리케이션에서 **바코드 PNG** 파일을 생성해야 한다면, 이 튜토리얼이 정확히 어떻게 하는지 보여줍니다. Aspose.BarCode를 사용하여 **바코드 이미지**를 생성하고, 특히 **맞춤형 크기의 Planet 바코드**를 만드는 과정을 단계별로 안내합니다. + +라이브러리 설치, Planet 심볼로지 설정, 크기 매개변수 조정, 고품질 PNG로 저장하는 방법을 배우게 됩니다. 이 가이드는 기본적인 Python 지식과 최신 Python 3 버전(3.8 이상)을 전제로 합니다. 바코드 표준에 대한 사전 경험은 필요하지 않습니다. + +--- + +## Aspose.BarCode로 바코드 PNG 만들기 + +이 섹션에서는 **바코드 PNG**를 만들기 위한 핵심 단계를 제공합니다. 각 단계마다 코드 스니펫, 중요 이유 설명, 즉시 적용 가능한 실용 팁이 포함됩니다. + +### 1. Aspose.BarCode 패키지 설치 + +Aspose는 .NET 코어 엔진을 래핑한 순수 Python 패키지를 제공합니다. `pip`으로 설치합니다: + +```bash +pip install aspose-barcode +``` + +*이 단계가 중요한 이유:* 예제 전반에 사용되는 `BarcodeGenerator` 클래스를 제공하는 패키지입니다. 전역에 설치하면 런타임에 어셈블리를 찾을 수 있습니다. + +### 2. 필요한 클래스 가져오기 + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*팁:* 필요한 심볼만 가져오세요. 이렇게 하면 네임스페이스가 깔끔해지고 모듈 로딩 속도가 빨라집니다. + +### 3. Planet 심볼로지를 위한 바코드 생성기 만들기 + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*이것이 중요한 이유:* `EncodeTypes.Planet`은 엔진에 Planet 바코드 표준을 사용하도록 지시하고, 두 번째 인자는 인코딩할 데이터를 제공합니다. 심볼로지를 `EncodeTypes.Code128` 등으로 바꾸면 전혀 다른 시각적 패턴이 생성됩니다. + +### 4. X 차원(모듈 너비)을 픽셀 단위로 설정 + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*설명:* X 차원은 좁은 바의 너비를 제어합니다. 4 픽셀 값은 대부분의 장치에서 스캔 가능하면서도 적당히 촘촘한 바코드를 만들어 줍니다. + +### 5. 수동 바 높이를 픽셀 단위로 정의 + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*조정이 필요한 경우:* 일부 소매 프린터는 신뢰성 있는 스캔을 위해 더 높은 바가 필요합니다. 기본 높이는 보통 50 px이며, 100 px로 늘리면 파일 크기를 크게 늘리지 않으면서 가독성이 향상됩니다. + +### 6. 생성된 바코드를 PNG 이미지로 저장 + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*결과:* **PlanetBarHeight100.png**라는 PNG 파일이 `output` 폴더에 생성됩니다. PNG는 무손실이므로 인쇄와 웹 페이지 삽입에 이상적입니다. + +### 7. 출력 확인 (선택 사항) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*팁:* 이미지를 확인하면 설정한 차원과 일치하는지 확인할 수 있습니다. 바코드가 왜곡되었다면 X 차원이나 바 높이 설정을 다시 검토하세요. + +--- + +## PNG 형식으로 바코드 이미지 생성 (대체 설정) + +다른 이미지 형식이 필요하거나 나중에 PDF에 바코드를 삽입하려면 `BarCodeImageFormat` 열거형을 변경할 수 있습니다: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*이것이 중요한 이유:* PNG는 모든 픽셀을 보존하므로 고대비 바코드에 필수적입니다. JPEG은 압축 아티팩트를 발생시켜 스캔에 방해가 될 수 있고, BMP는 오래된 도구와의 호환성을 제공합니다. + +--- + +## 맞춤 색상으로 Planet 바코드 생성 (고급) + +크기 외에도 전경색과 배경색을 사용자 정의할 수 있습니다: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*실용 팁:* 어두운 색을 밝은 색 배경에 사용하는 고대비 색 조합이 스캐너 신뢰성을 최대로 높입니다. 전경과 배경에 비슷한 색조를 사용하지 마세요. + +--- + +## 흔히 발생하는 문제와 해결 방법 + +| 증상 | 원인 | 해결 방법 | +|------|------|-----------| +| 바코드가 스캔되지 않음 | X 차원이 너무 작음 (≤ 2 px) | `x_dimension.pixels`를 최소 3 px 이상으로 늘리세요 | +| 이미지가 흐릿함 | PNG가 낮은 DPI로 저장됨 | `barcode_generator.save(..., BarCodeImageFormat.Png, 300)`와 같이 300 DPI를 지정하세요 (지원되는 경우) | +| `ImportError` 예외 | Aspose.BarCode가 설치되지 않음 | 스크립트와 동일한 환경에서 `pip install aspose-barcode` 실행 | +| 잘못된 심볼로지 사용 | `EncodeTypes.Code128` 대신 `EncodeTypes.Planet` 사용 | 생성기 생성 시 `EncodeTypes.Planet`으로 교체하세요 | + +--- + +## 전체 솔루션 요약 + +아래는 **바코드 PNG**를 처음부터 끝까지 **생성**하는 전체 실행 가능한 스크립트입니다: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +이 스크립트를 실행하면 선명한 **Planet 바코드 PNG**가 생성되며, HTML에 삽입하거나 이메일에 첨부하거나 제품 라벨에 인쇄할 수 있습니다. + +--- + +## 다음 단계 및 관련 주제 + +* **Flask 또는 Django와 통합** – 웹 엔드포인트에서 바로 생성된 PNG를 제공합니다. +* **배치 생성** – 제품 ID 리스트를 순회하면서 바코드 PNG 파일을 폴더에 대량 생성합니다. +* **PDF 생성과 결합** – `aspose-pdf`를 사용해 PNG를 인보이스나 운송 라벨에 삽입합니다. +* **다른 심볼로지 탐색** – `EncodeTypes.Planet`을 `EncodeTypes.QR`, `EncodeTypes.DataMatrix`, `EncodeTypes.Code128` 등으로 교체해 다양한 비즈니스 요구에 대응합니다. + +위 단계들을 마스터하면 **프로그램matically 바코드 이미지 생성** 방법을 알게 되며, Aspose.BarCode가 지원하는 모든 바코드 표준에 적용할 수 있습니다. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/korean/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..47c839228 --- /dev/null +++ b/barcode/korean/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-08-03 +description: C#에서 우편 바코드 이미지를 빠르게 생성하세요. 우편 바코드 생성 방법, 바코드 크기 설정, 그리고 Planet 바코드 생성 + 방법을 배워보세요. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: ko +lastmod: 2026-08-03 +og_description: C#로 우편 바코드 이미지를 만드는 완전한 튜토리얼; 바코드 크기 설정 방법, Planet 바코드 생성 및 RM4SCC + 바코드 제작을 배워보세요. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: C#에서 우편 바코드 이미지 만들기 – 전체 프로그래밍 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: C#에서 우편 바코드 이미지 만들기 – 단계별 가이드 +url: /ko/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 우편 바코드 이미지 만들기 – 단계별 가이드 + +C#에서 **우편 바코드 이미지 만들기**가 필요하다면, 이 가이드는 정확한 방법을 보여줍니다. 우리는 **우편 바코드 생성 방법**, **바코드 크기 설정 방법**, 그리고 일반적인 우편 표준에 대한 **플래닛 바코드 생성**을 다룰 것입니다. + +두 개의 사용 준비가 된 PNG 파일—하나는 Planet 바코드, 다른 하나는 RM4SCC 바코드—각각 높이 100 px 로 완성됩니다. 추가 도구는 Aspose.BarCode for .NET 라이브러리 외에 필요하지 않습니다. + +## 사전 요구 사항 + +* .NET 6 SDK 이상 (코드는 .NET Framework 4.7+에서도 작동합니다) +* Visual Studio 2022 또는 any C# IDE +* NuGet 패키지 **Aspose.BarCode** (`BarcodeGenerator`를 제공하는 라이브러리) + +## 1단계: 바코드 라이브러리 설치 + +프로젝트 폴더에서 터미널을 열고 다음을 실행합니다: + +```bash +dotnet add package Aspose.BarCode +``` + +이 패키지는 `Aspose.BarCode` 네임스페이스를 추가하며, 여기에는 우편 바코드에 필요한 `BarcodeGenerator`와 `EncodeTypes` 열거형이 포함됩니다. + +## 2단계: 출력 폴더 정의 + +신뢰할 수 있는 출력 경로를 생성하면 폴더가 없을 때 발생하는 런타임 오류를 방지할 수 있습니다. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*왜 중요한가*: `Directory.CreateDirectory`는 멱등 연산으로, 폴더가 이미 존재하지 않을 때만 생성하여 이후 실행 시 예외가 발생하지 않게 합니다. + +## 3단계: 일반 바코드 크기 구성 + +X‑dimension(단일 바의 너비)과 전체 바 높이를 설정하면 생성된 이미지의 시각적 크기를 제어할 수 있습니다. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**바코드 크기 설정 방법**: `Parameters.Barcode.XDimension.Pixels` 속성은 좁은 바의 너비를 정의하고, `Parameters.Barcode.BarHeight.Pixels`는 전체 높이를 정의합니다. 이 값을 조정하여 메일링 서비스의 사양에 맞추세요. + +## 4단계: Planet 바코드 생성 + +Planet은 영국에서 널리 사용되는 우편 바코드입니다. 아래 코드는 높이 100 px인 Planet 바코드를 생성하고 PNG로 저장합니다. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**왜 작동하는가**: `EncodeTypes.Planet`는 생성기에 Planet 심볼을 사용하도록 지시합니다. `Save` 메서드는 지정된 경로에 PNG 파일을 기록하며, 앞서 설정한 크기를 유지합니다. + +## 5단계: RM4SCC 바코드 생성 + +RM4SCC는 네덜란드 우편 바코드 표준입니다. 아래 코드는 Planet 예제를 그대로 따라하며, 동일한 크기로 다른 유형의 **우편 바코드 생성 방법**을 보여줍니다. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +두 PNG 파일은 이제 `Barcodes` 폴더에 저장됩니다. 파일을 열면 인쇄하거나 문서에 삽입할 준비가 된 깔끔한 100 px 높이 바코드를 확인할 수 있습니다. + +## 전체 소스 코드 + +아래는 Planet 및 RM4SCC 표준에 대한 **우편 바코드 이미지 만들기** 파일을 생성하는 완전하고 실행 가능한 프로그램입니다. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### 예상 출력 + +프로그램을 실행하면 파일 경로를 출력하고 두 개의 PNG 파일을 생성합니다: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +각 이미지는 높이 100 px이며, 좁은 바 너비가 4 픽셀로, 우리가 설정한 크기와 일치합니다. + +## 실용적인 팁 및 일반적인 함정 + +* **폴더 권한** – 프로그램이 제한된 계정으로 실행될 경우, 대상 폴더가 쓰기 가능한지 확인하세요. +* **다른 크기** – 더 높은 바코드를 만들려면 `barHeightPixels`를 늘리세요. 더 세밀한 해상도를 원한다면 `xDimensionPixels`를 낮추되, 렌더링 결함을 방지하기 위해 2 이상으로 유지하세요. +* **다른 우편 심볼** – Aspose.BarCode는 `EncodeTypes.Postnet` 및 `EncodeTypes.AustralianPost`도 지원합니다. `EncodeTypes` 값을 교체하고 동일한 차원 로직을 유지하세요. +* **이미지 포맷** – 무손실 품질이 필요 없을 때는 파일 크기를 줄이기 위해 `BarCodeImageFormat.Jpeg`를 사용하세요. + +## 결론 + +이제 차원을 구성하고 적절한 심볼을 선택한 뒤 PNG로 저장하여 C#에서 **우편 바코드 이미지 만들기** 파일을 생성하는 방법을 알게 되었습니다. 이 튜토리얼에서는 **우편 바코드 생성 방법**을 다루고, **플래닛 바코드 생성**을 시연했으며, 일관된 출력을 위한 **바코드 크기 설정 방법**을 설명했습니다. + +다음으로 **바코드 색상 맞춤**, **사람이 읽을 수 있는 텍스트** 추가, 혹은 이미지를 PDF 청구서에 통합하는 방법을 살펴보세요. 동일한 패턴은 Aspose.BarCode가 지원하는 다른 모든 바코드 유형에도 적용되며, 이 솔루션을 전체 우편 자동화 워크플로우로 확장할 수 있습니다. + +## 다음에 배워야 할 내용은? + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료에는 단계별 설명과 함께 완전한 작동 코드 예제가 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [바코드 생성 방법 - 일차원 바코드 유형](/barcode/english/net/one-dimensional-barcode-types/) +- [Aspose.BarCode for .NET을 사용하여 사용자 지정 종횡비로 Aztec 바코드 생성](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [barcode java 생성 방법 – Aspose와 함께하는 Australia Post 바코드](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/korean/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..df0209334 --- /dev/null +++ b/barcode/korean/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-08-03 +description: 'C#에서 바코드를 저장하는 방법: 단계별 바코드 생성기 예제. Planet 바코드 생성, 크기 설정 및 PNG 이미지 내보내기를 + 배워보세요.' +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: ko +lastmod: 2026-08-03 +og_description: 바코드 생성기 예제를 사용하여 C#에서 바코드를 저장하는 방법. 이 튜토리얼에서는 Planet 바코드를 생성하고 X‑디멘션을 + 설정하며 PNG 파일로 내보내는 방법을 보여줍니다. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: C#에서 바코드 저장 방법 – 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: C#에서 바코드 저장 방법 – 완전한 바코드 생성 가이드 +url: /ko/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 바코드 저장하기 – 완전한 바코드 생성기 가이드 + +C#에서 바코드 이미지를 저장하는 것은 청구서, 배송 라벨 또는 재고 태그에 우편 바코드를 삽입해야 할 때 흔히 요구되는 작업입니다. 이 가이드는 실용적인 **c# barcode generator** 워크플로우를 단계별로 안내하며, Planet 바코드 생성부터 채워진 막대와 비어있는 막대 PNG 파일을 내보내는 과정을 다룹니다. + +바의 너비 설정, 채워진 막대 토글, 출력 폴더를 안정적으로 처리하는 방법을 배우게 됩니다. 튜토리얼이 끝날 때쯤에는 어떤 .NET 프로젝트에도 복사해 사용할 수 있는 완전한 **barcode generator example**을 얻게 됩니다. + +## 필요 사항 + +- .NET 6.0 SDK 또는 그 이후 버전 (예제는 .NET Core 및 .NET Framework에서도 작동합니다) +- Visual Studio 2022 또는 C# 호환 IDE +- **Aspose.BarCode** NuGet 패키지(`EncodeTypes.Planet`을 지원하는 다른 라이브러리도 가능). 다음 명령으로 설치합니다: + +```bash +dotnet add package Aspose.BarCode +``` + +이 라이브러리는 본 튜토리얼 전반에 사용되는 `BarcodeGenerator` 클래스를 제공합니다. + +## 개발 환경 설정 + +새 콘솔 프로젝트를 만들고 필요한 네임스페이스를 추가합니다: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +`System.IO` 네임스페이스는 `Directory.CreateDirectory`를 제공하며, 파일을 쓰기 전에 출력 폴더가 존재하도록 보장합니다. + +## C# 바코드 생성기로 바코드 이미지 저장하기 + +솔루션의 핵심은 **Planet barcode**를 설정하고 이미지를 디스크에 저장하는 몇 단계로 구성됩니다. 다음 섹션에서는 이 과정을 관리하기 쉬운 부분으로 나눕니다. + +### 단계 1: 출력 폴더 정의 + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Why?** +경로를 하드코딩하면 폴더가 존재하지 않는 머신에서 `DirectoryNotFoundException`이 발생할 수 있습니다. `CreateDirectory`는 멱등성을 가지며, 폴더가 없을 때만 생성하므로 반복 실행에도 안전합니다. + +### 단계 2: Planet 바코드 생성기 만들기 (채워진 막대) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Why?** +`EncodeTypes.Planet`는 라이브러리에게 우편용 Planet 바코드를 생성하도록 지시합니다. 이 바코드는 우편 서비스에서 널리 사용됩니다. 문자열 `"123456"`은 샘플 페이로드이며, 비즈니스 로직에 필요한 숫자 데이터로 교체하면 됩니다. + +### 단계 3: 바 너비 (X‑dimension) 설정 및 기본 채워진 막대 유지 + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Why?** +X‑dimension은 각 막대의 물리적 너비를 제어합니다. `4` 픽셀 값은 표준 300 dpi 프린터에서 읽을 수 있는 바코드를 생성합니다. `FilledBars`를 `true`(기본값)로 두면 고전적인 실선 막대 모양이 만들어집니다. + +### 단계 4: 채워진 막대 바코드 이미지 저장 + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Why?** +PNG로 저장하면 무손실 이미지 품질이 유지되어 스캔 정확도에 중요합니다. `Save` 메서드는 이미지 파일을 자동으로 생성하므로 전체 경로와 원하는 포맷만 지정하면 됩니다. + +### 단계 5: 비어있는 막대 버전을 위한 두 번째 생성기 만들기 + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +새 인스턴스를 만들면 비어있는 막대 버전에 대한 변경 사항이 이미 저장된 채워진 막대 이미지에 영향을 주지 않도록 보장합니다. + +### 단계 6: 동일한 X‑dimension을 유지하면서 채워진 막대 비활성화 + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Why?** +`FilledBars = false`로 설정하면 각 막대의 외곽선만 표시된 바코드가 생성되며, 이는 일부 우편 표준에서 시각적 검증을 위해 요구됩니다. + +### 단계 7: 비어있는 막대 바코드 이미지 저장 + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +이제 채워진 막대와 비어있는 막대 각각에 대한 두 개의 PNG 파일이 생성되어 PDF, HTML 이메일 또는 인쇄 라벨에 포함시킬 수 있습니다. + +## 전체 실행 가능한 프로그램 + +아래는 `Program.cs`에 복사해 넣을 수 있는 전체 코드입니다. (Aspose.BarCode 패키지가 설치되어 있다고 가정하면) 수정 없이 컴파일 및 실행됩니다. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### 예상 출력 + +프로그램을 실행하면 다음과 유사한 두 줄이 출력됩니다: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +`Barcodes` 폴더를 열면 두 개의 PNG 파일이 보입니다. 두 이미지 모두 모든 이미지 뷰어에서 열 수 있으며 문서에 직접 삽입할 수 있습니다. + +![바코드 저장 예시](barcode-example.png){: .align-center alt="바코드 저장 예시"} + +## 일반적인 변형 및 엣지 케이스 + +| Scenario | Adjustment | +|----------|------------| +| **다른 이미지 포맷** | `BarCodeImageFormat.Png`를 필요에 따라 `Jpeg`, `Gif`, 또는 `Bmp`로 변경합니다. | +| **맞춤 출력 크기** | 특정 픽셀 크기를 강제하려면 `filled.Parameters.Image.Width`와 `Height`를 사용합니다. | +| **동적 데이터** | 정적 `"123456"`을 주문 번호, 추적 ID 등을 보관하는 변수로 교체합니다. | +| **존재하지 않는 폴더** | `Directory.CreateDirectory`가 이미 누락된 디렉터리를 처리하므로 추가 코드가 필요 없습니다. | +| **고해상도 인쇄** | 600 dpi 프린터용으로 `XDimension.Pixels`를 6–8로 늘리되, 스캐너 호환성을 확인하세요. | + +**Pro tip:** 루프에서 다수의 바코드를 생성해야 할 경우, 단일 `BarcodeGenerator` 인스턴스를 재사용하고 각 `Save` 전에 `CodeText` 속성만 변경하세요. 이렇게 하면 객체 할당 오버헤드를 줄일 수 있습니다. + +## 다른 표준에 대한 바코드 생성 방법 + +같은 패턴이 `Code128`, `QR`, `DataMatrix`와 같은 다른 `EncodeTypes`에도 적용됩니다. 원하는 타입으로 `EncodeTypes.Planet`을 교체하고 타입별 매개변수(예: `QRCodeVersion`)를 조정하면 됩니다. + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 주제를 다룹니다. 각 자료는 단계별 설명과 함께 완전한 동작 코드 예제를 제공하여 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하도록 돕습니다. + +- [Aspose.BarCode를 사용한 DataMatrix C40으로 PNG 저장 방법](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Aspose.BarCode for .NET으로 DataMatrix 바코드 (ECC 200) 생성 방법](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Aspose.BarCode를 사용한 바코드 생성 – Code 39 구성](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/polish/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..a0cd9b95e --- /dev/null +++ b/barcode/polish/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-08-03 +description: Samouczek generatora kodów kreskowych w C# pokazujący, jak utworzyć kod + kreskowy Planet przy użyciu Aspose.BarCode, ustawić wymiar X i zapisać jako obrazy + PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: pl +lastmod: 2026-08-03 +og_description: Samouczek generatora kodów kreskowych w C# prowadzi Cię przez tworzenie + kodu kreskowego Planet, regulację wymiaru X oraz zapisywanie jako PNG przy użyciu + Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Generator kodów kreskowych C# – twórz kod Planet krok po kroku +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Generator kodów kreskowych C# – tworzenie kodu Planet i przykład RM4SCC +url: /pl/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generator kodów kreskowych C# – tworzenie kodu Planet i przykład RM4SCC + +Jeśli potrzebujesz **generatora kodów kreskowych C#**, który może generować symbole specyficzne dla poczty, ten przewodnik pokaże Ci dokładnie, jak **tworzyć obrazy kodu Planet** przy użyciu Aspose.BarCode. Zobaczysz, jak skonfigurować wymiar X, wygenerować pasujący kod RM4SCC i zapisać oba jako pliki PNG — wszystko w kilku zwięzłych krokach. + +Poradnik obejmuje wszystko, co potrzebne do uruchomienia kodu na .NET 6 lub nowszym, wyjaśnia, dlaczego każde ustawienie ma znaczenie, oraz wskazuje typowe pułapki, takie jak nieprawidłowa szerokość modułu czy brak uprawnień do katalogu. Po zakończeniu będziesz mieć dwa gotowe do druku obrazy kodów kreskowych, które spełniają standardy Planet i RM4SCC. + +## Wymagania wstępne + +* .NET 6 SDK (lub dowolna wersja .NET obsługiwana przez Aspose.BarCode) +* Visual Studio 2022 lub dowolne IDE C#, które preferujesz +* Odwołanie NuGet do **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Uprawnienie do zapisu w folderze, w którym planujesz przechowywać pliki PNG + +Nie są wymagane żadne dodatkowe usługi zewnętrzne; biblioteka obsługuje całe kodowanie lokalnie. + +## Krok 1: Inicjalizacja obiektu generatora kodów kreskowych C# + +Pierwszym zadaniem jest utworzenie instancji `BarcodeGenerator`. Konstruktor przyjmuje symbologię kodu kreskowego (`EncodeTypes.Planet`) oraz dane do zakodowania. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Dlaczego ten krok?* +`BarcodeGenerator` jest punktem wejścia dla każdego generowanego kodu kreskowego. Wybranie `EncodeTypes.Planet` informuje bibliotekę, aby stosowała specyfikację ISO/IEC 24723 używaną przez wiele usług pocztowych. + +## Krok 2: Ustawienie wymiaru X (szerokości modułu) dla kodu Planet + +Wymiar X definiuje szerokość pojedynczego modułu kodu kreskowego (najmniejszej kreski lub przerwy). Wartość **4 piksele** dobrze sprawdza się w większości drukarek etykiet. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Dlaczego to ważne* +Jeśli moduł jest zbyt wąski, kod kreskowy może stać się nieczytelny; jeśli jest zbyt szeroki, rozmiar etykiety rośnie niepotrzebnie. Dostosowanie `Pixels` pozwala precyzyjnie dopasować kod kreskowy do rozdzielczości Twojej drukarki. + +## Krok 3: Zapisanie kodu Planet jako obrazu PNG + +Aspose.BarCode automatycznie oblicza wysokość kodu kreskowego na podstawie wybranej symbologii, więc musisz jedynie podać ścieżkę pliku i format. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Wskazówka* +Zastąp `YOUR_DIRECTORY` ścieżką absolutną lub względną, która istnieje na Twoim komputerze. Jeśli katalog nie istnieje, metoda `Save` zgłasza `DirectoryNotFoundException`. + +**Oczekiwany wynik** – plik PNG, który wygląda podobnie do ilustracji poniżej (rzeczywisty obraz nie jest tutaj wyświetlany, ale zobaczysz klasyczny kod Planet z ładunkiem numerycznym `123456`). + +## Krok 4: Inicjalizacja drugiego generatora dla kodu RM4SCC + +Wiele systemów pocztowych wymaga zarówno symboli Planet, jak i RM4SCC na tej samej przesyłce. Utwórz nową instancję `BarcodeGenerator` dla symbologii RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Dlaczego osobna instancja?* +Każda symbologia ma własny zestaw parametrów. Ponowne użycie tego samego generatora może nieumyślnie przenieść ustawienia (takie jak wymiar X), które nie są optymalne dla drugiego kodu kreskowego. + +## Krok 5: Konfiguracja wymiaru X dla kodu RM4SCC + +RM4SCC również respektuje ustawienie wymiaru X, więc stosujemy tę samą szerokość w pikselach dla spójności wizualnej. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +Jeśli potrzebujesz wyższego kodu kreskowego (np. dla większych etykiet), możesz również ustawić `Height.Pixels`. Pozostawienie go nieustawionego pozwala bibliotece automatycznie obliczyć idealną wysokość. + +## Krok 6: Zapisanie kodu RM4SCC jako obrazu PNG + +Na koniec zapisz kod RM4SCC na dysku. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Masz teraz dwa pliki PNG — `PostalPlanetBarHeightNone.png` i `PostalRM4SCCBarHeightNone.png` — które możesz osadzić w etykietach pocztowych, wydrukować na kopertach lub wysłać do zewnętrznej usługi drukowania. + +## Opcjonalnie: Dostosowanie wysokości lub użycie innych formatów obrazu + +Jeśli Twój przepływ pracy wymaga określonej wysokości kodu kreskowego lub innego formatu obrazu (np. JPEG lub BMP), możesz zmodyfikować parametry przed wywołaniem `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Przypadek brzegowy** – Gdy ustawiasz niestandardową wysokość, upewnij się, że wartość spełnia minimalną wysokość wymaganą przez standard ISO; w przeciwnym razie kod kreskowy może nie przejść walidacji. + +## Typowe pułapki i jak ich unikać + +| Pułapka | Dlaczego się pojawia | Rozwiązanie | +|---------|----------------------|-------------| +| `DirectoryNotFoundException` | Docelowy folder nie istnieje lub jest błędnie zapisany. | Utwórz najpierw folder lub użyj `Path.Combine` z `Environment.CurrentDirectory`. | +| Kod kreskowy nieczytelny na drukarkach o niskiej rozdzielczości | Wymiar X jest zbyt mały w stosunku do DPI drukarki. | Zwiększ `XDimension.Pixels` do 5‑6 dla drukarek 203 dpi lub przetestuj na próbnej etykiecie. | +| Użyto niewłaściwej symbologii | Przekazanie `EncodeTypes.Code128` zamiast `EncodeTypes.Planet`. | Sprawdź ponownie, czy wartość enum `EncodeTypes` odpowiada wymaganemu standardowi pocztowemu. | +| Odwołanie null do `Parameters` | Używanie starszej wersji Aspose.BarCode, w której API się różni. | Uaktualnij do najnowszego pakietu NuGet (v23.12 lub nowszy). | + +## Pełny przykład do uruchomienia + +Poniżej znajduje się kompletny program, który możesz skopiować, wkleić i uruchomić. Zawiera instrukcje `using`, obsługę błędów oraz komentarze wyjaśniające każdą linię. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Uruchomienie programu tworzy folder `Barcodes` obok pliku wykonywalnego i umieszcza w nim dwa pliki PNG. Otwórz je dowolnym przeglądarką obrazów, aby zweryfikować wynik. + +## Podsumowanie + +Masz teraz rozwiązanie **generatora kodów kreskowych C#**, które może **tworzyć obrazy kodu Planet**, dostosowywać wymiar X dla optymalnego drukowania oraz generować pasujący kod RM4SCC — wszystko przy użyciu kilku linii kodu. Podejście działa z .NET 6+, wymaga jedynie pakietu NuGet Aspose.BarCode i może być rozszerzone na inne symbologie, takie jak Code128, QR czy DataMatrix, poprzez zamianę wartości `EncodeTypes`. + +### Co dalej? + +* Eksperymentuj z różnymi wartościami `XDimension.Pixels`, aby dopasować je do DPI Twojej drukarki. +* Generuj kody kreskowe w innych formatach (PDF, SVG), zmieniając enum `BarCodeImageFormat`. +* Połącz dwa pliki PNG w jedną etykietę przy użyciu biblioteki graficznej, takiej jak **SkiaSharp**. +* Zbadaj pełne API Aspose.BarCode pod kątem zaawansowanych funkcji, takich jak walidacja sumy kontrolnej czy własne czcionki. + +Śmiało dostosuj kod do przetwarzania wsadowego lub zintegrować go z usługą webową ASP.NET Core, która zwraca obrazy kodów kreskowych na żądanie. Szczęśliwego kodowania! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki 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. + +- [Utwórz kod kreskowy PNG – Współczynnik proporcji DataMatrix – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Jak zapisać PNG przy użyciu DataMatrix C40 z Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [samouczek generatora kodów kreskowych c# – Dostosuj współczynniki proporcji kodu 16K z Aspose.BarCode dla .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/polish/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..ad327ac5f --- /dev/null +++ b/barcode/polish/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-08-03 +description: Samouczek generatora kodów kreskowych w C# pokazuje, jak wygenerować + obraz kodu kreskowego przy użyciu Aspose.BarCode, ustawić kolumny i wiersze oraz + zapisać pliki PNG dla DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: pl +lastmod: 2026-08-03 +og_description: Samouczek generatora kodów kreskowych w C# wyjaśnia, jak generować + obraz kodu kreskowego przy użyciu Aspose.BarCode, konfigurować kolumny i wiersze + DataBar Expanded Stacked oraz zapisywać pliki PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Generator kodów kreskowych C# – przewodnik krok po kroku generowania obrazu + kodu kreskowego +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Generator kodów kreskowych C# – generuj obraz kodu kreskowego +url: /pl/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generator kodów kreskowych C# – generowanie obrazu kodu kreskowego + +Jeśli potrzebujesz generatora kodów kreskowych C#, który potrafi generować obraz kodu kreskowego dla DataBar Expanded Stacked, ten przewodnik poprowadzi Cię przez cały proces. Dowiesz się, jak skonfigurować ustawienia kolumn i wierszy, zapisać wynik jako PNG oraz dostosować kod do innych symbologii. + +Programowe generowanie obrazów kodów kreskowych eliminuje ręczne kroki i zapewnia spójność w fakturach, etykietach wysyłkowych i systemach magazynowych. Ten tutorial obejmuje wszystko, czego potrzebujesz – od konfiguracji projektu po pełny kod źródłowy, abyś mógł od razu uruchomić przykład. + +## Wymagania wstępne + +Zanim rozpoczniesz, upewnij się, że masz: + +* .NET 6.0 lub nowszy zainstalowany +* IDE, takie jak Visual Studio 2022 (dowolny edytor obsługujący C#) +* Licencję na **Aspose.BarCode for .NET** – darmowa wersja ewaluacyjna wystarczy do testów +* Podstawową znajomość składni C# + +Jeśli którekolwiek z tych elementów brakuje, zainstaluj .NET SDK ze strony dotnet.microsoft.com i pobierz pakiet Aspose.BarCode NuGet przy pomocy: + +```bash +dotnet add package Aspose.BarCode +``` + +## Krok 1: Utwórz projekt generatora kodów kreskowych C# + +Utwórz nową aplikację konsolową i dodaj wymagane dyrektywy `using`: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +Klasa `BarcodeGenerator` jest rdzeniem API generatora kodów kreskowych C#. Otrzymuje ona typ symbologii oraz tekst do zakodowania. + +## Krok 2: Wygeneruj kod DataBar Expanded Stacked i ustaw kolumny + +Pierwszy przykład tworzy kod kreskowy z czterema kolumnami. Zmiana właściwości `Columns` wpływa na gęstość wizualną symbologii DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Dlaczego to ważne:** Liczba kolumn wpływa na ilość danych, które można przechować w kompaktowej przestrzeni. Ustawienie jej na 4 tworzy szerszy kod kreskowy, który pozostaje czytelny dla większości skanerów. + +## Krok 3: Wygeneruj kod kreskowy z niestandardową liczbą wierszy + +Drugi przykład pokazuje, jak kontrolować układ pionowy, ustawiając właściwość `Rows`. Konfiguracja trzech wierszy jest przydatna, gdy potrzebny jest wyższy kod kreskowy przy ograniczonej przestrzeni poziomej. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Dlaczego to ważne:** Dostosowanie liczby wierszy pozwala zmieścić kod kreskowy w wąskiej kolumnie, zachowując czytelność. Generator kodów kreskowych C# automatycznie przelicza rozmiar modułu, aby spełnić specyfikację. + +## Krok 4: Pełny, gotowy do uruchomienia przykład + +Poniżej znajduje się samodzielny program, który łączy poprzednie kroki. Skopiuj kod do pliku `Program.cs`, zamień `YOUR_DIRECTORY` na istniejącą ścieżkę folderu i uruchom aplikację. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Oczekiwany wynik + +Po uruchomieniu programu w docelowym katalogu pojawią się dwa pliki PNG: + +* **DatabarCols4.png** – kod DataBar Expanded Stacked z czterema kolumnami +* **DatabarRows3.png** – te same dane zakodowane w trzech wierszach + +Otwórz obrazy w dowolnym przeglądarce zdjęć; wyświetlają one ostre, skanowalne kody gotowe do druku lub osadzenia w plikach PDF. + +## Jak wygenerować obraz kodu kreskowego o niestandardowych wymiarach + +Jeśli potrzebujesz konkretnego rozmiaru obrazu, dostosuj właściwości `ImageHeight` i `ImageWidth` przed wywołaniem `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Zmiana wymiarów nie wpływa na zakodowane dane; jedynie skaluje ich wizualną reprezentację. Technika ta jest przydatna przy integracji kodów kreskowych w komponentach UI o stałych ograniczeniach układu. + +## Typowe pułapki i wskazówki profesjonalistów + +* **Separatory ścieżek:** Używaj łańcuchów dosłownych (`@"C:\Path\file.png"`) lub `Path.Combine`, aby uniknąć problemów ze znakami ucieczki w systemie Windows. +* **Wymuszanie licencji:** Bez ważnej licencji wygenerowane obrazy zawierają znak wodny. Zastosuj licencję wcześnie w aplikacji: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Limity kodowania:** DataBar Expanded Stacked obsługuje maksymalnie 74 znaki numeryczne. Przekroczenie tego limitu powoduje wyjątek. Zweryfikuj długość wejścia przed utworzeniem generatora. +* **Wydajność:** Ponowne użycie jednej instancji `BarcodeGenerator` do wielu zapisów zmniejsza alokację pamięci. Zmieniaj właściwości `Rows` lub `Columns` między zapisami tylko wtedy, gdy zakodowany tekst pozostaje ten sam. + +## Kolejne kroki + +Teraz, gdy potrafisz generować obrazy kodów kreskowych przy użyciu generatora kodów kreskowych C#, rozważ dalsze eksploracje: + +* **Różne symbologie** – wypróbuj `EncodeTypes.QR`, `EncodeTypes.Code128` lub `EncodeTypes.Pdf417`. +* **Dostosowanie kolorów** – ustaw `Parameters.Barcode.ForeColor` i `BackColor`, aby dopasować je do identyfikacji wizualnej marki. +* **Osadzanie w PDF** – połącz wygenerowane PNG z Aspose.PDF, aby tworzyć dokumenty gotowe do druku. + +Te rozszerzenia pozwalają zbudować w pełni funkcjonalne rozwiązanie kodów kreskowych dla zastosowań w magazynach, logistyce lub handlu detalicznym. + +--- + + +## Co powinieneś nauczyć się dalej? + + +Poniższe tutoriale 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 wraz z wyjaśnieniami 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 Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/polish/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..5871726ce --- /dev/null +++ b/barcode/polish/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-08-03 +description: Przykład generatora kodów kreskowych w C# pokazujący, jak ustawić szerokość, + jak zmienić wysokość i jak wygenerować obraz kodu kreskowego. Postępuj zgodnie z + instrukcjami krok po kroku. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: pl +lastmod: 2026-08-03 +og_description: Przykład generatora kodów kreskowych demonstruje ustawianie szerokości + wymiaru X, zmianę wysokości kreski oraz generowanie obrazu kodu kreskowego w C#. + Postępuj zgodnie z krokami, aby utworzyć pliki PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Przykład generatora kodów kreskowych – przewodnik po szerokości i wysokości + w C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Przykład generatora kodów kreskowych w C# – ustaw szerokość i wysokość +url: /pl/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Przykład generatora kodów kreskowych w C# – ustaw szerokość i wysokość + +Jeśli potrzebujesz **przykładu generatora kodów kreskowych** w C#, ten przewodnik pokaże Ci, jak ustawić szerokość wymiaru X, jak zmienić wysokość pasków oraz jak wygenerować plik obrazu kodu kreskowego. Zobaczysz kompletny, działający program, który tworzy dwa pliki PNG o różnych wysokościach. + +Typowym scenariuszem jest tworzenie etykiet produktów, gdzie rozmiar kodu kreskowego musi spełniać specyfikacje skanera. Po zakończeniu tego samouczka będziesz w stanie programowo dostosować parametry szerokości i wysokości oraz zapisać wynik jako obraz PNG. + +## Wymagania wstępne + +Przed rozpoczęciem upewnij się, że masz: + +* .NET 6 (lub nowszy) zainstalowany – kod jest skierowany do .NET 6 SDK. +* Bibliotekę kodów kreskowych obsługującą `EncodeTypes.DatabarOmniDirectional`. Przykład używa **Aspose.BarCode for .NET**, ale każda biblioteka udostępniająca podobne właściwości działa w ten sam sposób. +* IDE lub edytor (Visual Studio, VS Code, Rider) do kompilacji i uruchomienia programu. +* Uprawnienia do zapisu w katalogu, w którym będą zapisywane pliki PNG. + +> **Wskazówka:** Utwórz folder o nazwie `Barcodes` w katalogu głównym projektu i odwołuj się do niego przy pomocy `Path.Combine`, aby uniknąć twardego kodowania ścieżek bezwzględnych. + +## Przykład generatora kodów kreskowych: inicjalizacja i konfiguracja + +Pierwszym krokiem jest utworzenie instancji `BarcodeGenerator` z wybraną symbologią i ciągiem danych. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +Enum `EncodeTypes.DatabarOmniDirectional` wybiera symbologię Databar Omni‑directional, a sformatowany ciąg danych GS1 `(01)12345678901231` reprezentuje typową wartość GTIN‑14. Inicjalizacja generatora raz pozwala na ponowne użycie tego samego obiektu dla wielu obrazów. + +## Jak ustawić szerokość (wymiar X) + +Wymiar X kontroluje szerokość modułu kodu kreskowego. Ustawienie go na 2 piksele sprawia, że każdy wąski pasek ma 2 piksele szerokości, co jest częstym wymogiem przy druku wysokiej gęstości. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Dlaczego to ważne: Jeśli szerokość jest zbyt mała, skanery mogą nie rozróżnić poszczególnych pasków; jeśli jest zbyt duża, kod kreskowy może przekroczyć dostępną przestrzeń etykiety. Dostosuj wartość w pikselach do DPI drukarki oraz docelowego rozmiaru etykiety. + +## Jak zmienić wysokość + +Wysokość pasków określa, jak wysokie będą paski. Przykład tworzy dwa obrazy: jeden o wysokości 30 pikseli i drugi o wysokości 60 pikseli. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Właściwość `BarHeight.Pixels` bezpośrednio wpływa na wizualną wysokość pasków. Zmiana jej wartości pomiędzy zapisami pozwala generować wiele wariantów z tym samym zestawem danych bez konieczności ponownego tworzenia generatora. + +### Oczekiwany wynik + +Uruchomienie programu tworzy dwa pliki PNG w folderze `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – paski mają wysokość 30 pikseli. +* `DatabarBarHeight60Pixels.png` – paski mają wysokość 60 pikseli. + +Oba obrazy mają tę samą szerokość (określoną przez wymiar X) i kodują identyczne dane GTIN‑14. + +![Dwa pliki PNG z kodami kreskowymi o różnych wysokościach wygenerowane przez kod C#](barcode-example.png "Przykład generatora kodów kreskowych pokazujący wariacje wysokości") + +*Tekst alternatywny obrazu powyżej zawiera główne słowo kluczowe dla dostępności i SEO.* + +## Jak wygenerować obraz kodu kreskowego w C# + +Metoda `Save` obsługuje konwersję danych kodu kreskowego do pliku obrazu. Możesz wybrać inne formaty (JPEG, BMP, SVG), przekazując inną wartość wyliczeniową `BarCodeImageFormat`. Przykład używa PNG, ponieważ zachowuje jakość bezstratną i jest szeroko wspierany. + +Jeśli potrzebujesz osadzić kod kreskowy bezpośrednio w PDF‑ie lub na stronie internetowej, pobierz obraz jako `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +To podejście eliminuje potrzebę plików tymczasowych i jest przydatne w usługach o wysokiej przepustowości. + +## Typowe warianty i przypadki brzegowe + +| Sytuacja | Dostosowanie | +|-----------|------------| +| **Inna symbologia** | Zastąp `EncodeTypes.DatabarOmniDirectional` inną wartością wyliczeniową (np. `EncodeTypes.Code128`). | +| **Bardzo małe etykiety** | Zmniejsz `XDimension.Pixels` do 1 piksela, ale sprawdź czytnik pod kątem czytelności. | +| **Druk wysokiej rozdzielczości** | Zwiększ zarówno wymiar X, jak i wysokość pasków proporcjonalnie (np. 4 px szerokości, 80 px wysokości). | +| **Dynamiczne dane** | Przekaż ciąg danych w czasie wykonywania, być może z rekordu bazy danych. | +| **Generowanie wsadowe** | Iteruj po kolekcji ciągów danych, ponownie używając tego samego obiektu `BarcodeGenerator`, aktualizując `generator.Text`. | + +Gdy napotkasz wyjątek taki jak `ArgumentOutOfRangeException`, sprawdź ponownie, czy wartości w pikselach są dodatnimi liczbami całkowitymi oraz czy istnieje katalog wyjściowy. + +## Pełny kod źródłowy podsumowanie + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Skopiuj kod do nowego projektu konsolowego, przywróć pakiet NuGet Aspose.BarCode (`dotnet add package Aspose.BarCode`) i uruchom `dotnet run`. Zobaczysz komunikaty w konsoli potwierdzające zapisane pliki. + +## Zakończenie + +Ten **przykład generatora kodów kreskowych** pokazuje, jak ustawić szerokość, jak zmienić wysokość oraz jak wygenerować obraz kodu kreskowego w C#. Poprzez dostosowanie `XDimension.Pixels` i `BarHeight.Pixels` kontrolujesz wizualny rozmiar kodu, a metoda `Save` zapisuje wynik w plikach PNG. Eksperymentuj z różnymi symbologiami, formatami wyjściowymi i ciągami danych, aby dopasować rozwiązanie do wymagań Twojej aplikacji. + +**Kolejne kroki** + +* Poznaj **jak generować kod kreskowy** w innych formatach obrazu (SVG, JPEG) do użytku w sieci. +* Dowiedz się **jak tworzyć obraz kodu kreskowego c#** dla punktów końcowych ASP.NET Core, które zwracają PNG bezpośrednio do przeglądarki. +* Połącz ten kod z biblioteką generującą PDF, aby osadzać kody kreskowe w fakturach lub etykietach wysyłkowych. + +Śmiało dostosowuj przykład, dziel się wynikami lub zadawaj pytania w komentarzach. Szczęśliwego kodowania! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki 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 wraz z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak generować kod kreskowy – typy kodów jednowymiarowych](/barcode/english/net/one-dimensional-barcode-types/) +- [Jak ustawić obramowanie dla dostosowywania kodu ITF-14](/barcode/english/net/itf-14-barcode-customization/) +- [Jak generować kody DataMatrix (ECC 200) przy użyciu Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/polish/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..92f8716f9 --- /dev/null +++ b/barcode/polish/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-08-03 +description: Utwórz plik PNG z kodem kreskowym w C# i dowiedz się, jak zmienić proporcje + obrazu DataBar. Skorzystaj z tego pełnego przykładu z kodem i wskazówkami. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: pl +lastmod: 2026-08-03 +og_description: Utwórz plik PNG z kodem kreskowym w C# i zobacz, jak zmienić proporcje + dla kodów DataBar. Ten przewodnik dostarcza gotowy do uruchomienia kod oraz praktyczne + wskazówki. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Utwórz plik PNG z kodem kreskowym w C# – pełny przykład z kontrolą proporcji +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Tworzenie pliku PNG z kodem kreskowym w C# – przewodnik krok po kroku +url: /pl/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utwórz plik PNG z kodem kreskowym w C# – przewodnik krok po kroku + +Jeśli potrzebujesz **utworzyć plik PNG z kodem kreskowym** w C#, ten poradnik pokaże Ci dokładnie, jak to zrobić. Wygenerujesz stosowany omnidirectional DataBar, zapiszesz go jako plik PNG i dowiesz się **jak zmienić współczynnik proporcji**, aby dopasować go do różnych środowisk skanowania. + +Poradnik obejmuje wszystko, czego potrzebujesz: wymagane pakiety, kompletny, gotowy do uruchomienia program oraz wyjaśnienia, dlaczego każde ustawienie ma znaczenie. Po zakończeniu będziesz mieć dwa pliki PNG — jeden z współczynnikiem proporcji 15 i drugi z 30 — gotowe do testów lub użycia w produkcji. + +## Wymagania wstępne + +- .NET 6.0 SDK lub nowszy zainstalowany +- Visual Studio 2022 (lub dowolne IDE C#) +- Odwołanie NuGet do **Aspose.BarCode** (biblioteka udostępniająca `BarcodeGenerator`) +- Uprawnienia do zapisu w katalogu, w którym będą zapisywane pliki PNG + +Możesz dodać pakiet Aspose.BarCode za pomocą następującego polecenia: + +```bash +dotnet add package Aspose.BarCode +``` + +## Krok 1: Skonfiguruj projekt i zaimportuj przestrzenie nazw + +Utwórz nową aplikację konsolową i zaimportuj przestrzenie nazw wymagane do generowania kodów kreskowych oraz operacji I/O. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Dlaczego to ważne:** Importowanie `Aspose.BarCode.Generation` daje dostęp do `BarcodeGenerator`. Trzymanie kodu wewnątrz `Main` sprawia, że przykład jest samodzielny i łatwy do uruchomienia. + +## Krok 2: Utwórz generator kodu kreskowego dla stosowanego omnidirectional DataBar + +Zainicjuj `BarcodeGenerator` z typem `EncodeTypes.DatabarStackedOmniDirectional` oraz przykładowym ciągiem danych GS1‑128. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Dlaczego to ważne:** Wybrany typ kodowania generuje wysokiej gęstości DataBar, który może być odczytany przez większość nowoczesnych skanerów. Ciąg danych jest zgodny z formatem GS1 Application Identifier (01), powszechnym dla identyfikatorów produktów. + +## Krok 3: Zdefiniuj wymiar X (szerokość modułu) w pikselach + +Ustaw szerokość modułu, aby kontrolować ogólny rozmiar kodu kreskowego bez wpływu na jego czytelność. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Dlaczego to ważne:** Wymiar X równy 2 pikselom daje kod kreskowy, który nie jest ani za mały dla skanerów, ani za duży dla typowych przestrzeni etykiet. + +## Krok 4: Zapisz pierwszy plik PNG z współczynnikiem proporcji 15 + +Dostosuj współczynnik proporcji DataBar, a następnie zapisz obraz jako plik PNG. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Dlaczego to ważne:** Współczynnik proporcji kontroluje stosunek wysokości do szerokości stosowanego DataBar. Współczynnik 15 jest powszechnym domyślnym ustawieniem, które równoważy czytelność i wysokość etykiety. + +## Krok 5: Zmień współczynnik proporcji na 30 i zapisz drugi plik PNG + +Zmodyfikuj tę samą instancję generatora, aby używać większego współczynnika proporcji, a następnie zapisz drugi obraz. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Dlaczego to ważne:** Zwiększenie współczynnika proporcji rozciąga kod kreskowy w pionie, co może poprawić niezawodność skanowania na urządzeniach o niskiej rozdzielczości lub gdy etykieta jest drukowana na wąskim nośniku. + +## Oczekiwany wynik + +Uruchomienie programu tworzy dwa pliki PNG: + +| Plik | Współczynnik proporcji | Przybliżone wymiary (piksele) | +|------------------------------------|------------------------|-------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (szerokość × wysokość) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (szerokość × wysokość) | + +Oba obrazy zawierają wyraźny, możliwy do zeskanowania kod DataBar, który koduje identyfikator GS1 `(01)12345678901231`. + +## Częste pytania i przypadki brzegowe + +### Jak zmienić inne właściwości wizualne? + +Możesz dostosować kolor pierwszego planu, kolor tła lub dodać tekst czytelny dla człowieka za pomocą obiektu `generator.Parameters.Barcode`. Na przykład: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Co zrobić, jeśli potrzebuję innego formatu obrazu? + +Zastąp `BarCodeImageFormat.Png` przez `Jpeg`, `Bmp` lub `Gif` w zależności od potrzeb. PNG pozostaje najlepszym wyborem dla bezstratnych obrazów kodów kreskowych. + +### Czy współczynnik proporcji wpływa na szybkość skanowania? + +Wyższe współczynniki proporcji zwiększają wysokość kodu kreskowego, co może poprawić niezawodność skanowania na urządzeniach, które mają problemy z krótkimi stosowanymi symbolami. Jednak bardzo wysokie kody kreskowe mogą nie zmieścić się na małych etykietach, dlatego przetestuj je na docelowym sprzęcie. + +### Czy mogę generować wiele kodów kreskowych w pętli? + +Tak. Utwórz nową instancję `BarcodeGenerator` dla każdego ciągu danych lub ponownie użyj tej samej instancji, aktualizując `CodeText` i `DataBar.AspectRatio`. To podejście zmniejsza narzut związany z alokacją obiektów. + +## Porady profesjonalne + +- **Reuse the generator**: Zmiana tylko `CodeText` lub `AspectRatio` unika ponownego tworzenia obiektu, co przyspiesza przetwarzanie wsadowe. +- **Validate the output**: Użyj skanera ręcznego lub aplikacji mobilnej, aby potwierdzić, że wygenerowany PNG odczytuje się poprawnie przed wdrożeniem do produkcji. +- **File naming**: Umieść współczynnik proporcji w nazwie pliku (jak pokazano), aby śledzić warianty podczas testów. + +## Zakończenie + +Teraz wiesz, jak **utworzyć pliki PNG z kodem kreskowym** w C# i dokładnie **jak zmienić współczynnik proporcji** dla stosowanych omnidirectional DataBar. Pełny przykład demonstruje inicjalizację, ustawienie wymiaru X, manipulację współczynnikiem proporcji oraz zapisywanie obrazu — wszystko w jednym, uruchamialnym programie. + +Od tego momentu możesz eksplorować dodatkowe typy kodów kreskowych, eksperymentować z kolorami lub zintegrować generator z większym systemem raportowania lub inwentaryzacji. Szczęśliwego kodowania! + +## Co powinieneś nauczyć się dalej? + +Poniższe poradniki 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. + +- [Utwórz plik PNG z kodem kreskowym – Współczynnik proporcji DataMatrix – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Jak wygenerować kod Aztec z niestandardowym współczynnikiem proporcji przy użyciu Aspose.BarCode dla .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Jak dostosować kod kreskowy – Współczynnik proporcji Codablock F z Aspose.BarCode dla .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/polish/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..b51c1f53d --- /dev/null +++ b/barcode/polish/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-08-03 +description: Szybko utwórz plik PNG z kodem kreskowym dzięki temu przewodnikowi. Dowiedz + się, jak generować obraz kodu kreskowego przy użyciu Aspose.BarCode i wygenerować + kod kreskowy planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: pl +lastmod: 2026-08-03 +og_description: Twórz kod kreskowy PNG od razu. Ten samouczek pokazuje, jak wygenerować + obraz kodu kreskowego oraz kod planetarny przy użyciu Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Tworzenie kodu kreskowego PNG w Pythonie – kompletny przewodnik programistyczny +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Tworzenie kodu kreskowego PNG w Pythonie – przewodnik krok po kroku +url: /pl/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tworzenie pliku PNG z kodem kreskowym w Python – przewodnik krok po kroku + +Jeśli potrzebujesz **tworzyć pliki PNG z kodem kreskowym** w swojej aplikacji Python, ten tutorial pokaże Ci dokładnie, jak to zrobić. Przejdziemy przez **generowanie obrazu kodu kreskowego** przy użyciu Aspose.BarCode oraz, w szczególności, **generowanie kodu Planet** o niestandardowych wymiarach. + +Dowiesz się, jak zainstalować bibliotekę, skonfigurować symbologię Planet, dostosować parametry rozmiaru oraz zapisać wynik jako wysokiej jakości PNG. Poradnik zakłada podstawową znajomość Pythona oraz aktualną wersję Python 3 (3.8 lub nowszą). Nie wymaga wcześniejszej znajomości standardów kodów kreskowych. + +--- + +## Jak stworzyć PNG z kodem kreskowym przy użyciu Aspose.BarCode + +Ta sekcja zawiera podstawowe kroki niezbędne do **tworzenia PNG z kodem kreskowym**. Każdy krok zawiera fragment kodu, wyjaśnienie jego znaczenia oraz praktyczne wskazówki, które możesz od razu zastosować. + +### 1. Zainstaluj pakiet Aspose.BarCode + +Aspose udostępnia czysty pakiet Python, który opakowuje jego silnik .NET. Zainstaluj go przy pomocy `pip`: + +```bash +pip install aspose-barcode +``` + +*Dlaczego ten krok jest ważny:* Pakiet dostarcza klasę `BarcodeGenerator`, używaną w całym przykładzie. Globalna instalacja zapewnia interpreterowi możliwość odnalezienia zestawu w czasie wykonywania. + +### 2. Zaimportuj wymagane klasy + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Wskazówka:* Importuj tylko te symbole, które są potrzebne; dzięki temu przestrzeń nazw pozostaje czysta, a ładowanie modułów szybsze. + +### 3. Utwórz generator kodu kreskowego dla symbologii Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Dlaczego to istotne:* `EncodeTypes.Planet` informuje silnik, że ma użyć standardu kodu Planet, a drugi argument przekazuje dane do zakodowania. Zmiana symbologii (np. na `EncodeTypes.Code128`) spowodowałaby zupełnie inny wzór wizualny. + +### 4. Ustaw wymiar X (szerokość modułu) w pikselach + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Wyjaśnienie:* Wymiar X kontroluje szerokość wąskiej kreski. Wartość 4 piksele daje umiarkowanie gęsty kod, który pozostaje czytelny dla większości urządzeń. + +### 5. Zdefiniuj ręczną wysokość kreski w pikselach + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Dlaczego możesz to zmienić:* Niektóre drukarki detaliczne wymagają wyższych kresek dla niezawodnego skanowania. Domyślna wysokość to zazwyczaj 50 px; zwiększenie jej do 100 px poprawia czytelność bez znaczącego powiększenia rozmiaru pliku. + +### 6. Zapisz wygenerowany kod kreskowy jako obraz PNG + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Rezultat:* Plik PNG o nazwie **PlanetBarHeight100.png** pojawia się w folderze `output`. PNG jest bezstratny, co czyni go idealnym do druku i osadzania w stronach internetowych. + +### 7. Zweryfikuj wynik (opcjonalnie) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Wskazówka:* Oglądanie obrazu potwierdza, że wymiary odpowiadają ustawionym parametrom. Jeśli kod wygląda na zniekształcony, sprawdź ponownie ustawienia wymiaru X lub wysokości kreski. + +--- + +## Jak wygenerować obraz kodu kreskowego w formacie PNG (alternatywne ustawienia) + +Jeśli potrzebujesz innego formatu obrazu lub chcesz później osadzić kod w PDF, możesz zmienić wartość enum `BarCodeImageFormat`: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Dlaczego to ważne:* PNG zachowuje każdy piksel, co jest kluczowe dla kodów o wysokim kontraście. JPEG wprowadza artefakty kompresji, które mogą zakłócać skanowanie, natomiast BMP zapewnia kompatybilność ze starszymi narzędziami. + +--- + +## Generowanie kodu Planet z niestandardowymi kolorami (zaawansowane) + +Poza rozmiarem możesz dostosować kolory pierwszego planu i tła: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Praktyczna wskazówka:* Parowanie kolorów o wysokim kontraście (ciemny na jasnym) maksymalizuje niezawodność skanera. Unikaj podobnych odcieni dla pierwszego planu i tła. + +--- + +## Typowe pułapki i jak ich unikać + +| Objaw | Przyczyna | Rozwiązanie | +|-------|-----------|--------------| +| Kod nie jest odczytywany | Zbyt mały wymiar X (≤ 2 px) | Zwiększ `x_dimension.pixels` do przynajmniej 3 px | +| Obraz jest rozmyty | PNG zapisany w niskiej rozdzielczości DPI | Użyj `barcode_generator.save(..., BarCodeImageFormat.Png, 300)`, aby określić 300 DPI (jeśli jest wspierane) | +| Wyjątek `ImportError` | Aspose.BarCode nie został zainstalowany | Uruchom `pip install aspose-barcode` w tym samym środowisku co skrypt | +| Nieprawidłowa symbologia | Użyto `EncodeTypes.Code128` zamiast `EncodeTypes.Planet` | Zamień na `EncodeTypes.Planet` przy tworzeniu generatora | + +--- + +## Podsumowanie pełnego rozwiązania + +Poniżej znajduje się kompletny, gotowy do uruchomienia skrypt, który **tworzy PNG z kodem kreskowym** od początku do końca: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Uruchomienie tego skryptu generuje wyraźny **kod Planet w formacie PNG**, który możesz osadzić w HTML, dołączyć do e‑maili lub wydrukować na etykietach produktów. + +--- + +## Kolejne kroki i powiązane tematy + +* **Integracja z Flask lub Django** – serwuj wygenerowane PNG bezpośrednio z endpointu webowego. +* **Generowanie wsadowe** – iteruj listę identyfikatorów produktów, aby stworzyć folder z plikami PNG kodów kreskowych. +* **Połączenie z generowaniem PDF** – użyj `aspose-pdf`, aby umieścić PNG w fakturze lub etykiecie wysyłkowej. +* **Eksploracja innych symbologii** – zamień `EncodeTypes.Planet` na `EncodeTypes.QR`, `EncodeTypes.DataMatrix` lub `EncodeTypes.Code128`, aby spełnić różne potrzeby biznesowe. + +Opanowując powyższe kroki, teraz wiesz **jak programowo generować obraz kodu kreskowego** i możesz rozszerzyć tę metodę na dowolny standard obsługiwany przez Aspose.BarCode. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/polish/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..82d4e6943 --- /dev/null +++ b/barcode/polish/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-08-03 +description: Szybko utwórz obraz kodu pocztowego w C#. Dowiedz się, jak generować + kod pocztowy, ustawiać wymiary kodu i generować kod Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: pl +lastmod: 2026-08-03 +og_description: Utwórz obraz kodu kreskowego pocztowego w C# dzięki temu kompletnemu + samouczkowi; dowiedz się, jak ustawić wymiary kodu kreskowego, wygenerować kod Planet + oraz tworzyć kody RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Tworzenie obrazu kodu kreskowego pocztowego w C# – pełny przewodnik programistyczny +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Tworzenie obrazu kodu pocztowego w C# – przewodnik krok po kroku +url: /pl/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utwórz obraz kodu kreskowego pocztowego w C# – przewodnik krok po kroku + +Jeśli potrzebujesz **utworzyć obraz kodu kreskowego pocztowego** w C#, ten przewodnik pokaże Ci dokładnie, jak to zrobić. Omówimy **jak wygenerować kod kreskowy pocztowy**, **jak ustawić wymiary kodu kreskowego** oraz **jak wygenerować kod Planet** dla popularnych standardów pocztowych. + +Na końcu otrzymasz dwa gotowe do użycia pliki PNG — jeden z kodem Planet i jeden z kodem RM4SCC — każdy o wysokości 100 px. Nie są potrzebne żadne dodatkowe narzędzia poza biblioteką Aspose.BarCode for .NET. + +## Wymagania wstępne + +* .NET 6 SDK lub nowszy (kod działa również z .NET Framework 4.7+) +* Visual Studio 2022 lub dowolne IDE C# +* Pakiet NuGet **Aspose.BarCode** (biblioteka udostępniająca `BarcodeGenerator`) + +## Krok 1: Zainstaluj bibliotekę kodów kreskowych + +Otwórz terminal w folderze projektu i uruchom: + +```bash +dotnet add package Aspose.BarCode +``` + +Pakiet dodaje przestrzeń nazw `Aspose.BarCode`, która zawiera `BarcodeGenerator` oraz wyliczenie `EncodeTypes` niezbędne do kodów kreskowych pocztowych. + +## Krok 2: Zdefiniuj folder wyjściowy + +Utworzenie niezawodnej ścieżki wyjściowej zapobiega błędom w czasie wykonywania, gdy folder nie istnieje. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Dlaczego to ważne*: `Directory.CreateDirectory` jest idempotentny — tworzy folder tylko wtedy, gdy jeszcze nie istnieje, co zapobiega wyjątkom przy kolejnych uruchomieniach. + +## Krok 3: Skonfiguruj wspólne wymiary kodu kreskowego + +Ustawienie wymiaru X (szerokość pojedynczej kreski) oraz całkowitej wysokości kreski pozwala kontrolować wizualny rozmiar generowanego obrazu. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Jak ustawić wymiary kodu kreskowego**: właściwość `Parameters.Barcode.XDimension.Pixels` definiuje szerokość wąskiej kreski, natomiast `Parameters.Barcode.BarHeight.Pixels` określa pełną wysokość. Dostosuj te wartości, aby spełniały specyfikacje Twojej usługi pocztowej. + +## Krok 4: Wygeneruj kod Planet + +Planet jest szeroko stosowanym kodem kreskowym pocztowym w Wielkiej Brytanii. Poniższy kod tworzy kod Planet o wysokości 100 px i zapisuje go jako PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Dlaczego to działa**: `EncodeTypes.Planet` informuje generator, aby użył symboliki Planet. Metoda `Save` zapisuje plik PNG w określonej ścieżce, zachowując wcześniej ustawione wymiary. + +## Krok 5: Wygeneruj kod RM4SCC + +RM4SCC jest holenderskim standardem kodów kreskowych pocztowych. Poniższy kod odzwierciedla przykład Planet, demonstrując **jak wygenerować kod kreskowy pocztowy** innego typu przy zachowaniu identycznych wymiarów. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Oba pliki PNG znajdują się teraz w folderze `Barcodes`. Po otwarciu zobaczysz czyste kody kreskowe o wysokości 100 px, gotowe do druku lub osadzenia w dokumentach. + +## Pełny kod źródłowy + +Poniżej znajduje się kompletny, gotowy do uruchomienia program, który **tworzy obrazy kodów kreskowych pocztowych** dla standardów Planet i RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Oczekiwany wynik + +Uruchomienie programu wypisuje ścieżki do plików i tworzy dwa pliki PNG: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Każdy obraz ma wysokość 100 px, przy szerokości wąskiej kreski 4 px, co odpowiada ustawionym wymiarom. + +## Praktyczne wskazówki i typowe pułapki + +* **Uprawnienia folderu** – Jeśli program działa pod ograniczonym kontem, upewnij się, że docelowy folder jest zapisywalny. +* **Różne wymiary** – Aby utworzyć wyższy kod kreskowy, zwiększ `barHeightPixels`. Dla większej rozdzielczości, zmniejsz `xDimensionPixels`, ale zachowaj wartość ≥ 2, aby uniknąć artefaktów renderowania. +* **Inne symbologie pocztowe** – Aspose.BarCode obsługuje także `EncodeTypes.Postnet` i `EncodeTypes.AustralianPost`. Zamień wartość `EncodeTypes` i zachowaj tę samą logikę wymiarów. +* **Format obrazu** – Użyj `BarCodeImageFormat.Jpeg`, aby uzyskać mniejszy rozmiar pliku, gdy jakość bezstratna nie jest wymagana. + +## Zakończenie + +Teraz wiesz, jak **utworzyć obrazy kodów kreskowych pocztowych** w C#, konfigurując wymiary, wybierając odpowiednią symbologię i zapisując wynik jako PNG. Samouczek omówił **jak wygenerować kod kreskowy pocztowy**, pokazał **generowanie kodu Planet** oraz wyjaśnił **jak ustawić wymiary kodu kreskowego** dla spójnego wyniku. + +Następnie możesz zbadać **dostosowywanie kolorów kodu kreskowego**, dodawanie **czytelnego dla człowieka tekstu** lub integrowanie obrazów z fakturami PDF. Ten sam schemat działa dla każdego innego typu kodu kreskowego obsługiwanego przez Aspose.BarCode, co pozwala rozbudować to rozwiązanie do pełnego przepływu automatyzacji pocztowej. + +## Co powinieneś 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. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to generate barcode java – Australia Post Barcode with Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/polish/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..dff3275b3 --- /dev/null +++ b/barcode/polish/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-08-03 +description: Jak zapisać kod kreskowy w C# z przykładem generatora kodów kreskowych + krok po kroku. Dowiedz się, jak generować kody kreskowe Planet, ustawiać wymiary + i eksportować obrazy PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: pl +lastmod: 2026-08-03 +og_description: Jak zapisać kod kreskowy w C# przy użyciu przykładu generatora kodów + kreskowych. Ten poradnik pokazuje, jak generować kody kreskowe Planet, konfigurować + wymiar X i eksportować pliki PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Jak zapisać kod kreskowy w C# – przewodnik krok po kroku +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Jak zapisać kod kreskowy w C# – kompletny przewodnik po generatorze kodów kreskowych +url: /pl/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak zapisać kod kreskowy w C# – kompletny przewodnik po generatorze kodów kreskowych + +Zapisywanie obrazów kodów kreskowych w C# jest powszechnym wymaganiem, gdy trzeba osadzać kody pocztowe w fakturach, etykietach wysyłkowych lub tagach inwentaryzacyjnych. Ten przewodnik przeprowadzi Cię przez praktyczny **c# barcode generator** workflow, od tworzenia kodu Planet po eksportowanie zarówno plików PNG z filled‑bars i empty‑bars. + +Nauczysz się, jak ustawić szerokość paska, przełączać wypełnione paski i niezawodnie obsługiwać foldery wyjściowe. Po zakończeniu samouczka będziesz mieć w pełni funkcjonalny **barcode generator example**, który możesz skopiować do dowolnego projektu .NET. + +## Co będzie potrzebne + +- .NET 6.0 SDK lub nowszy (przykład działa z .NET Core i .NET Framework) +- Visual Studio 2022 lub dowolne IDE zgodne z C# +- Pakiet NuGet **Aspose.BarCode** (lub inna biblioteka obsługująca `EncodeTypes.Planet`). Zainstaluj go za pomocą: + +```bash +dotnet add package Aspose.BarCode +``` + +Biblioteka udostępnia klasę `BarcodeGenerator` używaną w całym tym samouczku. + +## Konfigurowanie środowiska programistycznego + +Utwórz nowy projekt konsolowy i dodaj wymaganą przestrzeń nazw: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +Przestrzeń nazw `System.IO` udostępnia `Directory.CreateDirectory`, co zapewnia istnienie folderu wyjściowego przed próbą zapisu plików. + +## Jak zapisać obrazy kodów kreskowych przy użyciu generatora kodów kreskowych w C# + +Sednem rozwiązania jest niewielki zestaw kroków, które konfigurowują **Planet barcode** i następnie zapisują obraz na dysku. Poniższe sekcje dzielą proces na łatwe do zarządzania części. + +### Krok 1: Zdefiniuj folder wyjściowy + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Why?** +Hard‑coding ścieżki może spowodować `DirectoryNotFoundException` na maszynach, gdzie folder nie istnieje. `CreateDirectory` jest idempotentny — tworzy katalog tylko wtedy, gdy go brakuje, co sprawia, że kod jest bezpieczny przy wielokrotnym uruchamianiu. + +### Krok 2: Utwórz generator kodu Planet (filled bars) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Why?** +`EncodeTypes.Planet` instruuje bibliotekę, aby wygenerowała pocztowy kod Planet, który jest szeroko stosowany przez usługi pocztowe. Ciąg znaków `"123456"` jest przykładową zawartością; zamień go na dowolne dane numeryczne wymagane przez Twoją logikę biznesową. + +### Krok 3: Skonfiguruj szerokość paska (X‑dimension) i zachowaj domyślne wypełnione paski + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Why?** +X‑dimension kontroluje fizyczną szerokość każdego paska. Wartość `4` piksele zapewnia czytelny kod kreskowy na standardowych drukarkach 300 dpi. Pozostawienie `FilledBars` jako `true` (wartość domyślna) daje klasyczny wygląd solid‑bar. + +### Krok 4: Zapisz obraz kodu kreskowego z wypełnionymi paskami + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Why?** +Zapis jako PNG zachowuje bezstratną jakość obrazu, co jest ważne dla dokładności skanowania. Metoda `Save` automatycznie tworzy plik obrazu; musisz jedynie podać pełną ścieżkę i żądany format. + +### Krok 5: Utwórz drugi generator dla wersji z pustymi paskami + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Utworzenie nowej instancji zapewnia, że zmiany wprowadzone dla wersji z pustymi paskami nie wpłyną na już zapisany obraz z wypełnionymi paskami. + +### Krok 6: Wyłącz wypełnione paski, zachowując tę samą X‑dimension + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Why?** +Ustawienie `FilledBars = false` renderuje kod kreskowy tylko z konturem każdego paska, co niektóre standardy pocztowe wymagają do weryfikacji wizualnej. + +### Krok 7: Zapisz obraz kodu kreskowego z pustymi paskami + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Teraz masz dwa pliki PNG — jeden z wypełnionymi paskami, a drugi z pustymi paskami — gotowe do włączenia w PDF-y, e‑maile HTML lub drukowane etykiety. + +## Pełny program do uruchomienia + +Poniżej znajduje się kompletny kod, który możesz skopiować do `Program.cs`. Kompiluje się i uruchamia bez modyfikacji (zakładając, że pakiet Aspose.BarCode jest zainstalowany). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Oczekiwany wynik + +Uruchomienie programu wypisuje dwie linie podobne do: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Otwórz folder `Barcodes` i zobaczysz dwa pliki PNG. Oba obrazy można otworzyć w dowolnej przeglądarce obrazów lub osadzić bezpośrednio w dokumentach. + +![przykład zapisywania kodu kreskowego](barcode-example.png){: .align-center alt="przykład zapisywania kodu kreskowego"} + +## Typowe warianty i przypadki brzegowe + +| Scenariusz | Dostosowanie | +|------------|--------------| +| **Inny format obrazu** | Zmien `BarCodeImageFormat.Png` na `Jpeg`, `Gif` lub `Bmp` w zależności od potrzeb. | +| **Niestandardowy rozmiar wyjściowy** | Użyj `filled.Parameters.Image.Width` i `Height`, aby wymusić określony wymiar w pikselach. | +| **Dane dynamiczne** | Zastąp statyczny ciąg `"123456"` zmienną przechowującą numery zamówień, identyfikatory śledzenia itp. | +| **Nieistniejący folder** | `Directory.CreateDirectory` już obsługuje brakujące katalogi; nie wymaga dodatkowego kodu. | +| **Druk wysokiej rozdzielczości** | Zwiększ `XDimension.Pixels` do 6–8 dla drukarek 600 dpi, ale sprawdź kompatybilność ze skanerem. | + +**Pro tip:** Jeśli musisz generować wiele kodów kreskowych w pętli, użyj jednej instancji `BarcodeGenerator` i zmieniaj tylko właściwość `CodeText` przed każdym wywołaniem `Save`. Redukuje to narzut alokacji obiektów. + +## Jak generować kody kreskowe dla innych standardów + +Ten sam wzorzec działa dla innych `EncodeTypes`, takich jak `Code128`, `QR` lub `DataMatrix`. Po prostu zamień `EncodeTypes.Planet` na żądany typ i dostosuj wszelkie parametry specyficzne dla typu (np. `QRCodeVersion` + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki 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 instrukcjami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Jak zapisać PNG używając DataMatrix C40 z Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Jak generować kody DataMatrix (ECC 200) z Aspose.BarCode dla .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Jak generować kod kreskowy – konfiguracja Code 39 z Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/portuguese/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..a7fd5bb0a --- /dev/null +++ b/barcode/portuguese/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-08-03 +description: Tutorial de geração de código de barras em C# mostrando como criar código + de barras Planet com Aspose.BarCode, definir a dimensão X e salvar como imagens + PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: pt +lastmod: 2026-08-03 +og_description: O tutorial de gerador de código de barras em C# orienta você na criação + de um código de barras Planet, ajuste da dimensão X e salvamento como PNG usando + Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Gerador de código de barras C# – crie o código de barras Planet passo a + passo +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Gerador de código de barras C# – criar código de barras Planet e exemplo RM4SCC +url: /pt/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Gerador de código de barras C# – exemplo de criação de código Planet e RM4SCC + +Se você precisa de um **barcode generator C#** que possa gerar símbolos postais específicos, este guia mostra exatamente como **create Planet barcode** imagens com Aspose.BarCode. Você verá como configurar a dimensão X, gerar um código de barras RM4SCC correspondente e salvar ambos como arquivos PNG — tudo em poucos passos concisos. + +O tutorial cobre tudo o que você precisa para executar o código no .NET 6 ou posterior, explica por que cada configuração importa e aponta armadilhas comuns, como largura de módulo incorreta ou permissões de diretório ausentes. Ao final, você terá duas imagens de código de barras prontas para impressão que atendem aos padrões Planet e RM4SCC. + +## Prerequisites + +Antes de começar, certifique‑se de que você tem: + +* .NET 6 SDK (ou qualquer versão do .NET suportada pelo Aspose.BarCode) +* Visual Studio 2022 ou qualquer IDE C# de sua preferência +* Uma referência NuGet ao **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Permissão de escrita na pasta onde você pretende armazenar os arquivos PNG + +Nenhum serviço externo adicional é necessário; a biblioteca lida com toda a codificação localmente. + +## Step 1: Initialise the barcode generator C# object + +A primeira tarefa é criar uma instância de `BarcodeGenerator`. O construtor recebe a simbologia do código de barras (`EncodeTypes.Planet`) e os dados a serem codificados. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Why this step?* +`BarcodeGenerator` é o ponto de entrada para cada código de barras que você gera. Selecionar `EncodeTypes.Planet` indica à biblioteca que deve seguir a especificação ISO/IEC 24723 usada por muitos serviços postais. + +## Step 2: Set the X‑dimension (module width) for the Planet barcode + +A dimensão X define a largura de um único módulo do código de barras (a menor barra ou espaço). Um valor de **4 pixels** funciona bem para a maioria das impressoras de etiquetas. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Why this matters* +Se o módulo for muito estreito, o código de barras pode ficar ilegível; se for muito largo, o tamanho da etiqueta cresce desnecessariamente. Ajustar `Pixels` permite afinar o código de barras para a resolução específica da sua impressora. + +## Step 3: Save the Planet barcode as a PNG image + +Aspose.BarCode calcula automaticamente a altura do código de barras com base na simbologia selecionada, portanto você só precisa especificar o caminho do arquivo e o formato. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tip* +Substitua `YOUR_DIRECTORY` por um caminho absoluto ou relativo que exista na sua máquina. Se a pasta não existir, o método `Save` lançará uma `DirectoryNotFoundException`. + +**Expected output** – um arquivo PNG que se parece com a ilustração abaixo (a imagem real não é exibida aqui, mas você verá um clássico código Planet com carga numérica `123456`). + +## Step 4: Initialise a second generator for the RM4SCC barcode + +Muitos sistemas postais exigem símbolos Planet e RM4SCC no mesmo envelope. Crie uma nova instância de `BarcodeGenerator` para a simbologia RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Why a separate instance?* +Cada simbologia tem seu próprio conjunto de parâmetros. Reutilizar o mesmo gerador poderia transferir inadvertidamente configurações (como a dimensão X) que não são ideais para o segundo código de barras. + +## Step 5: Configure the X‑dimension for the RM4SCC barcode + +RM4SCC também respeita a configuração da dimensão X, então aplicamos a mesma largura em pixels para consistência visual. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +Se precisar de um código de barras mais alto (por exemplo, para etiquetas maiores), você pode também definir `Height.Pixels`. Deixar esse parâmetro sem definição permite que a biblioteca calcule a altura ideal automaticamente. + +## Step 6: Save the RM4SCC barcode as a PNG image + +Por fim, persista o código de barras RM4SCC no disco. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Agora você tem dois arquivos PNG — `PostalPlanetBarHeightNone.png` e `PostalRM4SCCBarHeightNone.png` — que podem ser incorporados em etiquetas de correio, impressos em envelopes ou enviados a um serviço de impressão terceirizado. + +## Optional: Adjusting height or using other image formats + +Se seu fluxo de trabalho exigir uma altura de código de barras específica ou um formato de imagem diferente (por exemplo, JPEG ou BMP), você pode modificar os parâmetros antes de chamar `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Edge case** – Ao definir uma altura personalizada, certifique‑se de que o valor respeita a altura mínima exigida pela norma ISO; caso contrário, o código de barras pode falhar na validação. + +## Common pitfalls and how to avoid them + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| `DirectoryNotFoundException` | A pasta de destino não existe ou está escrita incorretamente. | Crie a pasta primeiro ou use `Path.Combine` com `Environment.CurrentDirectory`. | +| Barcode unreadable on low‑resolution printers | X‑dimension muito pequena para o DPI da impressora. | Aumente `XDimension.Pixels` para 5 – 6 em impressoras de 203 dpi, ou teste com uma etiqueta de amostra. | +| Wrong symbology used | Passando `EncodeTypes.Code128` em vez de `EncodeTypes.Planet`. | Verifique novamente se o valor do enum `EncodeTypes` corresponde ao padrão postal requerido. | +| Null reference on `Parameters` | Usando uma versão mais antiga do Aspose.BarCode onde a API difere. | Atualize para o pacote NuGet mais recente (v23.12 ou superior). | + +## Full runnable example + +Abaixo está o programa completo que você pode copiar, colar e executar. Ele inclui instruções `using`, tratamento de erros e comentários que explicam cada linha. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Executar o programa cria uma pasta `Barcodes` ao lado do executável e coloca os dois arquivos PNG dentro. Abra-os com qualquer visualizador de imagens para verificar o resultado. + +## Conclusion + +Você agora possui uma solução **barcode generator C#** que pode **create Planet barcode** imagens, ajustar a dimensão X para impressão ideal e gerar um código de barras RM4SCC correspondente — tudo com poucas linhas de código. A abordagem funciona com .NET 6+, requer apenas o pacote NuGet Aspose.BarCode e pode ser estendida a outras simbologias como Code128, QR ou DataMatrix trocando o valor de `EncodeTypes`. + +### What’s next? + +* Experimente diferentes valores de `XDimension.Pixels` para combinar com o DPI da sua impressora. +* Gere códigos de barras em outros formatos (PDF, SVG) alterando o enum `BarCodeImageFormat`. +* Combine os dois arquivos PNG em uma única etiqueta usando uma biblioteca gráfica como **SkiaSharp**. +* Explore a API completa do Aspose.BarCode para recursos avançados como validação de checksum ou fontes personalizadas. + +Sinta‑se à vontade para adaptar o código para processamento em lote ou integrá‑lo a um serviço web ASP.NET Core que devolva imagens de códigos de barras sob demanda. Boa codificação! + +## What Should You Learn Next? + +Os tutoriais a seguir abordam 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 em seus próprios projetos. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/portuguese/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..4451f178d --- /dev/null +++ b/barcode/portuguese/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-08-03 +description: Tutorial de gerador de código de barras em C# mostra como gerar imagem + de código de barras com Aspose.BarCode, definir colunas e linhas e salvar arquivos + PNG para DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: pt +lastmod: 2026-08-03 +og_description: Tutorial de geração de código de barras C# explica como gerar imagem + de código de barras usando Aspose.BarCode, configurar colunas e linhas DataBar Expanded + Stacked e salvar arquivos PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Gerador de código de barras C# – guia passo a passo para gerar imagem de + código de barras +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Gerador de código de barras C# – gerar imagem de código de barras +url: /pt/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Gerador de código de barras C# – gerar imagem de código de barras + +Se você precisa de um gerador de código de barras C# que possa gerar imagem de código de barras para DataBar Expanded Stacked, este guia o conduzirá através do processo completo. Você aprenderá como configurar as definições de colunas e linhas, salvar o resultado como PNG e adaptar o código para outras simbologias. + +Gerar imagens de código de barras programaticamente elimina etapas manuais e garante consistência em faturas, etiquetas de envio e sistemas de inventário. Este tutorial cobre tudo o que você precisa, desde a configuração do projeto até o código-fonte completo, para que você possa executar o exemplo imediatamente. + +## Pré-requisitos + +* .NET 6.0 ou posterior instalado +* Uma IDE como Visual Studio 2022 (qualquer editor que suporte C# funciona) +* Uma licença para **Aspose.BarCode for .NET** – a avaliação gratuita funciona para testes +* Familiaridade básica com a sintaxe C# + +Se algum desses itens estiver faltando, instale o .NET SDK em dotnet.microsoft.com e obtenha o pacote NuGet Aspose.BarCode com: + +```bash +dotnet add package Aspose.BarCode +``` + +## Etapa 1: Criar um projeto de gerador de código de barras C# + +Crie um novo aplicativo de console e adicione as diretivas `using` necessárias: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +A classe `BarcodeGenerator` é o núcleo da API de gerador de código de barras C#. Ela recebe o tipo de simbologia e o texto a ser codificado. + +## Etapa 2: Gerar um código de barras DataBar Expanded Stacked e definir colunas + +O primeiro exemplo cria um código de barras com quatro colunas. Ajustar a propriedade `Columns` altera a densidade visual da simbologia DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Por que isso importa:** A contagem de colunas influencia a quantidade de dados que pode ser armazenada em um espaço compacto. Definir para 4 produz um código de barras mais largo que permanece legível pela maioria dos scanners. + +## Etapa 3: Gerar um código de barras com contagem de linhas personalizada + +O segundo exemplo mostra como controlar o layout vertical definindo a propriedade `Rows`. Uma configuração de três linhas é útil quando você precisa de um código de barras mais alto para espaço horizontal limitado. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Por que isso importa:** Ajustar as linhas permite encaixar o código de barras em uma coluna estreita enquanto preserva a legibilidade. O gerador de código de barras C# recalcula automaticamente o tamanho do módulo para atender à especificação. + +## Etapa 4: Exemplo completo e executável + +Abaixo está um programa autônomo que combina as etapas anteriores. Copie o código para `Program.cs`, substitua `YOUR_DIRECTORY` por um caminho de pasta existente e execute o aplicativo. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Saída esperada + +Ao executar o programa, dois arquivos PNG aparecem no diretório de destino: + +* **DatabarCols4.png** – um código de barras DataBar Expanded Stacked com quatro colunas +* **DatabarRows3.png** – os mesmos dados codificados em três linhas + +Abra as imagens com qualquer visualizador; elas exibem códigos de barras nítidos e escaneáveis, prontos para impressão ou incorporação em PDFs. + +## Como gerar imagem de código de barras com dimensões personalizadas + +Se você precisar de um tamanho de imagem específico, ajuste as propriedades `ImageHeight` e `ImageWidth` antes de chamar `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Alterar as dimensões não afeta os dados codificados; apenas escala a representação visual. Essa técnica é útil ao integrar códigos de barras em componentes de UI com restrições de layout fixas. + +## Armadilhas comuns e dicas profissionais + +* **Separadores de caminho:** Use strings verbatim (`@"C:\Path\file.png"`) ou `Path.Combine` para evitar problemas de caracteres de escape no Windows. +* **Aplicação de licença:** Sem uma licença válida, as imagens geradas contêm uma marca d'água. Aplique sua licença logo no início da aplicação: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Limites de codificação:** DataBar Expanded Stacked suporta até 74 caracteres numéricos. Exceder esse limite lança uma exceção. Valide o comprimento da entrada antes de criar o gerador. +* **Desempenho:** Reutilizar uma única instância `BarcodeGenerator` para várias gravações reduz a alocação de memória. Alterar as propriedades `Rows` ou `Columns` entre gravações somente se o texto codificado permanecer o mesmo. + +## Próximos passos + +Agora que você pode gerar imagens de código de barras com o gerador de código de barras C#, considere explorar: + +* **Simbologias diferentes** – experimente `EncodeTypes.QR`, `EncodeTypes.Code128` ou `EncodeTypes.Pdf417`. +* **Personalização de cores** – defina `Parameters.Barcode.ForeColor` e `BackColor` para combinar com a identidade visual. +* **Incorporação em PDFs** – combine o PNG gerado com Aspose.PDF para criar documentos imprimíveis. + +Essas extensões permitem que você construa uma solução completa de código de barras para aplicações de inventário, logística ou varejo. + +--- + +## 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 gerar códigos de barras DataMatrix (ECC 200) com Aspose.BarCode para .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/portuguese/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..55ee26a73 --- /dev/null +++ b/barcode/portuguese/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-08-03 +description: Exemplo de gerador de código de barras em C# mostrando como definir a + largura, como alterar a altura e como gerar a imagem do código de barras. Siga as + instruções passo a passo. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: pt +lastmod: 2026-08-03 +og_description: O exemplo de gerador de código de barras demonstra como definir a + largura da dimensão X, alterar a altura da barra e gerar uma imagem de código de + barras em C#. Siga os passos para criar arquivos PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Exemplo de gerador de código de barras – Guia de largura e altura em C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Exemplo de gerador de código de barras em C# – definir largura e altura +url: /pt/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< 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 em C# – definir largura e altura + +Se você precisa de um **exemplo de gerador de código de barras** em C#, este guia mostra como definir a largura da dimensão X, como alterar a altura das barras e como gerar um arquivo de imagem de código de barras. Você verá um programa completo e executável que produz dois arquivos PNG com alturas diferentes. + +Um cenário típico é a criação de etiquetas de produto onde o tamanho do código de barras deve atender às especificações do scanner. Ao final deste tutorial você será capaz de ajustar programaticamente os parâmetros de largura e altura e salvar o resultado como uma imagem PNG. + +## Pré-requisitos + +Antes de começar, certifique‑se de que você tem: + +* .NET 6 (ou superior) instalado – o código tem como alvo o .NET 6 SDK. +* Uma biblioteca de código de barras que suporte `EncodeTypes.DatabarOmniDirectional`. O exemplo usa **Aspose.BarCode for .NET**, mas qualquer biblioteca que exponha propriedades semelhantes funciona da mesma forma. +* Uma IDE ou editor (Visual Studio, VS Code, Rider) para compilar e executar o programa. +* Permissão de gravação em um diretório onde os arquivos PNG serão salvos. + +> **Dica profissional:** Crie uma pasta chamada `Barcodes` na raiz do seu projeto e faça referência a ela com `Path.Combine` para evitar codificar caminhos absolutos. + +## Exemplo de gerador de código de barras: inicializar e configurar + +O primeiro passo é criar uma instância de `BarcodeGenerator` com a simbologia e a string de dados desejadas. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +O enum `EncodeTypes.DatabarOmniDirectional` seleciona a simbologia Databar Omni‑directional, e a string de dados formatada em GS1 `(01)12345678901231` representa um valor típico de GTIN‑14. Inicializar o gerador uma única vez permite reutilizar o mesmo objeto para várias imagens. + +## Como definir a largura (dimensão X) + +A dimensão X controla a largura do módulo do código de barras. Definir 2 pixels faz com que cada barra estreita tenha 2 pixels de largura, o que é um requisito comum para impressão de alta densidade. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Por que isso importa: se a largura for muito pequena, os scanners podem não conseguir distinguir as barras individuais; se for muito grande, o código de barras pode exceder o espaço da etiqueta. Ajuste o valor em pixels para corresponder ao DPI da impressora e ao tamanho da etiqueta alvo. + +## Como alterar a altura + +A altura da barra determina o quão altas as barras aparecem. O exemplo cria duas imagens: uma com altura de 30 pixels e outra com altura de 60 pixels. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +A propriedade `BarHeight.Pixels` influencia diretamente a altura visual das barras. Alterá‑la entre as gravações permite gerar múltiplas variantes a partir do mesmo payload de dados sem recriar o gerador. + +### Resultado esperado + +Executar o programa produz dois arquivos PNG na pasta `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – barras com 30 pixels de altura. +* `DatabarBarHeight60Pixels.png` – barras com 60 pixels de altura. + +Ambas as imagens compartilham a mesma largura (determinada pela dimensão X) e codificam os mesmos dados GTIN‑14. + +![Two barcode PNG files with different heights generated by C# code](barcode-example.png "Barcode generator example showing height variations") + +*O texto alternativo da imagem acima contém a palavra‑chave principal para acessibilidade e SEO.* + +## Como gerar a imagem do código de barras em C# + +O método `Save` cuida da conversão dos dados do código de barras para um arquivo de imagem. Você pode escolher outros formatos (JPEG, BMP, SVG) passando um valor diferente do enum `BarCodeImageFormat`. O exemplo usa PNG porque preserva qualidade sem perdas e é amplamente suportado. + +Se precisar incorporar o código de barras diretamente em um PDF ou página web, recupere a imagem como um `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Essa abordagem elimina a necessidade de arquivos temporários e é útil para serviços de alta taxa de transferência. + +## Variações comuns e casos de borda + +| Situação | Ajuste | +|-----------|------------| +| **Simbologia diferente** | Substitua `EncodeTypes.DatabarOmniDirectional` por outro valor de enum (por exemplo, `EncodeTypes.Code128`). | +| **Etiquetas muito pequenas** | Diminua `XDimension.Pixels` para 1 pixel, mas verifique a legibilidade pelo scanner. | +| **Impressão de alta resolução** | Aumente tanto a dimensão X quanto a altura da barra proporcionalmente (por exemplo, 4 px de largura, 80 px de altura). | +| **Dados dinâmicos** | Passe a string de dados em tempo de execução, talvez a partir de um registro de banco de dados. | +| **Geração em lote** | Percorra uma coleção de strings de dados, reutilizando a mesma instância de `BarcodeGenerator` enquanto atualiza `generator.Text`. | + +Quando encontrar uma exceção como `ArgumentOutOfRangeException`, verifique se os valores de pixel são inteiros positivos e se o diretório de saída existe. + +## Recapitulação do código‑fonte completo + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Copie o código para um novo projeto de console, restaure o pacote NuGet Aspose.BarCode (`dotnet add package Aspose.BarCode`) e execute `dotnet run`. Você verá mensagens no console confirmando os arquivos salvos. + +## Conclusão + +Este **exemplo de gerador de código de barras** demonstra como definir a largura, como alterar a altura e como gerar uma imagem de código de barras em C#. Ao ajustar `XDimension.Pixels` e `BarHeight.Pixels` você controla o tamanho visual do código de barras, e o método `Save` grava o resultado em arquivos PNG. Experimente diferentes simbologias, formatos de saída e strings de dados para atender aos requisitos da sua aplicação. + +**Próximos passos** + +* Explore **como gerar código de barras** em outros formatos de imagem (SVG, JPEG) para uso na web. +* Aprenda **criar imagem de código de barras c#** para endpoints ASP.NET Core que retornam o PNG diretamente ao navegador. +* Combine este código com uma biblioteca de geração de PDF para incorporar códigos de barras em notas fiscais ou etiquetas de envio. + +Sinta‑se à vontade para adaptar o exemplo, compartilhar seus resultados ou fazer perguntas nos comentários. Boa codificação! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam 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. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to Set Border for ITF-14 Barcode Customization](/barcode/english/net/itf-14-barcode-customization/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/portuguese/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..8fef5ecea --- /dev/null +++ b/barcode/portuguese/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-08-03 +description: Crie PNG de código de barras em C# e aprenda como alterar a proporção + de aspecto para imagens DataBar. Siga este exemplo completo com código e dicas. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: pt +lastmod: 2026-08-03 +og_description: Crie PNG de código de barras em C# e veja como alterar a proporção + para códigos de barras DataBar. Este guia fornece código pronto‑para‑usar e dicas + práticas. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Criar código de barras PNG em C# – exemplo completo com controle de proporção +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Criar PNG de código de barras em C# – guia passo a passo +url: /pt/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar PNG de código de barras em C# – guia passo a passo + +Se você precisa **criar PNG de código de barras** em C#, este tutorial mostra exatamente como fazer. Você irá gerar um código de barras DataBar omnidirecional empilhado, salvá‑lo como um arquivo PNG e aprender **como alterar a proporção** para se adequar a diferentes ambientes de leitura. + +O guia cobre tudo o que você precisa: pacotes necessários, um programa completo e executável, e explicações sobre por que cada configuração importa. Ao final, você terá dois arquivos PNG — um com proporção 15 e outro com 30 — prontos para teste ou uso em produção. + +## Pré‑requisitos + +Antes de começar, certifique‑se de que você tem: + +- .NET 6.0 SDK ou posterior instalado +- Visual Studio 2022 (ou qualquer IDE para C#) +- Uma referência NuGet ao **Aspose.BarCode** (a biblioteca que fornece `BarcodeGenerator`) +- Permissão de gravação no diretório onde os arquivos PNG serão salvos + +Você pode adicionar o pacote Aspose.BarCode com o seguinte comando: + +```bash +dotnet add package Aspose.BarCode +``` + +## Etapa 1: Configurar o projeto e importar namespaces + +Crie um novo aplicativo de console e importe os namespaces necessários para a geração de códigos de barras e I/O de arquivos. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Por que isso importa:** Importar `Aspose.BarCode.Generation` lhe dá acesso ao `BarcodeGenerator`. Manter o código dentro de `Main` torna o exemplo autocontido e fácil de executar. + +## Etapa 2: Criar um gerador de código de barras para um DataBar omnidirecional empilhado + +Instancie `BarcodeGenerator` com o tipo `EncodeTypes.DatabarStackedOmniDirectional` e uma string de dados GS1‑128 de exemplo. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Por que isso importa:** O tipo de codificação escolhido produz um DataBar de alta densidade que pode ser lido pela maioria dos scanners modernos. A string de dados segue o formato do Identificador de Aplicação GS1 (01), que é comum para identificadores de produto. + +## Etapa 3: Definir a X‑dimension (largura do módulo) em pixels + +Defina a largura do módulo para controlar o tamanho geral do código de barras sem afetar sua legibilidade. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Por que isso importa:** Uma X‑dimension de 2 pixels gera um código de barras que não é nem pequeno demais para os scanners nem grande demais para os espaços típicos de etiquetas. + +## Etapa 4: Salvar o primeiro PNG com proporção 15 + +Ajuste a proporção do DataBar e, em seguida, salve a imagem como um arquivo PNG. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Por que isso importa:** A proporção controla a relação altura‑largura do DataBar empilhado. Uma proporção de 15 é um padrão comum que equilibra legibilidade e altura da etiqueta. + +## Etapa 5: Alterar a proporção para 30 e salvar um segundo PNG + +Modifique a mesma instância do gerador para usar uma proporção maior e, então, salve a segunda imagem. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Por que isso importa:** Aumentar a proporção estica o código de barras verticalmente, o que pode melhorar a confiabilidade da leitura em dispositivos de baixa resolução ou quando a etiqueta é impressa em mídia estreita. + +## Saída esperada + +A execução do programa cria dois arquivos PNG: + +| Arquivo | Proporção | Dimensões aproximadas (pixels) | +|--------------------------------------|-----------|--------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (largura × altura) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (largura × altura) | + +Ambas as imagens contêm um código de barras DataBar claro e legível que codifica o identificador GS1 `(01)12345678901231`. + +## Perguntas comuns e casos de borda + +### Como alterar outras propriedades visuais? + +Você pode ajustar a cor de primeiro plano, cor de fundo ou adicionar texto legível por humanos através do objeto `generator.Parameters.Barcode`. Por exemplo: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### E se eu precisar de um formato de imagem diferente? + +Substitua `BarCodeImageFormat.Png` por `Jpeg`, `Bmp` ou `Gif`, conforme necessário. PNG continua sendo a melhor escolha para imagens de código de barras sem perdas. + +### A proporção afeta a velocidade de leitura? + +Proporções maiores aumentam a altura do código de barras, o que pode melhorar a confiabilidade da leitura em dispositivos que têm dificuldade com símbolos empilhados curtos. Contudo, códigos de barras extremamente altos podem não caber em etiquetas pequenas, portanto teste com o hardware alvo. + +### Posso gerar vários códigos de barras em um loop? + +Sim. Crie uma nova instância de `BarcodeGenerator` para cada string de dados ou reutilize a mesma instância atualizando `CodeText` e `DataBar.AspectRatio`. Essa abordagem reduz a sobrecarga de alocação de objetos. + +## Dicas profissionais + +- **Reutilize o gerador**: Alterar apenas `CodeText` ou `AspectRatio` evita reinstanciar o objeto, o que acelera o processamento em lote. +- **Valide a saída**: Use um scanner portátil ou um aplicativo móvel para confirmar que o PNG gerado é lido corretamente antes de colocar em produção. +- **Nomeação de arquivos**: Inclua a proporção no nome do arquivo (conforme mostrado) para acompanhar as variações durante os testes. + +## Conclusão + +Agora você sabe como **criar arquivos PNG de código de barras** em C# e, precisamente, **como alterar a proporção** para símbolos DataBar omnidirecionais empilhados. O exemplo completo demonstra inicialização, definição da X‑dimension, manipulação da proporção e salvamento da imagem — tudo em um único programa executável. + +A partir daqui, você pode explorar outros tipos de códigos de barras, experimentar cores ou integrar o gerador a um sistema maior de relatórios ou inventário. Boa codificação! + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam 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. + +- [Criar PNG de código de barras – Proporção do DataMatrix – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Como gerar código de barras Aztec com proporção personalizada usando Aspose.BarCode para .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Como personalizar a proporção do código de barras Codablock F com Aspose.BarCode para .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/portuguese/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..03fa7ea1c --- /dev/null +++ b/barcode/portuguese/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-08-03 +description: Crie PNG de código de barras rapidamente com este guia. Aprenda como + gerar imagem de código de barras usando Aspose.BarCode e gerar código de barras + planetário. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: pt +lastmod: 2026-08-03 +og_description: Crie PNG de código de barras instantaneamente. Este tutorial mostra + como gerar imagem de código de barras e gerar código de barras Planet com Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Criar código de barras PNG em Python – guia completo de programação +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Criar código de barras PNG em Python – guia passo a passo +url: /pt/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar barcode PNG em Python – guia passo a passo + +Se você precisa **criar arquivos barcode PNG** a partir da sua aplicação Python, este tutorial mostra exatamente como fazer. Vamos percorrer **como gerar imagem de barcode** usando Aspose.BarCode e especificamente **gerar barcode planet** com dimensões personalizadas. + +Você aprenderá como instalar a biblioteca, configurar a simbologia Planet, ajustar os parâmetros de tamanho e salvar o resultado como um PNG de alta qualidade. O guia assume conhecimento básico de Python e uma versão recente do Python 3 (3.8 ou superior). Não é necessária experiência prévia com padrões de barcode. + +--- + +## Como criar barcode PNG com Aspose.BarCode + +Esta seção contém as etapas principais necessárias para **criar barcode PNG**. Cada passo inclui um trecho de código, uma explicação do porquê é importante e dicas práticas que você pode aplicar imediatamente. + +### 1. Instalar o pacote Aspose.BarCode + +Aspose provides a pure‑Python package that wraps its .NET core engine. Install it with `pip`: + +```bash +pip install aspose-barcode +``` + +*Por que esta etapa importa:* O pacote fornece a classe `BarcodeGenerator` usada ao longo do exemplo. Instalá‑lo globalmente garante que o interpretador possa localizar o assembly em tempo de execução. + +### 2. Importar classes necessárias + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Dica:* Importe apenas os símbolos que você precisa; isso mantém o namespace limpo e acelera o carregamento do módulo. + +### 3. Criar um gerador de barcode para a simbologia Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Por que isso importa:* `EncodeTypes.Planet` indica ao motor para usar o padrão de barcode Planet, enquanto o segundo argumento fornece os dados a serem codificados. Alterar a simbologia (por exemplo, `EncodeTypes.Code128`) produziria um padrão visual completamente diferente. + +### 4. Definir a dimensão X (largura do módulo) em pixels + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Explicação:* A dimensão X controla a largura da barra estreita. Um valor de 4 pixels produz um barcode moderadamente denso que permanece legível na maioria dos dispositivos. + +### 5. Definir manualmente a altura da barra em pixels + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Por que você pode ajustar isso:* Algumas impressoras de varejo exigem barras mais altas para uma leitura confiável. A altura padrão costuma ser 50 px; aumentá‑la para 100 px melhora a legibilidade sem aumentar drasticamente o tamanho do arquivo. + +### 6. Salvar o barcode gerado como imagem PNG + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Resultado:* Um arquivo PNG chamado **PlanetBarHeight100.png** aparece na pasta `output`. PNG é sem perdas, tornando‑lo ideal para impressão e para incorporação em páginas web. + +### 7. Verificar a saída (opcional) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Dica:* Visualizar a imagem confirma que as dimensões correspondem aos parâmetros definidos. Se o barcode parecer distorcido, revise as configurações da dimensão X ou da altura da barra. + +--- + +## Como gerar imagem de barcode em formato PNG (configurações alternativas) + +Se você precisar de um formato de imagem diferente ou quiser incorporar o barcode em um PDF posteriormente, pode alterar o enum `BarCodeImageFormat`: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Por que isso importa:* PNG preserva cada pixel, o que é crucial para barcodes de alto contraste. JPEG introduz artefatos de compressão que podem interferir na leitura, enquanto BMP oferece compatibilidade com ferramentas mais antigas. + +--- + +## Gerar barcode planet com cores personalizadas (avançado) + +Além do tamanho, você pode personalizar as cores de primeiro plano e de fundo: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Dica prática:* Pares de cores de alto contraste (escuro sobre claro) maximizam a confiabilidade do scanner. Evite usar tons semelhantes para o primeiro plano e o fundo. + +--- + +## Armadilhas comuns e como evitá‑las + +| Sintoma | Causa | Correção | +|---------|-------|-----| +| Barcode não escaneia | Dimensão X muito pequena (≤ 2 px) | Aumente `x_dimension.pixels` para pelo menos 3 px | +| Imagem aparece borrada | PNG salvo com DPI baixo | Use `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` para especificar 300 DPI (se suportado) | +| Exceção `ImportError` | Aspose.BarCode não instalado | Execute `pip install aspose-barcode` no mesmo ambiente do seu script | +| Simbologia errada | Usou `EncodeTypes.Code128` em vez de `EncodeTypes.Planet` | Substitua por `EncodeTypes.Planet` ao criar o gerador | + +--- + +## Recapitulação da solução completa + +Abaixo está o script completo e executável que **cria barcode PNG** do início ao fim: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Executar este script produz um **Planet barcode PNG** nítido que você pode incorporar em HTML, anexar a e‑mails ou imprimir em etiquetas de produto. + +--- + +## Próximos passos e tópicos relacionados + +* **Integrar com Flask ou Django** – sirva o PNG gerado diretamente de um endpoint web. +* **Geração em lote** – percorra uma lista de IDs de produto para criar uma pasta de arquivos barcode PNG. +* **Combinar com geração de PDF** – use `aspose-pdf` para inserir o PNG em uma fatura ou etiqueta de envio. +* **Explorar outras simbologias** – substitua `EncodeTypes.Planet` por `EncodeTypes.QR`, `EncodeTypes.DataMatrix` ou `EncodeTypes.Code128` para atender a diferentes necessidades de negócio. + +Ao dominar as etapas acima, você agora sabe **como gerar imagem de barcode** programaticamente e pode estender o padrão a qualquer padrão de barcode suportado pelo Aspose.BarCode. + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/portuguese/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..b86311f8b --- /dev/null +++ b/barcode/portuguese/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-08-03 +description: Crie rapidamente uma imagem de código de barras postal em C#. Aprenda + a gerar código de barras postal, definir as dimensões do código de barras e gerar + um código Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: pt +lastmod: 2026-08-03 +og_description: Crie imagem de código de barras postal em C# com este tutorial completo; + aprenda a definir as dimensões do código de barras, gerar um código de barras Planet + e produzir códigos de barras RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Crie imagem de código de barras postal em C# – guia completo de programação +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Criar imagem de código de barras postal em C# – guia passo a passo +url: /pt/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar imagem de código de barras postal em C# – guia passo a passo + +Se você precisa **criar imagem de código de barras postal** em C#, este guia mostra exatamente como fazer. Vamos abordar **como gerar código de barras postal**, **como definir dimensões do código de barras** e como **gerar código de barras Planet** para padrões postais comuns. + +Você terminará com dois arquivos PNG prontos para uso — um código de barras Planet e um código de barras RM4SCC — cada um com 100 px de altura. Nenhuma ferramenta adicional é necessária além da biblioteca Aspose.BarCode for .NET. + +## Pré-requisitos + +* .NET 6 SDK ou posterior (o código também funciona com .NET Framework 4.7+) +* Visual Studio 2022 ou qualquer IDE C# +* Pacote NuGet **Aspose.BarCode** (a biblioteca que fornece `BarcodeGenerator`) + +## Etapa 1: Instalar a biblioteca de código de barras + +Abra um terminal na pasta do seu projeto e execute: + +```bash +dotnet add package Aspose.BarCode +``` + +O pacote adiciona o namespace `Aspose.BarCode`, que contém `BarcodeGenerator` e a enumeração `EncodeTypes` necessária para códigos de barras postais. + +## Etapa 2: Definir a pasta de saída + +Criar um caminho de saída confiável evita erros de tempo de execução quando a pasta não existe. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Por que isso importa*: `Directory.CreateDirectory` é idempotente — cria a pasta somente se ela ainda não existir, evitando exceções em execuções subsequentes. + +## Etapa 3: Configurar dimensões comuns do código de barras + +Definir a X‑dimension (largura de uma única barra) e a altura total da barra permite controlar o tamanho visual da imagem gerada. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Como definir dimensões do código de barras**: A propriedade `Parameters.Barcode.XDimension.Pixels` define a largura da barra estreita, enquanto `Parameters.Barcode.BarHeight.Pixels` define a altura total. Ajuste esses valores para atender às especificações do seu serviço de correspondência. + +## Etapa 4: Gerar um código de barras Planet + +Planet é um código de barras postal amplamente usado no Reino Unido. O código a seguir cria um código de barras Planet de 100 px de altura e o salva como PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Por que isso funciona**: `EncodeTypes.Planet` indica ao gerador para usar a simbologia Planet. O método `Save` grava um arquivo PNG no caminho especificado, preservando as dimensões que definimos anteriormente. + +## Etapa 5: Gerar um código de barras RM4SCC + +RM4SCC é o padrão de código de barras postal holandês. O código abaixo espelha o exemplo Planet, demonstrando **como gerar código de barras postal** de um tipo diferente com dimensões idênticas. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Ambos os arquivos PNG agora residem na pasta `Barcodes`. Abrindo-os, você verá códigos de barras limpos, de 100 px de altura, prontos para impressão ou incorporação em documentos. + +## Código-fonte completo + +Abaixo está o programa completo e executável que **cria arquivos de imagem de código de barras postal** para os padrões Planet e RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Saída esperada + +Executar o programa exibe os caminhos dos arquivos e cria dois arquivos PNG: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Cada imagem tem 100 px de altura, com largura de barra estreita de 4 pixels, correspondendo às dimensões que definimos. + +## Dicas práticas e armadilhas comuns + +* **Permissões de pasta** – Se o programa for executado sob uma conta restrita, garanta que a pasta de destino seja gravável. +* **Dimensões diferentes** – Para criar um código de barras mais alto, aumente `barHeightPixels`. Para resolução mais fina, diminua `xDimensionPixels`, mas mantenha ≥ 2 para evitar artefatos de renderização. +* **Outras simbologias postais** – Aspose.BarCode também suporta `EncodeTypes.Postnet` e `EncodeTypes.AustralianPost`. Troque o valor de `EncodeTypes` e mantenha a mesma lógica de dimensões. +* **Formato de imagem** – Use `BarCodeImageFormat.Jpeg` para tamanho de arquivo menor quando a qualidade sem perdas não for necessária. + +## Conclusão + +Agora você sabe como **criar arquivos de imagem de código de barras postal** em C# configurando dimensões, selecionando a simbologia correta e salvando o resultado como PNG. O tutorial abordou **como gerar código de barras postal**, demonstrou **gerar código de barras Planet** e explicou **como definir dimensões do código de barras** para uma saída consistente. + +Em seguida, explore **personalizar cores do código de barras**, adicionar **texto legível por humanos**, ou integrar as imagens em faturas PDF. O mesmo padrão se aplica a qualquer outro tipo de código de barras suportado pelo Aspose.BarCode, permitindo que você estenda esta solução para um fluxo completo de automação postal. + +## 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 de implementação alternativas em seus próprios projetos. + +- [Como gerar código de barras – Tipos de códigos de barras unidimensionais](/barcode/english/net/one-dimensional-barcode-types/) +- [Como gerar código de barras Aztec com proporção personalizada usando Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Como gerar código de barras java – Código de barras Australia Post com Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/portuguese/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..83ef5b287 --- /dev/null +++ b/barcode/portuguese/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-08-03 +description: Como salvar código de barras em C# com um exemplo passo a passo de gerador + de códigos de barras. Aprenda a gerar códigos de barras Planet, definir dimensões + e exportar imagens PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: pt +lastmod: 2026-08-03 +og_description: Como salvar código de barras em C# usando um exemplo de gerador de + código de barras. Este tutorial mostra como gerar códigos de barras Planet, configurar + a dimensão X e exportar arquivos PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Como salvar código de barras em C# – guia passo a passo +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Como salvar código de barras em C# – guia completo de geração de códigos de + barras +url: /pt/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como salvar código de barras em C# – guia completo do gerador de códigos de barras + +Salvar imagens de código de barras em C# é uma necessidade comum quando você precisa incorporar códigos de barras postais em faturas, etiquetas de envio ou etiquetas de inventário. Este guia orienta você através de um fluxo de trabalho prático de **c# barcode generator**, desde a criação de um código de barras Planet até a exportação de arquivos PNG com barras preenchidas e vazias. + +Você aprenderá como definir a largura das barras, alternar barras preenchidas e lidar com pastas de saída de forma confiável. Ao final do tutorial, você terá um **barcode generator example** totalmente funcional que pode copiar para qualquer projeto .NET. + +## O que você precisará + +- .NET 6.0 SDK ou posterior (o exemplo funciona com .NET Core e .NET Framework) +- Visual Studio 2022 ou qualquer IDE compatível com C# +- O pacote NuGet **Aspose.BarCode** (ou outra biblioteca que suporte `EncodeTypes.Planet`). Instale‑o com: + +```bash +dotnet add package Aspose.BarCode +``` + +A biblioteca fornece a classe `BarcodeGenerator` usada ao longo deste tutorial. + +## Configurando o ambiente de desenvolvimento + +Crie um novo projeto de console e adicione o namespace necessário: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +O namespace `System.IO` nos fornece `Directory.CreateDirectory`, que garante que a pasta de saída exista antes de tentarmos gravar arquivos. + +## Como salvar imagens de código de barras com o gerador de códigos de barras C# + +O núcleo da solução é um pequeno conjunto de etapas que configuram um **Planet barcode** e então persistem a imagem no disco. As seções a seguir dividem o processo em partes manejáveis. + +### Etapa 1: Definir a pasta de saída + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Por quê?** +Definir um caminho fixo pode causar `DirectoryNotFoundException` em máquinas onde a pasta não existe. `CreateDirectory` é idempotente — cria o diretório apenas se ele estiver ausente, tornando o código seguro para execuções repetidas. + +### Etapa 2: Criar um gerador de código de barras Planet (barras preenchidas) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Por quê?** +`EncodeTypes.Planet` indica à biblioteca que ela deve gerar um código de barras postal Planet, amplamente usado pelos serviços de correio. A string `"123456"` é a carga de exemplo; substitua‑a por quaisquer dados numéricos exigidos pela lógica de negócios. + +### Etapa 3: Configurar a largura da barra (dimensão X) e manter as barras preenchidas padrão + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Por quê?** +A dimensão X controla a largura física de cada barra. Um valor de `4` pixels produz um código de barras legível em impressoras padrão de 300 dpi. Manter `FilledBars` como `true` (o padrão) gera a aparência clássica de barra sólida. + +### Etapa 4: Salvar a imagem do código de barras com barras preenchidas + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Por quê?** +Salvar como PNG preserva a qualidade de imagem sem perdas, o que é importante para a precisão da leitura. O método `Save` cria automaticamente o arquivo de imagem; você só precisa fornecer o caminho completo e o formato desejado. + +### Etapa 5: Criar um segundo gerador para a versão de barras vazias + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Criar uma nova instância garante que as alterações feitas para a versão de barras vazias não afetem a imagem de barras preenchidas já salva. + +### Etapa 6: Desativar barras preenchidas mantendo a mesma dimensão X + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Por quê?** +Definir `FilledBars = false` renderiza o código de barras apenas com o contorno de cada barra, o que alguns padrões postais exigem para verificação visual. + +### Etapa 7: Salvar a imagem do código de barras com barras vazias + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Agora você tem dois arquivos PNG — um com barras preenchidas e outro com barras vazias — prontos para inclusão em PDFs, e‑mails HTML ou etiquetas impressas. + +## Programa completo executável + +Abaixo está o código completo que você pode copiar para `Program.cs`. Ele compila e executa sem modificações (desde que o pacote Aspose.BarCode esteja instalado). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Saída esperada + +Executar o programa imprime duas linhas semelhantes a: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Abra a pasta `Barcodes` e você verá os dois arquivos PNG. Ambas as imagens podem ser abertas em qualquer visualizador de imagens ou incorporadas diretamente em documentos. + +![exemplo de como salvar código de barras](barcode-example.png){: .align-center alt="exemplo de como salvar código de barras"} + +## Variações comuns e casos de borda + +| Cenário | Ajuste | +|----------|------------| +| **Different image format** | Change `BarCodeImageFormat.Png` to `Jpeg`, `Gif`, or `Bmp` as needed. | +| **Custom output size** | Use `filled.Parameters.Image.Width` and `Height` to force a specific pixel dimension. | +| **Dynamic data** | Replace the static `"123456"` with a variable that holds order numbers, tracking IDs, etc. | +| **Non‑existent folder** | `Directory.CreateDirectory` already handles missing directories; no extra code required. | +| **High‑resolution printing** | Increase `XDimension.Pixels` to 6–8 for 600 dpi printers, but verify scanner compatibility. | + +**Dica profissional:** Se precisar gerar muitos códigos de barras em um loop, reutilize uma única instância `BarcodeGenerator` e altere apenas a propriedade `CodeText` antes de cada `Save`. Isso reduz a sobrecarga de alocação de objetos. + +## Como gerar código de barras para outros padrões + +O mesmo padrão funciona para outros `EncodeTypes` como `Code128`, `QR` ou `DataMatrix`. Basta substituir `EncodeTypes.Planet` pelo tipo desejado e ajustar quaisquer parâmetros específicos do tipo (por exemplo, `QRCodeVersion`). + +## 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 de implementação alternativas em seus próprios projetos. + +- [Como salvar PNG usando DataMatrix C40 com Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Como gerar códigos de barras DataMatrix (ECC 200) com Aspose.BarCode para .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Como gerar código de barras – Configuração Code 39 com Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/russian/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..6a1596d71 --- /dev/null +++ b/barcode/russian/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-08-03 +description: Учебник по генерации штрихкодов на C#, показывающий, как создать штрихкод + Planet с помощью Aspose.BarCode, установить X‑размер и сохранить в виде PNG‑изображений. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: ru +lastmod: 2026-08-03 +og_description: Учебник по генератору штрих‑кодов на C# пошагово покажет, как создать + штрих‑код Planet, настроить X‑размер и сохранить его в формате PNG с помощью Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Генератор штрих‑кодов C# – создаём штрих‑код Planet шаг за шагом +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Генератор штрихкодов C# – пример создания штрихкода Planet и RM4SCC +url: /ru/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Генератор штрих‑кодов C# – пример создания штрих‑кода Planet и RM4SCC + +Если вам нужен **barcode generator C#**, способный создавать почтовые символы, это руководство покажет, как **create Planet barcode** изображения с помощью Aspose.BarCode. Вы увидите, как настроить X‑dimension, сгенерировать соответствующий штрих‑код RM4SCC и сохранить оба в виде PNG‑файлов — всё в нескольких лаконичных шагах. + +В учебнике описано всё, что необходимо для запуска кода на .NET 6 или новее, объясняется, почему важна каждая настройка, и указаны распространённые подводные камни, такие как неверная ширина модуля или отсутствие прав на запись в каталог. К концу вы получите два готовых к печати изображения штрих‑кодов, соответствующих стандартам Planet и RM4SCC. + +## Prerequisites + +Прежде чем начать, убедитесь, что у вас есть: + +* .NET 6 SDK (или любая версия .NET, поддерживаемая Aspose.BarCode) +* Visual Studio 2022 или любой другой предпочитаемый IDE для C# +* NuGet‑ссылка на **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Права на запись в папку, где планируется сохранять PNG‑файлы + +Дополнительные внешние сервисы не требуются; библиотека выполняет всё кодирование локально. + +## Step 1: Initialise the barcode generator C# object + +Первая задача — создать экземпляр `BarcodeGenerator`. Конструктор принимает тип штрих‑кода (`EncodeTypes.Planet`) и данные для кодирования. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Почему этот шаг?* +`BarcodeGenerator` — точка входа для любого генерируемого штрих‑кода. Выбор `EncodeTypes.Planet` сообщает библиотеке использовать спецификацию ISO/IEC 24723, применяемую многими почтовыми службами. + +## Step 2: Set the X‑dimension (module width) for the Planet barcode + +X‑dimension определяет ширину одного модуля штрих‑кода (самой маленькой полоски или пробела). Значение **4 пикселя** хорошо подходит для большинства принтеров этикеток. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Почему это важно* +Если модуль слишком узкий, штрих‑код может стать нечитаемым; если слишком широкий — размер этикетки будет избыточным. Настройка `Pixels` позволяет точно подобрать ширину штрих‑кода под разрешение вашего принтера. + +## Step 3: Save the Planet barcode as a PNG image + +Aspose.BarCode автоматически рассчитывает высоту штрих‑кода в зависимости от выбранной символьной системы, поэтому вам нужно указать только путь к файлу и формат. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Подсказка* +Замените `YOUR_DIRECTORY` на абсолютный или относительный путь, существующий на вашем компьютере. Если каталог не существует, метод `Save` выбросит `DirectoryNotFoundException`. + +**Ожидаемый результат** – PNG‑файл, похожий на иллюстрацию ниже (изображение не отображается, но вы увидите классический штрих‑код Planet с числовой нагрузкой `123456`). + +## Step 4: Initialise a second generator for the RM4SCC barcode + +Во многих почтовых системах требуется наличие одновременно штрих‑кодов Planet и RM4SCC. Создайте новый экземпляр `BarcodeGenerator` для символьной системы RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Почему отдельный экземпляр?* +Каждая символьная система имеет собственный набор параметров. Повторное использование того же генератора может непреднамеренно перенести настройки (например, X‑dimension), которые не оптимальны для второго штрих‑кода. + +## Step 5: Configure the X‑dimension for the RM4SCC barcode + +RM4SCC также учитывает настройку X‑dimension, поэтому применяем ту же ширину в пикселях для визуального соответствия. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +Если нужен более высокий штрих‑код (например, для больших этикеток), можно также задать `Height.Pixels`. Оставив параметр пустым, библиотека автоматически вычислит оптимальную высоту. + +## Step 6: Save the RM4SCC barcode as a PNG image + +Наконец, сохраняем штрих‑код RM4SCC на диск. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Теперь у вас есть два PNG‑файла — `PostalPlanetBarHeightNone.png` и `PostalRM4SCCBarHeightNone.png` — которые можно вставлять в почтовые ярлыки, печатать на конвертах или отправлять в стороннюю типографию. + +## Optional: Adjusting height or using other image formats + +Если ваш процесс требует конкретной высоты штрих‑кода или другого формата изображения (например, JPEG или BMP), можно изменить параметры перед вызовом `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Edge case** – При установке пользовательской высоты убедитесь, что значение соответствует минимальной высоте, требуемой ISO‑стандартом; иначе штрих‑код может не пройти проверку. + +## Common pitfalls and how to avoid them + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| `DirectoryNotFoundException` | Целевой каталог не существует или указано неверное имя. | Сначала создайте каталог или используйте `Path.Combine` с `Environment.CurrentDirectory`. | +| Штрих‑код нечитаем на принтерах с низким разрешением | X‑dimension слишком мал для DPI принтера. | Увеличьте `XDimension.Pixels` до 5 – 6 для принтеров 203 dpi, либо протестируйте на образце этикетки. | +| Неправильный тип символьной системы | Передан `EncodeTypes.Code128` вместо `EncodeTypes.Planet`. | Проверьте, что значение `EncodeTypes` соответствует требуемому почтовому стандарту. | +| Null reference на `Parameters` | Используется более старая версия Aspose.BarCode с отличающимся API. | Обновите до последней версии NuGet‑пакета (v23.12 или новее). | + +## Full runnable example + +Ниже представлена полная программа, которую можно скопировать, вставить и запустить. В ней есть `using`‑директивы, обработка ошибок и комментарии, поясняющие каждую строку. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Запуск программы создаст папку `Barcodes` рядом с исполняемым файлом и поместит в неё два PNG‑файла. Откройте их в любом просмотрщике изображений, чтобы убедиться в корректности вывода. + +## Conclusion + +Теперь у вас есть **barcode generator C#** решение, которое может **create Planet barcode** изображения, настроить X‑dimension для оптимальной печати и создать соответствующий штрих‑код RM4SCC — всё в паре строк кода. Подход работает с .NET 6+, требует только NuGet‑пакет Aspose.BarCode и может быть расширен другими символьными системами, такими как Code128, QR или DataMatrix, заменой значения `EncodeTypes`. + +### What’s next? + +* Поэкспериментируйте с различными значениями `XDimension.Pixels`, чтобы подобрать их под DPI вашего принтера. +* Генерируйте штрих‑коды в других форматах (PDF, SVG), изменив значение перечисления `BarCodeImageFormat`. +* Объедините два PNG‑файла в один ярлык с помощью графической библиотеки, например **SkiaSharp**. +* Изучите полный API Aspose.BarCode для продвинутых функций, таких как проверка контрольных сумм или пользовательские шрифты. + +Не стесняйтесь адаптировать код для пакетной обработки или интегрировать его в веб‑службу ASP.NET Core, которая будет возвращать изображения штрих‑кодов по запросу. Приятного кодинга! + +## What Should You Learn Next? + +Следующие учебные материалы охватывают близкие темы, расширяющие техники, продемонстрированные в этом руководстве. Каждый ресурс содержит полностью рабочие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/russian/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..c607fc045 --- /dev/null +++ b/barcode/russian/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: Учебник по генерации штрихкодов на C# показывает, как создать изображение + штрихкода с помощью Aspose.BarCode, задать столбцы и строки и сохранить PNG‑файлы + для DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: ru +lastmod: 2026-08-03 +og_description: Учебник по генерации штрихкодов на C# объясняет, как создавать изображение + штрихкода с помощью Aspose.BarCode, настраивать столбцы и строки DataBar Expanded + Stacked и сохранять файлы PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Генератор штрихкодов C# – пошаговое руководство по созданию изображения + штрихкода +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Генератор штрихкодов C# – генерировать изображение штрихкода +url: /ru/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – generate barcode image + +Если вам нужен barcode generator C# , способный генерировать изображение штрих‑кода для DataBar Expanded Stacked, это руководство проведёт вас через весь процесс. Вы узнаете, как настроить параметры столбцов и строк, сохранить результат в PNG и адаптировать код для других символогий. + +Программная генерация изображений штрих‑кодов устраняет ручные шаги и обеспечивает единообразие в счетах, транспортных этикетках и системах учёта. В этом учебнике рассматривается всё необходимое — от настройки проекта до полного исходного кода, чтобы вы могли сразу запустить пример. + +## Prerequisites + +Прежде чем начать, убедитесь, что у вас есть: + +* .NET 6.0 или более поздняя версия +* IDE, например Visual Studio 2022 (подойдёт любой редактор, поддерживающий C#) +* Лицензия на **Aspose.BarCode for .NET** — бесплатная оценочная версия подходит для тестирования +* Базовые знания синтаксиса C# + +Если чего‑то не хватает, установите .NET SDK с сайта dotnet.microsoft.com и получите пакет Aspose.BarCode NuGet с помощью: + +```bash +dotnet add package Aspose.BarCode +``` + +## Step 1: Create a barcode generator C# project + +Создайте новое консольное приложение и добавьте необходимые директивы `using`: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +Класс `BarcodeGenerator` является ядром API barcode generator C#. Он принимает тип символогии и текст для кодирования. + +## Step 2: Generate a DataBar Expanded Stacked barcode and set columns + +В первом примере создаётся штрих‑код с четырьмя столбцами. Изменение свойства `Columns` меняет визуальную плотность символогии DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Почему это важно:** Количество столбцов влияет на объём данных, которые можно разместить в компактном пространстве. Установка значения 4 даёт более широкий штрих‑код, остающийся читаемым большинством сканеров. + +## Step 3: Generate a barcode with custom row count + +Во втором примере показано, как управлять вертикальной компоновкой, задавая свойство `Rows`. Конфигурация из трёх строк полезна, когда нужен более высокий штрих‑код при ограниченном горизонтальном пространстве. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Почему это важно:** Регулировка количества строк позволяет разместить штрих‑код в узкой колонке, сохраняя читаемость. barcode generator C# автоматически пересчитывает размер модуля, чтобы соответствовать спецификации. + +## Step 4: Full, runnable example + +Ниже приведена автономная программа, объединяющая предыдущие шаги. Скопируйте код в `Program.cs`, замените `YOUR_DIRECTORY` на существующий путь к папке и запустите приложение. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Expected output + +При запуске программы в целевом каталоге появятся два PNG‑файла: + +* **DatabarCols4.png** — штрих‑код DataBar Expanded Stacked с четырьмя столбцами +* **DatabarRows3.png** — те же данные, закодированные в три строки + +Откройте изображения в любом просмотрщике; они показывают чёткие, сканируемые штрих‑коды, готовые к печати или встраиванию в PDF‑файлы. + +## How to generate barcode image with custom dimensions + +Если нужен конкретный размер изображения, задайте свойства `ImageHeight` и `ImageWidth` перед вызовом `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Изменение размеров не влияет на закодированные данные; оно лишь масштабирует визуальное представление. Эта техника полезна при интеграции штрих‑кодов в UI‑компоненты с фиксированными ограничениями макета. + +## Common pitfalls and pro tips + +* **Path separators:** Используйте дословные строки (`@"C:\Path\file.png"`) или `Path.Combine`, чтобы избежать проблем с экранированием символов в Windows. +* **License enforcement:** Без действующей лицензии сгенерированные изображения содержат водяной знак. Примените лицензию сразу после запуска приложения: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Encoding limits:** DataBar Expanded Stacked поддерживает до 74 цифровых символов. Превышение этого лимита вызывает исключение. Проверяйте длину входных данных перед созданием генератора. +* **Performance:** Повторное использование одного экземпляра `BarcodeGenerator` для нескольких сохранений снижает расход памяти. Меняйте свойства `Rows` или `Columns` между сохранениями только если закодированный текст остаётся тем же. + +## Next steps + +Теперь, когда вы умеете генерировать изображения штрих‑кодов с помощью barcode generator C#, можете изучить следующее: + +* **Different symbologies** — попробуйте `EncodeTypes.QR`, `EncodeTypes.Code128` или `EncodeTypes.Pdf417`. +* **Color customization** — задайте `Parameters.Barcode.ForeColor` и `BackColor`, чтобы соответствовать фирменному стилю. +* **Embedding in PDFs** — объедините сгенерированный PNG с Aspose.PDF для создания печатных документов. + +Эти расширения позволят построить полнофункциональное решение штрих‑кодов для инвентаризации, логистики или розничных приложений. + +--- + + +## What Should You Learn Next? + +Следующие учебники охватывают близко связанные темы, которые развивают техники, продемонстрированные в этом руководстве. Каждый ресурс содержит полностью рабочие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности 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 Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/russian/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..663fb5ff4 --- /dev/null +++ b/barcode/russian/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-08-03 +description: Пример генератора штрихкодов на C#, показывающий, как установить ширину, + как изменить высоту и как сгенерировать изображение штрихкода. Следуйте пошаговым + инструкциям. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: ru +lastmod: 2026-08-03 +og_description: Пример генератора штрихкодов демонстрирует установку ширины X‑измерения, + изменение высоты штриха и создание изображения штрихкода на C#. Следуйте инструкциям, + чтобы создать PNG‑файлы. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Пример генератора штрихкодов – руководство по ширине и высоте в C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Пример генератора штрихкода на C# – установка ширины и высоты +url: /ru/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Пример генератора штрихкодов на C# – установка ширины и высоты + +Если вам нужен **пример генератора штрихкодов** на C#, это руководство покажет, как установить ширину X‑dimension, как изменить высоту штриха и как сгенерировать файл изображения штрихкода. Вы увидите полностью готовую программу, которая создает два PNG‑файла с разной высотой. + +Типичный сценарий — создание этикеток продуктов, где размер штрихкода должен соответствовать требованиям сканера. К концу этого руководства вы сможете программно регулировать параметры ширины и высоты и сохранять результат в виде PNG‑изображения. + +## Prerequisites + +Перед началом убедитесь, что у вас есть: + +* .NET 6 (или новее) установлен – код нацелен на .NET 6 SDK. +* Библиотека штрихкодов, поддерживающая `EncodeTypes.DatabarOmniDirectional`. В примере используется **Aspose.BarCode for .NET**, но любая библиотека с аналогичными свойствами работает так же. +* IDE или редактор (Visual Studio, VS Code, Rider) для компиляции и запуска программы. +* Разрешение на запись в каталог, где будут сохраняться PNG‑файлы. + +> **Совет:** Создайте папку `Barcodes` в корне проекта и используйте `Path.Combine` для ссылки, чтобы избежать жёстко заданных абсолютных путей. + +## Barcode generator example: initialize and configure + +Первый шаг — создать экземпляр `BarcodeGenerator` с нужной символьностью и строкой данных. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +Перечисление `EncodeTypes.DatabarOmniDirectional` выбирает символьность Databar Omni‑directional, а строка данных в формате GS1 `(01)12345678901231` представляет типичное значение GTIN‑14. Одноразовая инициализация генератора позволяет переиспользовать один объект для создания нескольких изображений. + +## How to set width (X‑dimension) + +X‑dimension управляет шириной модуля штрихкода. Установка значения 2 пикселя делает каждый узкий штрих шириной 2 пикселя, что часто требуется при печати высокой плотности. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Почему это важно: если ширина слишком мала, сканеры могут не различать отдельные штрихи; если она слишком велика, штрихкод может выйти за пределы этикетки. Подберите значение пикселей в соответствии с DPI принтера и требуемым размером этикетки. + +## How to change height + +Высота штриха определяет, насколько высокими будут штрихи. В примере создаются два изображения: одно с высотой 30 пикселей, другое — 60 пикселей. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Свойство `BarHeight.Pixels` напрямую влияет на визуальную высоту штрихов. Изменяя его между сохранениями, вы можете генерировать несколько вариантов из одного и того же набора данных без повторного создания генератора. + +### Expected output + +Запуск программы создаёт два PNG‑файла в папке `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – штрихи высотой 30 пикселей. +* `DatabarBarHeight60Pixels.png` – штрихи высотой 60 пикселей. + +Оба изображения имеют одинаковую ширину (определяемую X‑dimension) и кодируют одинаковые данные GTIN‑14. + +![Два PNG‑файла штрихкода с разной высотой, сгенерированные кодом C#](barcode-example.png "Пример генератора штрихкодов, показывающий вариации высоты") + +*Текст alt‑изображения выше содержит основной ключевой запрос для доступности и SEO.* + +## How to generate barcode image in C# + +Метод `Save` осуществляет преобразование данных штрихкода в файл изображения. Вы можете выбрать другие форматы (JPEG, BMP, SVG), передав другое значение перечисления `BarCodeImageFormat`. В примере используется PNG, поскольку он сохраняет без потерь и широко поддерживается. + +Если вам нужно встроить штрихкод непосредственно в PDF или веб‑страницу, получите изображение как `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Этот подход устраняет необходимость во временных файлах и полезен для сервисов с высокой пропускной способностью. + +## Common variations and edge cases + +| Ситуация | Корректировка | +|-----------|------------| +| **Разные символьные наборы** | Замените `EncodeTypes.DatabarOmniDirectional` другим значением перечисления (например, `EncodeTypes.Code128`). | +| **Очень маленькие этикетки** | Уменьшите `XDimension.Pixels` до 1 пикселя, но проверьте читаемость сканером. | +| **Печать высокого разрешения** | Увеличьте как X‑dimension, так и высоту штриха пропорционально (например, ширина 4 px, высота 80 px). | +| **Динамические данные** | Передавайте строку данных во время выполнения, возможно из записи базы данных. | +| **Пакетная генерация** | Итерируйте коллекцию строк данных, переиспользуя один объект `BarcodeGenerator`, обновляя `generator.Text`. | + +Когда вы сталкиваетесь с исключением, например `ArgumentOutOfRangeException`, проверьте, что значения пикселей являются положительными целыми числами и что каталог вывода существует. + +## Full source code recap + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Скопируйте код в новый консольный проект, восстановите NuGet‑пакет Aspose.BarCode (`dotnet add package Aspose.BarCode`) и выполните `dotnet run`. Вы увидите сообщения в консоли, подтверждающие сохранённые файлы. + +## Conclusion + +Этот **пример генератора штрихкодов** демонстрирует, как установить ширину, как изменить высоту и как сгенерировать изображение штрихкода на C#. Регулируя `XDimension.Pixels` и `BarHeight.Pixels`, вы контролируете визуальный размер штрихкода, а метод `Save` записывает результат в PNG‑файлы. Экспериментируйте с различными символьностями, форматами вывода и строками данных, чтобы подобрать оптимальное решение для вашего приложения. + +**Следующие шаги** + +* Изучите **как генерировать штрихкоды** в других форматах изображений (SVG, JPEG) для веб‑использования. +* Узнайте **create barcode image c#** для конечных точек ASP.NET Core, которые возвращают PNG напрямую в браузер. +* Скомбинируйте этот код с библиотекой генерации PDF, чтобы внедрять штрихкоды в счета‑фактуры или транспортные этикетки. + +Не стесняйтесь адаптировать пример, делиться результатами или задавать вопросы в комментариях. Приятного кодинга! + +## Что вам следует изучить дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Как генерировать штрихкоды – одноразмерные типы штрихкодов](/barcode/english/net/one-dimensional-barcode-types/) +- [Как установить границу для настройки штрихкода ITF-14](/barcode/english/net/itf-14-barcode-customization/) +- [Как генерировать DataMatrix штрихкоды (ECC 200) с Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/russian/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..bf3d3fb7d --- /dev/null +++ b/barcode/russian/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-08-03 +description: Создайте PNG‑изображение штрихкода на C# и узнайте, как изменить соотношение + сторон для изображений DataBar. Следуйте этому полному примеру с кодом и советами. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: ru +lastmod: 2026-08-03 +og_description: Создайте PNG‑изображение штрих‑кода на C# и узнайте, как изменить + соотношение сторон для штрих‑кодов DataBar. Это руководство предоставляет готовый + к запуску код и практические советы. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Создание PNG‑штрихкода в C# – полный пример с контролем соотношения сторон +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Создание PNG‑штрихкода в C# – пошаговое руководство +url: /ru/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание PNG‑изображения штрих‑кода в C# – пошаговое руководство + +Если вам нужно **создать PNG‑изображение штрих‑кода** в C#, это руководство покажет, как это сделать. Вы сгенерируете многослойный всенаправленный DataBar‑штрих‑код, сохраните его в файл PNG и узнаете **как изменить соотношение сторон**, чтобы адаптировать его к различным условиям сканирования. + +В руководстве изложены все необходимые шаги: требуемые пакеты, полностью готовая к запуску программа и объяснения, почему каждое из настроек важно. По завершении у вас будет два PNG‑файла — один с соотношением сторон 15, другой 30 — готовые к тестированию или использованию в продакшене. + +## Требования + +Прежде чем начать, убедитесь, что у вас есть: + +- .NET 6.0 SDK или более новая версия +- Visual Studio 2022 (или любая другая IDE для C#) +- NuGet‑ссылка на **Aspose.BarCode** (библиотека, предоставляющая `BarcodeGenerator`) +- Права записи в каталог, куда будут сохраняться PNG‑файлы + +Пакет Aspose.BarCode можно добавить следующей командой: + +```bash +dotnet add package Aspose.BarCode +``` + +## Шаг 1: Создание проекта и импорт пространств имён + +Создайте новое консольное приложение и импортируйте пространства имён, необходимые для генерации штрих‑кода и работы с файловой системой. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Почему это важно:** Импорт `Aspose.BarCode.Generation` даёт доступ к `BarcodeGenerator`. Размещение кода внутри `Main` делает пример автономным и простым для запуска. + +## Шаг 2: Создание генератора штрих‑кода для многослойного всенаправленного DataBar + +Создайте экземпляр `BarcodeGenerator` с типом `EncodeTypes.DatabarStackedOmniDirectional` и примером строки данных GS1‑128. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Почему это важно:** Выбранный тип кодирования генерирует высокоплотный DataBar, который может считываться большинством современных сканеров. Строка данных соответствует формату идентификатора GS1 Application Identifier (01), часто используемому для обозначения товаров. + +## Шаг 3: Задание X‑размера (ширины модуля) в пикселях + +Установите ширину модуля, чтобы контролировать общий размер штрих‑кода без влияния на его читаемость. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Почему это важно:** X‑размер 2 пикселя даёт штрих‑код, который не слишком мал для сканеров и не слишком велик для типовых этикеток. + +## Шаг 4: Сохранение первого PNG с соотношением сторон 15 + +Отрегулируйте соотношение сторон DataBar, затем сохраните изображение в файл PNG. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Почему это важно:** Соотношение сторон определяет соотношение высоты к ширине у многослойного DataBar. Значение 15 — распространённый параметр по умолчанию, обеспечивающий баланс между читаемостью и высотой этикетки. + +## Шаг 5: Изменение соотношения сторон на 30 и сохранение второго PNG + +Измените тот же экземпляр генератора, задав более высокое соотношение сторон, затем сохраните второе изображение. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Почему это важно:** Увеличение соотношения сторон растягивает штрих‑код по вертикали, что может повысить надёжность сканирования на устройствах с низким разрешением или при печати на узких носителях. + +## Ожидаемый результат + +Запуск программы создаёт два PNG‑файла: + +| Файл | Соотношение сторон | Приблизительные размеры (пиксели) | +|------------------------------------|--------------------|-----------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (ширина × высота) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (ширина × высота) | + +Оба изображения содержат чёткий, сканируемый DataBar‑штрих‑код, кодирующий GS1‑идентификатор `(01)12345678901231`. + +## Часто задаваемые вопросы и особые случаи + +### Как изменить другие визуальные свойства? + +Можно настроить цвет переднего плана, цвет фона или добавить человекочитаемый текст через объект `generator.Parameters.Barcode`. Например: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Что делать, если нужен другой формат изображения? + +Замените `BarCodeImageFormat.Png` на `Jpeg`, `Bmp` или `Gif` по необходимости. PNG остаётся лучшим выбором для без потерь изображений штрих‑кодов. + +### Влияет ли соотношение сторон на скорость сканирования? + +Более высокие соотношения увеличивают высоту штрих‑кода, что может улучшить надёжность сканирования на устройствах, испытывающих трудности с короткими многослойными символами. Однако чрезмерно высокие штрих‑коды могут не помещаться на небольших этикетках, поэтому тестируйте их с целевым оборудованием. + +### Можно ли генерировать несколько штрих‑кодов в цикле? + +Да. Создавайте новый экземпляр `BarcodeGenerator` для каждой строки данных или переиспользуйте один экземпляр, обновляя свойства `CodeText` и `DataBar.AspectRatio`. Такой подход уменьшает накладные расходы на создание объектов. + +## Полезные советы + +- **Переиспользуйте генератор**: меняя только `CodeText` или `AspectRatio`, вы избегаете повторного создания объекта, что ускоряет пакетную обработку. +- **Проверяйте результат**: используйте ручной сканер или мобильное приложение, чтобы убедиться, что сгенерированный PNG читается корректно перед выпуском в продакшн. +- **Именование файлов**: включайте соотношение сторон в имя файла (как показано), чтобы легко отслеживать варианты во время тестирования. + +## Заключение + +Теперь вы знаете, как **создавать PNG‑изображения штрих‑кодов** в C# и точно **изменять соотношение сторон** для многослойных всенаправленных DataBar‑символов. Полный пример демонстрирует инициализацию, настройку X‑размера, манипуляцию соотношением сторон и сохранение изображения — всё в одной готовой к запуску программе. + +Далее вы можете изучать другие типы штрих‑кодов, экспериментировать с цветами или интегрировать генератор в более крупные системы отчётности или учёта. Приятного кодинга! + +## Что изучать дальше? + +Следующие руководства охватывают смежные темы, расширяющие техники, продемонстрированные в этом пособии. Каждый ресурс содержит полностью рабочие примеры кода с пошаговыми объяснениями, помогающие освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/russian/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..714237447 --- /dev/null +++ b/barcode/russian/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-08-03 +description: Быстро создавайте PNG‑штрихкоды с помощью этого руководства. Узнайте, + как генерировать изображение штрихкода с помощью Aspose.BarCode и создавать planet‑штрихкод. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: ru +lastmod: 2026-08-03 +og_description: Создавайте PNG‑изображения штрихкода мгновенно. В этом руководстве + показано, как генерировать изображение штрихкода и создавать planet‑штрихкод с помощью + Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Создание PNG‑штрихкода в Python — полное руководство по программированию +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Создание PNG‑штрихкода в Python – пошаговое руководство +url: /ru/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание PNG штрих‑кода в Python – пошаговое руководство + +Если вам нужно **создавать PNG‑файлы штрих‑кода** из вашего Python‑приложения, этот учебник покажет, как это сделать. Мы пройдемся по **созданию изображения штрих‑кода** с помощью Aspose.BarCode и конкретно **создадим штрих‑код Planet** с пользовательскими размерами. + +Вы узнаете, как установить библиотеку, настроить симбологию Planet, отрегулировать параметры размера и сохранить результат в виде PNG высокого качества. Руководство предполагает базовые знания Python и современную версию Python 3 (3.8 или новее). Предыдущий опыт работы со стандартами штрих‑кодов не требуется. + +--- + +## Как создать PNG штрих‑кода с помощью Aspose.BarCode + +Этот раздел содержит основные шаги, необходимые для **создания PNG штрих‑кода**. Каждый шаг включает фрагмент кода, объяснение его важности и практические советы, которые можно применить сразу. + +### 1. Установите пакет Aspose.BarCode + +Aspose предоставляет чисто‑Python пакет, который оборачивает его .NET‑ядро. Установите его с помощью `pip`: + +```bash +pip install aspose-barcode +``` + +*Почему этот шаг важен:* Пакет поставляет класс `BarcodeGenerator`, используемый во всём примере. Установка его глобально гарантирует, что интерпретатор сможет найти сборку во время выполнения. + +### 2. Импортируйте необходимые классы + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Совет:* Импортируйте только те символы, которые действительно нужны; так пространство имён остаётся чистым, а загрузка модулей ускоряется. + +### 3. Создайте генератор штрих‑кода для симбологии Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Почему это важно:* `EncodeTypes.Planet` указывает движку использовать стандарт штрих‑кода Planet, а второй аргумент передаёт данные для кодирования. Замена симбологии (например, `EncodeTypes.Code128`) приведёт к полностью другому визуальному паттерну. + +### 4. Установите X‑размер (ширина модуля) в пикселях + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Объяснение:* X‑размер контролирует ширину узкой полосы. Значение 4 пикселя даёт умеренно плотный штрих‑код, который остаётся считываемым большинством устройств. + +### 5. Задайте ручную высоту полосы в пикселях + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Зачем это может понадобиться:* Некоторые розничные принтеры требуют более высоких полос для надёжного сканирования. Высота по умолчанию обычно 50 px; увеличение её до 100 px улучшает читаемость без значительного роста размера файла. + +### 6. Сохраните сгенерированный штрих‑код как PNG‑изображение + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Результат:* В папке `output` появляется файл PNG с именем **PlanetBarHeight100.png**. PNG — формат без потерь, что делает его идеальным для печати и встраивания в веб‑страницы. + +### 7. Проверьте результат (по желанию) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Совет:* Просмотр изображения подтверждает, что размеры соответствуют заданным параметрам. Если штрих‑код выглядит искажённым, проверьте настройки X‑размера или высоты полосы. + +--- + +## Как сгенерировать изображение штрих‑кода в формате PNG (альтернативные настройки) + +Если нужен другой формат изображения или планируется последующее встраивание штрих‑кода в PDF, можно изменить перечисление `BarCodeImageFormat`: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Почему это важно:* PNG сохраняет каждый пиксель, что критично для штрих‑кодов с высоким контрастом. JPEG вводит артефакты сжатия, которые могут мешать сканированию, а BMP обеспечивает совместимость со старыми инструментами. + +--- + +## Генерация штрих‑кода Planet с пользовательскими цветами (расширенный уровень) + +Помимо размеров, можно настроить цвета переднего плана и фона: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Практический совет:* Пары цветов с высоким контрастом (тёмный на светлом) максимизируют надёжность сканера. Избегайте использования схожих оттенков для переднего плана и фона. + +--- + +## Распространённые ошибки и как их избежать + +| Признак | Причина | Решение | +|---------|---------|---------| +| Штрих‑код не считывается | X‑размер слишком мал (≤ 2 px) | Увеличьте `x_dimension.pixels` минимум до 3 px | +| Изображение размыто | PNG сохранён с низким DPI | Используйте `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` для указания 300 DPI (если поддерживается) | +| Исключение `ImportError` | Aspose.BarCode не установлен | Выполните `pip install aspose-barcode` в той же среде, где находится ваш скрипт | +| Неправильная симбология | Был использован `EncodeTypes.Code128` вместо `EncodeTypes.Planet` | Замените на `EncodeTypes.Planet` при создании генератора | + +--- + +## Итоги полного решения + +Ниже представлен полностью готовый к запуску скрипт, который **создаёт PNG штрих‑кода** от начала до конца: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Запуск этого скрипта создаёт чёткий **PNG штрих‑код Planet**, который можно встраивать в HTML, прикреплять к письмам или печатать на этикетках продукции. + +--- + +## Следующие шаги и связанные темы + +* **Интеграция с Flask или Django** – обслуживайте сгенерированный PNG напрямую из веб‑эндпоинта. +* **Пакетная генерация** – перебирайте список идентификаторов продуктов, чтобы создать папку с PNG‑файлами штрих‑кодов. +* **Комбинация с генерацией PDF** – используйте `aspose-pdf` для размещения PNG в счёте или транспортной этикетке. +* **Исследование других симбологий** – замените `EncodeTypes.Planet` на `EncodeTypes.QR`, `EncodeTypes.DataMatrix` или `EncodeTypes.Code128`, чтобы удовлетворить различные бизнес‑требования. + +Освоив перечисленные шаги, вы теперь знаете, **как программно генерировать изображение штрих‑кода**, и можете расширять эту схему на любой стандарт штрих‑кода, поддерживаемый Aspose.BarCode. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/russian/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..cee38712c --- /dev/null +++ b/barcode/russian/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-08-03 +description: Создайте изображение почтового штрихкода на C# быстро. Узнайте, как генерировать + почтовый штрихкод, задавать размеры штрихкода и создавать штрихкод Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: ru +lastmod: 2026-08-03 +og_description: Создайте изображение почтового штрихкода на C# с помощью этого полного + руководства; узнайте, как задавать размеры штрихкода, генерировать штрихкод Planet + и создавать штрихкоды RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Создание изображения почтового штрихкода в C# – полное руководство по программированию +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Создание изображения почтового штрихкода в C# – пошаговое руководство +url: /ru/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание изображения почтового штрих‑кода в C# – пошаговое руководство + +Если вам нужно **создать изображение почтового штрих‑кода** в C#, это руководство покажет, как это сделать. Мы рассмотрим **как генерировать почтовый штрих‑код**, **как задать размеры штрих‑кода** и как **создать штрих‑код Planet** для распространённых почтовых стандартов. + +В конце вы получите два готовых PNG‑файла — один штрих‑код Planet и один штрих‑код RM4SCC — каждый высотой 100 px. Дополнительные инструменты не требуются, кроме библиотеки Aspose.BarCode для .NET. + +## Требования + +* .NET 6 SDK или новее (код также работает с .NET Framework 4.7+) +* Visual Studio 2022 или любой IDE для C# +* NuGet‑пакет **Aspose.BarCode** (библиотека, предоставляющая `BarcodeGenerator`) + +## Шаг 1: Установить библиотеку штрих‑кодов + +Откройте терминал в папке проекта и выполните: + +```bash +dotnet add package Aspose.BarCode +``` + +Пакет добавляет пространство имён `Aspose.BarCode`, которое содержит `BarcodeGenerator` и перечисление `EncodeTypes`, необходимое для почтовых штрих‑кодов. + +## Шаг 2: Определить папку вывода + +Создание надёжного пути вывода предотвращает ошибки выполнения, когда папка не существует. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Почему это важно*: `Directory.CreateDirectory` идемпотентен — он создаёт папку только если её ещё нет, избегая исключений при последующих запусках. + +## Шаг 3: Настроить общие размеры штрих‑кода + +Установка X‑размера (ширины отдельного бара) и общей высоты бара позволяет контролировать визуальный размер генерируемого изображения. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Как задать размеры штрих‑кода**: свойство `Parameters.Barcode.XDimension.Pixels` определяет ширину узкого бара, а `Parameters.Barcode.BarHeight.Pixels` — полную высоту. Отрегулируйте эти значения в соответствии со спецификациями вашей почтовой службы. + +## Шаг 4: Сгенерировать штрих‑код Planet + +Planet — широко используемый почтовый штрих‑код в Великобритании. Ниже приведён код, который создаёт штрих‑код Planet высотой 100 px и сохраняет его как PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Почему это работает**: `EncodeTypes.Planet` указывает генератору использовать симбологию Planet. Метод `Save` записывает PNG‑файл по указанному пути, сохраняя ранее заданные размеры. + +## Шаг 5: Сгенерировать штрих‑код RM4SCC + +RM4SCC — нидерландский стандарт почтовых штрих‑кодов. Приведённый ниже код повторяет пример с Planet, демонстрируя **как генерировать почтовый штрих‑код** другого типа с теми же размерами. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Оба PNG‑файла теперь находятся в папке `Barcodes`. При открытии вы увидите чистые штрих‑коды высотой 100 px, готовые к печати или встраиванию в документы. + +## Полный исходный код + +Ниже представлена полная, готовая к запуску программа, которая **создаёт изображения почтовых штрих‑кодов** для стандартов Planet и RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Ожидаемый вывод + +Запуск программы выводит пути к файлам и создаёт два PNG‑файла: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Каждое изображение высотой 100 px, ширина узкого бара — 4 пикселя, что соответствует заданным размерам. + +## Практические советы и распространённые подводные камни + +* **Разрешения папки** — если программа запускается под ограничённой учётной записью, убедитесь, что целевая папка доступна для записи. +* **Другие размеры** — чтобы получить более высокий штрих‑код, увеличьте `barHeightPixels`. Для более высокой детализации уменьшите `xDimensionPixels`, но оставьте значение ≥ 2, чтобы избежать артефактов рендеринга. +* **Другие почтовые симбологии** — Aspose.BarCode также поддерживает `EncodeTypes.Postnet` и `EncodeTypes.AustralianPost`. Поменяйте значение `EncodeTypes`, оставив ту же логику размеров. +* **Формат изображения** — используйте `BarCodeImageFormat.Jpeg` для уменьшения размера файла, если не требуется безупречное качество. + +## Заключение + +Теперь вы знаете, как **создавать изображения почтовых штрих‑кодов** в C# путем настройки размеров, выбора нужной симбологии и сохранения результата в PNG. В руководстве рассмотрено **как генерировать почтовый штрих‑код**, продемонстрировано **генерирование штрих‑кода Planet** и объяснено **как задать размеры штрих‑кода** для получения согласованного вывода. + +Далее изучайте **кастомизацию цветов штрих‑кода**, добавление **читаемого человеком текста** или интеграцию изображений в PDF‑счета. Тот же шаблон применим к любому другому типу штрих‑кода, поддерживаемому Aspose.BarCode, позволяя расширить решение до полной автоматизации почтовых процессов. + + +## Что изучать дальше? + + +Следующие руководства охватывают близкие темы, опираясь на техники, продемонстрированные в этом руководстве. Каждый ресурс содержит полностью работающие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы реализации в ваших проектах. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to generate barcode java – Australia Post Barcode with Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/russian/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..2651e0097 --- /dev/null +++ b/barcode/russian/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-08-03 +description: Как сохранить штрих‑код в C# с пошаговым примером генератора штрих‑кодов. + Узнайте, как генерировать штрих‑коды Planet, задавать размеры и экспортировать PNG‑изображения. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: ru +lastmod: 2026-08-03 +og_description: Как сохранить штрих‑код в C# с помощью примера генератора штрих‑кодов. + Этот учебник показывает, как генерировать штрих‑коды Planet, настраивать X‑размер + и экспортировать файлы PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Как сохранить штрих‑код в C# – пошаговое руководство +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Как сохранить штрих‑код в C# – полное руководство по генерации штрих‑кодов +url: /ru/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как сохранить штрих‑код в C# – полное руководство по генератору штрих‑кодов + +Сохранение изображений штрих‑кодов в C# является распространённой задачей, когда необходимо внедрять почтовые штрих‑коды в счета‑фактуры, транспортные этикетки или бирки инвентаря. Это руководство проведёт вас через практический **c# barcode generator** рабочий процесс, от создания штрих‑кода Planet до экспорта PNG‑файлов с заполненными и пустыми полосами. + +Вы узнаете, как установить ширину полосы, переключать заполненные полосы и надёжно работать с папками вывода. К концу руководства у вас будет полностью рабочий **barcode generator example**, который можно скопировать в любой проект .NET. + +## Что понадобится + +Before writing code, make sure you have: + +- .NET 6.0 SDK или новее (пример работает с .NET Core и .NET Framework) +- Visual Studio 2022 или любой IDE, совместимый с C# +- Пакет NuGet **Aspose.BarCode** (или другая библиотека, поддерживающая `EncodeTypes.Planet`). Установите его с помощью: + +```bash +dotnet add package Aspose.BarCode +``` + +Библиотека предоставляет класс `BarcodeGenerator`, используемый в течение всего руководства. + +## Настройка среды разработки + +Создайте новый консольный проект и добавьте необходимое пространство имён: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +Пространство имён `System.IO` предоставляет `Directory.CreateDirectory`, которое гарантирует существование папки вывода перед попыткой записи файлов. + +## Как сохранять изображения штрих‑кодов с помощью генератора штрих‑кодов C# + +Суть решения состоит из небольшого набора шагов, которые настраивают **Planet barcode** и затем сохраняют изображение на диск. Ниже приведённые разделы разбивают процесс на удобные части. + +### Шаг 1: Определите папку вывода + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Почему?** +Жёстко заданный путь может вызвать `DirectoryNotFoundException` на машинах, где папка не существует. `CreateDirectory` идемпотентен — создаёт директорию только при её отсутствии, делая код безопасным при многократных запусках. + +### Шаг 2: Создайте генератор штрих‑кода Planet (заполненные полосы) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Почему?** +`EncodeTypes.Planet` указывает библиотеке генерировать почтовый штрих‑код Planet, который широко используется почтовыми службами. Строка `"123456"` — пример полезной нагрузки; замените её любыми числовыми данными, необходимыми вашему бизнес‑логике. + +### Шаг 3: Настройте ширину полосы (X‑dimension) и оставьте заполненные полосы по умолчанию + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Почему?** +X‑dimension контролирует физическую ширину каждой полосы. Значение `4` пикселя даёт читаемый штрих‑код на стандартных принтерах 300 dpi. Оставив `FilledBars` равным `true` (по умолчанию), вы получаете классический вид сплошных полос. + +### Шаг 4: Сохраните изображение штрих‑кода с заполненными полосами + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Почему?** +Сохранение в PNG сохраняет качество изображения без потерь, что важно для точности сканирования. Метод `Save` автоматически создаёт файл изображения; вам нужно лишь указать полный путь и желаемый формат. + +### Шаг 5: Создайте второй генератор для версии с пустыми полосами + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Создание нового экземпляра гарантирует, что изменения, внесённые для версии с пустыми полосами, не повлияют на уже сохранённое изображение с заполненными полосами. + +### Шаг 6: Отключите заполненные полосы, сохранив ту же X‑dimension + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Почему?** +Установка `FilledBars = false` выводит штрих‑код только с контуром каждой полосы, что некоторые почтовые стандарты требуют для визуальной проверки. + +### Шаг 7: Сохраните изображение штрих‑кода с пустыми полосами + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Теперь у вас есть два PNG‑файла — один с заполненными полосами, другой с пустыми — готовые к включению в PDF, HTML‑письма или печатные этикетки. + +## Полностью исполняемая программа + +Ниже приведён полный код, который вы можете скопировать в `Program.cs`. Он компилируется и запускается без изменений (при условии, что пакет Aspose.BarCode установлен). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Ожидаемый вывод + +Запуск программы выводит две строки, похожие на: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Откройте папку `Barcodes`, и вы увидите два PNG‑файла. Оба изображения можно открыть в любом просмотрщике изображений или встроить напрямую в документы. + +![пример сохранения штрих‑кода](barcode-example.png){: .align-center alt="пример сохранения штрих‑кода"} + +## Распространённые варианты и граничные случаи + +| Сценарий | Корректировка | +|----------|----------------| +| **Другой формат изображения** | Измените `BarCodeImageFormat.Png` на `Jpeg`, `Gif` или `Bmp` при необходимости. | +| **Пользовательский размер вывода** | Используйте `filled.Parameters.Image.Width` и `Height`, чтобы задать конкретные пиксельные размеры. | +| **Динамические данные** | Замените статическую строку `"123456"` переменной, содержащей номера заказов, идентификаторы отслеживания и т.д. | +| **Не существующая папка** | `Directory.CreateDirectory` уже обрабатывает отсутствие папок; дополнительный код не требуется. | +| **Печать высокого разрешения** | Увеличьте `XDimension.Pixels` до 6–8 для принтеров 600 dpi, но проверьте совместимость со сканером. | + +**Совет:** Если необходимо генерировать множество штрих‑кодов в цикле, переиспользуйте один экземпляр `BarcodeGenerator` и меняйте только свойство `CodeText` перед каждым `Save`. Это уменьшает накладные расходы на создание объектов. + +## Как генерировать штрих‑коды для других стандартов + +Тот же шаблон работает для других `EncodeTypes`, таких как `Code128`, `QR` или `DataMatrix`. Просто замените `EncodeTypes.Planet` на нужный тип и скорректируйте любые специфичные для типа параметры (например, `QRCodeVersion` + +## Что изучать дальше? + +Следующие руководства охватывают тесно связанные темы, опирающиеся на техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Как сохранить PNG, используя DataMatrix C40 с Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Как генерировать штрих‑коды DataMatrix (ECC 200) с Aspose.BarCode для .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Как генерировать штрих‑код – конфигурация Code 39 с Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/spanish/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..bb8d0dc09 --- /dev/null +++ b/barcode/spanish/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-08-03 +description: Tutorial de generador de códigos de barras en C# que muestra cómo crear + un código de barras Planet con Aspose.BarCode, establecer la dimensión X y guardar + como imágenes PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: es +lastmod: 2026-08-03 +og_description: El tutorial del generador de códigos de barras en C# te guía para + crear un código de barras Planet, ajustar la dimensión X y guardarlo como PNG usando + Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Generador de códigos de barras C# – crea el código de barras Planet paso + a paso +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Generador de códigos de barras C# – crear código de barras Planet y ejemplo + RM4SCC +url: /es/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generador de códigos de barras C# – crear código de barras Planet y ejemplo RM4SCC + +Si necesitas un **barcode generator C#** que pueda producir símbolos específicos de correo, esta guía te muestra exactamente cómo **create Planet barcode** imágenes con Aspose.BarCode. Verás cómo configurar la X‑dimension, generar un código de barras RM4SCC correspondiente y guardar ambos como archivos PNG, todo en unos pocos pasos concisos. + +El tutorial cubre todo lo que necesitas para ejecutar el código en .NET 6 o posterior, explica por qué cada configuración es importante y señala los problemas comunes, como un ancho de módulo incorrecto o permisos de directorio faltantes. Al final tendrás dos imágenes de códigos de barras listas para imprimir que cumplen con los estándares Planet y RM4SCC. + +## Requisitos previos + +* .NET 6 SDK (o cualquier versión de .NET compatible con Aspose.BarCode) +* Visual Studio 2022 o cualquier IDE de C# que prefieras +* Una referencia NuGet a **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Permiso de escritura en la carpeta donde planeas almacenar los archivos PNG + +No se requieren servicios externos adicionales; la biblioteca maneja todo el codificado localmente. + +## Paso 1: Inicializar el objeto barcode generator C# + +La primera tarea es crear una instancia de `BarcodeGenerator`. El constructor recibe la simbología del código de barras (`EncodeTypes.Planet`) y los datos a codificar. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*¿Por qué este paso?* +`BarcodeGenerator` es el punto de entrada para cada código de barras que generas. Seleccionar `EncodeTypes.Planet` indica a la biblioteca que siga la especificación ISO/IEC 24723 utilizada por muchos servicios postales. + +## Paso 2: Establecer la X‑dimension (ancho del módulo) para el código de barras Planet + +La X‑dimension define el ancho de un solo módulo del código de barras (la barra o espacio más pequeño). Un valor de **4 píxeles** funciona bien para la mayoría de impresoras de etiquetas. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*¿Por qué es importante?* +Si el módulo es demasiado estrecho, el código de barras puede volverse ilegible; si es demasiado ancho, el tamaño de la etiqueta crece innecesariamente. Ajustar `Pixels` te permite afinar el código de barras para la resolución específica de tu impresora. + +## Paso 3: Guardar el código de barras Planet como una imagen PNG + +Aspose.BarCode calcula automáticamente la altura del código de barras en función de la simbología seleccionada, por lo que solo necesitas especificar la ruta del archivo y el formato. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Consejo* +Reemplaza `YOUR_DIRECTORY` con una ruta absoluta o relativa que exista en tu máquina. Si la carpeta no existe, el método `Save` lanza una `DirectoryNotFoundException`. + +**Salida esperada** – un archivo PNG que se asemeja a la ilustración a continuación (la imagen real no se muestra aquí, pero verás un código de barras Planet clásico con una carga numérica de `123456`). + +## Paso 4: Inicializar un segundo generador para el código de barras RM4SCC + +Muchos sistemas postales requieren tanto los símbolos Planet como RM4SCC en el mismo envío. Crea una nueva instancia de `BarcodeGenerator` para la simbología RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*¿Por qué una instancia separada?* +Cada simbología tiene su propio conjunto de parámetros. Reutilizar el mismo generador podría transferir inadvertidamente configuraciones (como la X‑dimension) que no son óptimas para el segundo código de barras. + +## Paso 5: Configurar la X‑dimension para el código de barras RM4SCC + +RM4SCC también respeta la configuración de X‑dimension, por lo que aplicamos el mismo ancho en píxeles para mantener la consistencia visual. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Consejo profesional* +Si necesitas un código de barras más alto (p. ej., para etiquetas más grandes), también puedes establecer `Height.Pixels`. Dejarlo sin establecer permite que la biblioteca calcule automáticamente la altura ideal. + +## Paso 6: Guardar el código de barras RM4SCC como una imagen PNG + +Finalmente, guarda el código de barras RM4SCC en disco. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Ahora tienes dos archivos PNG —`PostalPlanetBarHeightNone.png` y `PostalRM4SCCBarHeightNone.png`— que puedes incrustar en etiquetas de envío, imprimir en sobres o enviar a un servicio de impresión externo. + +## Opcional: Ajustar la altura o usar otros formatos de imagen + +Si tu flujo de trabajo requiere una altura específica del código de barras o un formato de imagen diferente (p. ej., JPEG o BMP), puedes modificar los parámetros antes de llamar a `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Caso límite** – Cuando estableces una altura personalizada, asegúrate de que el valor respete la altura mínima requerida por la norma ISO; de lo contrario, el código de barras podría fallar la validación. + +## Problemas comunes y cómo evitarlos + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| `DirectoryNotFoundException` | La carpeta de destino no existe o está escrita incorrectamente. | Crea la carpeta primero o usa `Path.Combine` con `Environment.CurrentDirectory`. | +| Barcode unreadable on low‑resolution printers | X‑dimension demasiado pequeña para el DPI de la impresora. | Aumenta `XDimension.Pixels` a 5 – 6 para impresoras de 203 dpi, o prueba con una etiqueta de muestra. | +| Wrong symbology used | Se pasa `EncodeTypes.Code128` en lugar de `EncodeTypes.Planet`. | Verifica que el valor del enum `EncodeTypes` coincida con el estándar postal requerido. | +| Null reference on `Parameters` | Usar una versión anterior de Aspose.BarCode donde la API difiere. | Actualiza al último paquete NuGet (v23.12 o posterior). | + +## Ejemplo completo ejecutable + +A continuación se muestra el programa completo que puedes copiar, pegar y ejecutar. Incluye sentencias `using`, manejo de errores y comentarios que explican cada línea. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Al ejecutar el programa se crea una carpeta `Barcodes` junto al ejecutable y se colocan los dos archivos PNG dentro. Ábrelos con cualquier visor de imágenes para verificar el resultado. + +## Conclusión + +Ahora tienes una solución de **barcode generator C#** que puede **create Planet barcode** imágenes, ajustar la X‑dimension para una impresión óptima y generar un código de barras RM4SCC correspondiente, todo con unas pocas líneas de código. El enfoque funciona con .NET 6+, solo requiere el paquete NuGet Aspose.BarCode y puede ampliarse a otras simbologías como Code128, QR o DataMatrix cambiando el valor de `EncodeTypes`. + +### ¿Qué sigue? + +* Experimenta con diferentes valores de `XDimension.Pixels` para que coincidan con el DPI de tu impresora. +* Genera códigos de barras en otros formatos (PDF, SVG) cambiando el enum `BarCodeImageFormat`. +* Combina los dos archivos PNG en una sola etiqueta usando una biblioteca gráfica como **SkiaSharp**. +* Explora la API completa de Aspose.BarCode para funciones avanzadas como validación de checksum o fuentes personalizadas. + +Siéntete libre de adaptar el código para procesamiento por lotes o integrarlo en un servicio web ASP.NET Core que devuelva imágenes de códigos de barras bajo demanda. ¡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 funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Crear PNG de código de barras – Relación de aspecto DataMatrix – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Cómo guardar PNG usando DataMatrix C40 con Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [tutorial de generador de códigos de barras c# – Personalizar relaciones de aspecto del código de barras Code 16K con Aspose.BarCode para .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/spanish/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..3def7337e --- /dev/null +++ b/barcode/spanish/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: El tutorial de generador de códigos de barras en C# muestra cómo generar + una imagen de código de barras con Aspose.BarCode, establecer columnas y filas, + y guardar archivos PNG para DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: es +lastmod: 2026-08-03 +og_description: El tutorial de generador de códigos de barras en C# explica cómo generar + una imagen de código de barras usando Aspose.BarCode, configurar columnas y filas + de DataBar Expanded Stacked y guardar archivos PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Generador de códigos de barras C# – guía paso a paso para generar una imagen + de código de barras +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Generador de códigos de barras C# – generar imagen de código de barras +url: /es/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Generador de códigos de barras C# – generar imagen de código de barras + +Si necesita un generador de códigos de barras C# que pueda generar una imagen de código de barras para DataBar Expanded Stacked, esta guía lo acompañará paso a paso en todo el proceso. Aprenderá cómo configurar los ajustes de columnas y filas, guardar el resultado como PNG y adaptar el código para otras simbologías. + +Generar imágenes de códigos de barras programáticamente elimina pasos manuales y garantiza consistencia en facturas, etiquetas de envío y sistemas de inventario. Este tutorial cubre todo lo que necesita, desde la configuración del proyecto hasta el código fuente completo, para que pueda ejecutar el ejemplo de inmediato. + +## Requisitos previos + +Antes de comenzar, asegúrese de tener: + +* .NET 6.0 o posterior instalado +* Un IDE como Visual Studio 2022 (cualquier editor que soporte C# funciona) +* Una licencia para **Aspose.BarCode for .NET** – la evaluación gratuita funciona para pruebas +* Familiaridad básica con la sintaxis de C# + +Si falta alguno de estos elementos, instale el .NET SDK desde dotnet.microsoft.com y obtenga el paquete NuGet de Aspose.BarCode con: + +```bash +dotnet add package Aspose.BarCode +``` + +## Paso 1: Crear un proyecto de generador de códigos de barras C# + +Cree una nueva aplicación de consola y agregue las directivas `using` requeridas: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +La clase `BarcodeGenerator` es el núcleo de la API del generador de códigos de barras C#. Recibe el tipo de simbología y el texto a codificar. + +## Paso 2: Generar un código de barras DataBar Expanded Stacked y establecer columnas + +El primer ejemplo crea un código de barras con cuatro columnas. Ajustar la propiedad `Columns` cambia la densidad visual de la simbología DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Por qué es importante:** El número de columnas influye en la cantidad de datos que se pueden almacenar en un espacio compacto. Configurarlo a 4 produce un código de barras más ancho que sigue siendo legible por la mayoría de los escáneres. + +## Paso 3: Generar un código de barras con recuento de filas personalizado + +El segundo ejemplo muestra cómo controlar el diseño vertical estableciendo la propiedad `Rows`. Una configuración de tres filas es útil cuando necesita un código de barras más alto para un espacio horizontal limitado. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Por qué es importante:** Ajustar las filas le permite encajar el código de barras en una columna estrecha mientras se preserva la legibilidad. El generador de códigos de barras C# recalcula automáticamente el tamaño del módulo para cumplir con la especificación. + +## Paso 4: Ejemplo completo y ejecutable + +A continuación se muestra un programa autónomo que combina los pasos anteriores. Copie el código en `Program.cs`, reemplace `YOUR_DIRECTORY` con una ruta de carpeta existente y ejecute la aplicación. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Resultado esperado + +Al ejecutar el programa, aparecen dos archivos PNG en el directorio de destino: + +* **DatabarCols4.png** – un código de barras DataBar Expanded Stacked con cuatro columnas +* **DatabarRows3.png** – los mismos datos codificados en tres filas + +Abra las imágenes con cualquier visor; muestran códigos de barras nítidos y escaneables listos para imprimir o incrustar en PDFs. + +## Cómo generar una imagen de código de barras con dimensiones personalizadas + +Si necesita un tamaño de imagen específico, ajuste las propiedades `ImageHeight` y `ImageWidth` antes de llamar a `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Cambiar las dimensiones no afecta los datos codificados; solo escala la representación visual. Esta técnica es útil al integrar códigos de barras en componentes de UI con restricciones de diseño fijas. + +## Errores comunes y consejos profesionales + +* **Separadores de ruta:** Use cadenas verbatim (`@"C:\Path\file.png"`) o `Path.Combine` para evitar problemas de caracteres de escape en Windows. +* **Aplicación de licencia:** Sin una licencia válida, las imágenes generadas contienen una marca de agua. Aplique su licencia al inicio de la aplicación: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Límites de codificación:** DataBar Expanded Stacked admite hasta 74 caracteres numéricos. Superar este límite lanza una excepción. Valide la longitud de la entrada antes de crear el generador. +* **Rendimiento:** Reutilizar una única instancia de `BarcodeGenerator` para múltiples guardados reduce la asignación de memoria. Solo cambie las propiedades `Rows` o `Columns` entre guardados si el texto codificado permanece igual. + +## Próximos pasos + +Ahora que puede generar imágenes de códigos de barras con el generador de códigos de barras C#, considere explorar: + +* **Diferentes simbologías** – pruebe `EncodeTypes.QR`, `EncodeTypes.Code128` o `EncodeTypes.Pdf417`. +* **Personalización de color** – establezca `Parameters.Barcode.ForeColor` y `BackColor` para que coincidan con la marca. +* **Incrustar en PDFs** – combine el PNG generado con Aspose.PDF para crear documentos imprimibles. + +Estas extensiones le permiten crear una solución de códigos de barras completa para aplicaciones de inventario, logística o comercio minorista. + +--- + + +## ¿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 ayudarle a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en sus 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 generar códigos de barras DataMatrix (ECC 200) con Aspose.BarCode para .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/spanish/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..ca12cc1e5 --- /dev/null +++ b/barcode/spanish/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: Ejemplo de generador de códigos de barras en C# que muestra cómo establecer + el ancho, cómo cambiar la altura y cómo generar la imagen del código de barras. + Sigue las instrucciones paso a paso. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: es +lastmod: 2026-08-03 +og_description: El ejemplo del generador de códigos de barras muestra cómo establecer + el ancho de la dimensión X, cambiar la altura de la barra y generar una imagen de + código de barras en C#. Sigue los pasos para crear archivos PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Ejemplo de generador de códigos de barras – Guía de ancho y altura en C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Ejemplo de generador de códigos de barras en C# – establecer ancho y altura +url: /es/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ejemplo de generador de códigos de barras en C# – establecer ancho y altura + +Si necesitas un **ejemplo de generador de códigos de barras** en C#, esta guía te muestra cómo establecer el ancho de la X‑dimension, cómo cambiar la altura de la barra y cómo generar un archivo de imagen de código de barras. Verás un programa completo y ejecutable que produce dos archivos PNG con diferentes alturas. + +Un escenario típico es crear etiquetas de producto donde el tamaño del código de barras debe cumplir con las especificaciones del escáner. Al final de este tutorial podrás ajustar los parámetros de ancho y altura programáticamente y guardar el resultado como una imagen PNG. + +## Requisitos previos + +* .NET 6 (o posterior) instalado – el código está dirigido al SDK de .NET 6. +* Una biblioteca de códigos de barras que soporte `EncodeTypes.DatabarOmniDirectional`. El ejemplo usa **Aspose.BarCode for .NET**, pero cualquier biblioteca que exponga propiedades similares funciona de la misma manera. +* Un IDE o editor (Visual Studio, VS Code, Rider) para compilar y ejecutar el programa. +* Permiso de escritura en un directorio donde se guardarán los archivos PNG. + +> **Consejo profesional:** Crea una carpeta llamada `Barcodes` en la raíz de tu proyecto y haz referencia a ella con `Path.Combine` para evitar codificar rutas absolutas. + +## Ejemplo de generador de códigos de barras: inicializar y configurar + +El primer paso es crear una instancia de `BarcodeGenerator` con la simbología y la cadena de datos deseadas. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +El enum `EncodeTypes.DatabarOmniDirectional` selecciona la simbología Databar Omni‑directional, y la cadena de datos con formato GS1 `(01)12345678901231` representa un valor típico de GTIN‑14. Inicializar el generador una vez te permite reutilizar el mismo objeto para múltiples imágenes. + +## Cómo establecer el ancho (X‑dimension) + +La X‑dimension controla el ancho del módulo del código de barras. Configurarla a 2 píxeles hace que cada barra estrecha tenga 2 píxeles de ancho, lo cual es un requisito común para la impresión de alta densidad. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Por qué es importante: Si el ancho es demasiado pequeño, los escáneres pueden no resolver las barras individuales; si es demasiado grande, el código de barras puede exceder el espacio de la etiqueta. Ajusta el valor en píxeles para que coincida con el DPI de la impresora y el tamaño objetivo de la etiqueta. + +## Cómo cambiar la altura + +La altura de la barra determina cuán altas aparecen las barras. El ejemplo crea dos imágenes: una con una altura de 30 píxeles y otra con una altura de 60 píxeles. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +La propiedad `BarHeight.Pixels` influye directamente en la altura visual de las barras. Cambiarla entre guardados te permite generar múltiples variantes del mismo conjunto de datos sin recrear el generador. + +### Resultado esperado + +Ejecutar el programa produce dos archivos PNG en la carpeta `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – las barras tienen 30 píxeles de altura. +* `DatabarBarHeight60Pixels.png` – las barras tienen 60 píxeles de altura. + +Ambas imágenes comparten el mismo ancho (determinado por la X‑dimension) y codifican los mismos datos GTIN‑14. + +![Dos archivos PNG de códigos de barras con diferentes alturas generados por código C#](barcode-example.png "Ejemplo de generador de códigos de barras mostrando variaciones de altura") + +*El texto alternativo de la imagen anterior contiene la palabra clave principal para accesibilidad y SEO.* + +## Cómo generar una imagen de código de barras en C# + +El método `Save` se encarga de la conversión de los datos del código de barras a un archivo de imagen. Puedes elegir otros formatos (JPEG, BMP, SVG) pasando un valor diferente del enum `BarCodeImageFormat`. El ejemplo usa PNG porque preserva calidad sin pérdidas y es ampliamente compatible. + +Si necesitas incrustar el código de barras directamente en un PDF o una página web, obtén la imagen como un `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Este enfoque elimina la necesidad de archivos temporales y es útil para servicios de alto rendimiento. + +## Variaciones comunes y casos límite + +| Situation | Adjustment | +|-----------|------------| +| **Simbología diferente** | Reemplaza `EncodeTypes.DatabarOmniDirectional` con otro valor del enum (p.ej., `EncodeTypes.Code128`). | +| **Etiquetas muy pequeñas** | Disminuye `XDimension.Pixels` a 1 píxel, pero verifica la legibilidad con el escáner. | +| **Impresión de alta resolución** | Aumenta tanto la X‑dimension como la altura de la barra proporcionalmente (p.ej., ancho de 4 px, altura de 80 px). | +| **Datos dinámicos** | Pasa la cadena de datos en tiempo de ejecución, quizás desde un registro de base de datos. | +| **Generación por lotes** | Itera sobre una colección de cadenas de datos, reutilizando la misma instancia de `BarcodeGenerator` mientras actualizas `generator.Text`. | + +Cuando encuentres una excepción como `ArgumentOutOfRangeException`, verifica que los valores de píxeles sean enteros positivos y que el directorio de salida exista. + +## Recapitulación del código fuente completo + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Copia el código en un nuevo proyecto de consola, restaura el paquete NuGet Aspose.BarCode (`dotnet add package Aspose.BarCode`) y ejecuta `dotnet run`. Verás mensajes en la consola que confirman los archivos guardados. + +## Conclusión + +Este **ejemplo de generador de códigos de barras** demuestra cómo establecer el ancho, cómo cambiar la altura y cómo generar una imagen de código de barras en C#. Al ajustar `XDimension.Pixels` y `BarHeight.Pixels` controlas el tamaño visual del código de barras, y el método `Save` escribe el resultado en archivos PNG. Experimenta con diferentes simbologías, formatos de salida y cadenas de datos para adaptarlos a los requisitos de tu aplicación. + +**Próximos pasos** + +* Explora **cómo generar códigos de barras** en otros formatos de imagen (SVG, JPEG) para uso web. +* Aprende **crear imagen de código de barras c#** para endpoints de ASP.NET Core que devuelven el PNG directamente a un navegador. +* Combina este código con una biblioteca de generación de PDF para incrustar códigos de barras en facturas o etiquetas de envío. + +¡Siéntete libre de adaptar el ejemplo, compartir tus resultados o hacer preguntas en los comentarios! ¡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 funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Cómo generar códigos de barras - Tipos de códigos de barras unidimensionales](/barcode/english/net/one-dimensional-barcode-types/) +- [Cómo establecer borde para la personalización de códigos de barras ITF-14](/barcode/english/net/itf-14-barcode-customization/) +- [Cómo generar códigos de barras DataMatrix (ECC 200) con Aspose.BarCode para .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/spanish/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..e18333e69 --- /dev/null +++ b/barcode/spanish/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-08-03 +description: Crea un PNG de código de barras en C# y aprende cómo cambiar la relación + de aspecto de las imágenes DataBar. Sigue este ejemplo completo con código y consejos. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: es +lastmod: 2026-08-03 +og_description: Crea un PNG de código de barras en C# y descubre cómo cambiar la relación + de aspecto de los códigos de barras DataBar. Esta guía te ofrece código listo para + ejecutar y consejos prácticos. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Crear PNG de código de barras en C# – ejemplo completo con control de relación + de aspecto +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Crear código de barras PNG en C# – guía paso a paso +url: /es/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear código de barras PNG en C# – guía paso a paso + +Si necesitas **crear código de barras PNG** en C#, este tutorial te muestra exactamente cómo hacerlo. Generarás un código de barras DataBar omnidireccional apilado, lo guardarás como un archivo PNG y aprenderás **cómo cambiar la relación de aspecto** para adaptarla a diferentes entornos de escaneo. + +La guía cubre todo lo que necesitas: paquetes requeridos, un programa completo y ejecutable, y explicaciones de por qué cada configuración es importante. Al final tendrás dos archivos PNG—uno con una relación de aspecto de 15 y otro con 30—listos para pruebas o uso en producción. + +## Prerrequisitos + +Antes de comenzar, asegúrate de tener: + +- .NET 6.0 SDK o posterior instalado +- Visual Studio 2022 (o cualquier IDE de C#) +- Una referencia NuGet a **Aspose.BarCode** (la biblioteca que proporciona `BarcodeGenerator`) +- Permiso de escritura en el directorio donde se guardarán los archivos PNG + +Puedes agregar el paquete Aspose.BarCode con el siguiente comando: + +```bash +dotnet add package Aspose.BarCode +``` + +## Paso 1: Configurar el proyecto e importar espacios de nombres + +Crea una nueva aplicación de consola e importa los espacios de nombres necesarios para la generación de códigos de barras y la E/S de archivos. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Por qué es importante:** Importar `Aspose.BarCode.Generation` te da acceso a `BarcodeGenerator`. Mantener el código dentro de `Main` hace que el ejemplo sea autocontenido y fácil de ejecutar. + +## Paso 2: Crear un generador de código de barras para un DataBar omnidireccional apilado + +Instancia `BarcodeGenerator` con el tipo `EncodeTypes.DatabarStackedOmniDirectional` y una cadena de datos de ejemplo GS1‑128. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Por qué es importante:** El tipo de codificación elegido produce un DataBar de alta densidad que puede ser leído por la mayoría de los escáneres modernos. La cadena de datos sigue el formato del Identificador de Aplicación GS1 (01), que es común para identificadores de productos. + +## Paso 3: Definir la dimensión X (ancho del módulo) en píxeles + +Establece el ancho del módulo para controlar el tamaño general del código de barras sin afectar su legibilidad. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Por qué es importante:** Una dimensión X de 2 píxeles produce un código de barras que no es ni demasiado pequeño para los escáneres ni demasiado grande para los espacios típicos de etiquetas. + +## Paso 4: Guardar el primer PNG con una relación de aspecto de 15 + +Ajusta la relación de aspecto del DataBar y luego guarda la imagen como archivo PNG. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Por qué es importante:** La relación de aspecto controla la relación altura‑ancho del DataBar apilado. Una relación de 15 es un valor predeterminado común que equilibra la legibilidad y la altura de la etiqueta. + +## Paso 5: Cambiar la relación de aspecto a 30 y guardar un segundo PNG + +Modifica la misma instancia del generador para usar una relación de aspecto mayor y luego guarda la segunda imagen. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Por qué es importante:** Incrementar la relación de aspecto estira el código de barras verticalmente, lo que puede mejorar la fiabilidad del escaneo en dispositivos de baja resolución o cuando la etiqueta se imprime en medios estrechos. + +## Resultado esperado + +Ejecutar el programa crea dos archivos PNG: + +| Archivo | Relación de aspecto | Dimensiones aproximadas (píxeles) | +|--------------------------------------|---------------------|-----------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (ancho × alto) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (ancho × alto) | + +Ambas imágenes contienen un código de barras DataBar claro y escaneable que codifica el identificador GS1 `(01)12345678901231`. + +## Preguntas comunes y casos límite + +### ¿Cómo cambiar otras propiedades visuales? + +Puedes ajustar el color de primer plano, el color de fondo o añadir texto legible por humanos a través del objeto `generator.Parameters.Barcode`. Por ejemplo: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### ¿Qué pasa si necesito un formato de imagen diferente? + +Reemplaza `BarCodeImageFormat.Png` por `Jpeg`, `Bmp` o `Gif` según sea necesario. PNG sigue siendo la mejor opción para imágenes de códigos de barras sin pérdida. + +### ¿Afecta la relación de aspecto a la velocidad de escaneo? + +Relaciones de aspecto mayores aumentan la altura del código de barras, lo que puede mejorar la fiabilidad del escaneo en dispositivos que tienen dificultades con símbolos apilados cortos. Sin embargo, códigos de barras extremadamente altos pueden no caber en etiquetas pequeñas, por lo que es necesario probar con el hardware objetivo. + +### ¿Puedo generar varios códigos de barras en un bucle? + +Sí. Crea una nueva instancia de `BarcodeGenerator` para cada cadena de datos o reutiliza la misma instancia actualizando `CodeText` y `DataBar.AspectRatio`. Este enfoque reduce la sobrecarga de asignación de objetos. + +## Consejos profesionales + +- **Reutiliza el generador**: Cambiar solo `CodeText` o `AspectRatio` evita volver a instanciar el objeto, lo que acelera el procesamiento por lotes. +- **Valida la salida**: Usa un escáner manual o una aplicación móvil para confirmar que el PNG generado se lee correctamente antes de desplegarlo en producción. +- **Nombrado de archivos**: Incluye la relación de aspecto en el nombre del archivo (como se muestra) para llevar un registro de las variantes durante las pruebas. + +## Conclusión + +Ahora sabes cómo **crear archivos PNG de códigos de barras** en C# y exactamente **cómo cambiar la relación de aspecto** para símbolos DataBar omnidireccionales apilados. El ejemplo completo muestra la inicialización, la configuración de la dimensión X, la manipulación de la relación de aspecto y el guardado de la imagen, todo en un solo programa ejecutable. + +A partir de aquí puedes explorar tipos de códigos de barras adicionales, experimentar con colores o integrar el generador en un sistema de informes o de inventario más amplio. ¡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. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/spanish/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..8061d75a6 --- /dev/null +++ b/barcode/spanish/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-08-03 +description: Crea un PNG de código de barras rápidamente con esta guía. Aprende cómo + generar una imagen de código de barras usando Aspose.BarCode y generar un código + de barras planetario. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: es +lastmod: 2026-08-03 +og_description: Crea un PNG de código de barras al instante. Este tutorial muestra + cómo generar una imagen de código de barras y crear un código de barras planetario + con Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Crear código de barras PNG en Python – guía completa de programación +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Crear código de barras PNG en Python – guía paso a paso +url: /es/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear código de barras PNG en Python – guía paso a paso + +Si necesitas **crear archivos PNG de códigos de barras** desde tu aplicación Python, este tutorial te muestra exactamente cómo. Recorreremos **cómo generar una imagen de código de barras** usando Aspose.BarCode y específicamente **generar un código de barras Planet** con dimensiones personalizadas. + +Aprenderás cómo instalar la biblioteca, configurar la simbología Planet, ajustar los parámetros de tamaño y guardar el resultado como un PNG de alta calidad. La guía asume conocimientos básicos de Python y una versión reciente de Python 3 (3.8 o superior). No se requiere experiencia previa con estándares de códigos de barras. + +--- + +## Cómo crear un PNG de código de barras con Aspose.BarCode + +Esta sección contiene los pasos esenciales necesarios para **crear un PNG de código de barras**. Cada paso incluye un fragmento de código, una explicación de por qué es importante y consejos prácticos que puedes aplicar de inmediato. + +### 1. Instalar el paquete Aspose.BarCode + +Aspose ofrece un paquete puro de Python que envuelve su motor .NET core. Instálalo con `pip`: + +```bash +pip install aspose-barcode +``` + +*Por qué este paso es importante:* El paquete proporciona la clase `BarcodeGenerator` utilizada a lo largo del ejemplo. Instalarlo globalmente garantiza que el intérprete pueda localizar el ensamblado en tiempo de ejecución. + +### 2. Importar las clases requeridas + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Consejo:* Importa solo los símbolos que necesitas; esto mantiene limpio el espacio de nombres y acelera la carga del módulo. + +### 3. Crear un generador de código de barras para la simbología Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Por qué es importante:* `EncodeTypes.Planet` indica al motor que use el estándar de código de barras Planet, mientras que el segundo argumento proporciona los datos a codificar. Cambiar la simbología (p.ej., `EncodeTypes.Code128`) produciría un patrón visual completamente diferente. + +### 4. Establecer la dimensión X (ancho del módulo) en píxeles + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Explicación:* La dimensión X controla el ancho de la barra estrecha. Un valor de 4 píxeles produce un código de barras moderadamente denso que sigue siendo escaneable en la mayoría de los dispositivos. + +### 5. Definir una altura de barra manual en píxeles + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Por qué podrías ajustarlo:* Algunas impresoras minoristas requieren barras más altas para un escaneo fiable. La altura predeterminada suele ser 50 px; aumentarla a 100 px mejora la legibilidad sin ampliar drásticamente el tamaño del archivo. + +### 6. Guardar el código de barras generado como una imagen PNG + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Resultado:* Aparece un archivo PNG llamado **PlanetBarHeight100.png** en la carpeta `output`. PNG es sin pérdida, lo que lo hace ideal para impresión e incrustación en páginas web. + +### 7. Verificar la salida (opcional) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Consejo:* Ver la imagen confirma que las dimensiones coinciden con los parámetros que estableciste. Si el código de barras se ve distorsionado, revisa la dimensión X o la configuración de la altura de la barra. + +--- + +## Cómo generar una imagen de código de barras en formato PNG (configuraciones alternativas) + +Si necesitas un formato de imagen diferente o deseas incrustar el código de barras en un PDF más adelante, puedes cambiar el enumerado `BarCodeImageFormat`: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Por qué es importante:* PNG conserva cada píxel, lo cual es crucial para códigos de barras de alto contraste. JPEG introduce artefactos de compresión que pueden interferir con el escaneo, mientras que BMP ofrece compatibilidad con herramientas más antiguas. + +--- + +## Generar código de barras Planet con colores personalizados (avanzado) + +Más allá del tamaño, puedes personalizar los colores de primer plano y de fondo: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Consejo práctico:* Los pares de colores de alto contraste (oscuro sobre claro) maximizan la fiabilidad del escáner. Evita usar tonos similares para el primer plano y el fondo. + +--- + +## Errores comunes y cómo evitarlos + +| Síntoma | Causa | Solución | +|---------|-------|----------| +| El código de barras no se escanea | Dimensión X demasiado pequeña (≤ 2 px) | Aumentar `x_dimension.pixels` a al menos 3 px | +| La imagen aparece borrosa | PNG guardado a baja DPI | Usar `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` para especificar 300 DPI (si es compatible) | +| Excepción `ImportError` | Aspose.BarCode no está instalado | Ejecuta `pip install aspose-barcode` en el mismo entorno que tu script | +| Simbología incorrecta | Se usó `EncodeTypes.Code128` en lugar de `EncodeTypes.Planet` | Reemplazar por `EncodeTypes.Planet` al crear el generador | + +--- + +## Resumen de la solución completa + +A continuación se muestra el script completo y ejecutable que **crea un PNG de código de barras** de principio a fin: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Ejecutar este script produce un **PNG de código de barras Planet** nítido que puedes incrustar en HTML, adjuntar a correos electrónicos o imprimir en etiquetas de producto. + +--- + +## Próximos pasos y temas relacionados + +* **Integrar con Flask o Django** – servir el PNG generado directamente desde un endpoint web. +* **Generación por lotes** – iterar sobre una lista de IDs de producto para crear una carpeta de archivos PNG de códigos de barras. +* **Combinar con generación de PDF** – usar `aspose-pdf` para colocar el PNG en una factura o etiqueta de envío. +* **Explorar otras simbologías** – reemplazar `EncodeTypes.Planet` por `EncodeTypes.QR`, `EncodeTypes.DataMatrix` o `EncodeTypes.Code128` para satisfacer diferentes necesidades empresariales. + +Al dominar los pasos anteriores, ahora sabes **cómo generar una imagen de código de barras** programáticamente y puedes extender el patrón a cualquier estándar de código de barras soportado por Aspose.BarCode. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/spanish/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..c9b52d591 --- /dev/null +++ b/barcode/spanish/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-08-03 +description: Crea rápidamente una imagen de código de barras postal en C#. Aprende + cómo generar un código de barras postal, establecer las dimensiones del código de + barras y generar un código de barras Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: es +lastmod: 2026-08-03 +og_description: Crea una imagen de código de barras postal en C# con este tutorial + completo; aprende a establecer las dimensiones del código de barras, generar un + código de barras Planet y producir códigos de barras RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Crear imagen de código de barras postal en C# – guía completa de programación +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Crear imagen de código de barras postal en C# – guía paso a paso +url: /es/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear imagen de código de barras postal en C# – guía paso a paso + +Si necesitas **crear una imagen de código de barras postal** en C#, esta guía te muestra exactamente cómo hacerlo. Cubriremos **cómo generar un código de barras postal**, **cómo establecer las dimensiones del código de barras**, y cómo **generar un código de barras Planet** para los estándares postales comunes. + +Terminarás con dos archivos PNG listos para usar—un código de barras Planet y un código de barras RM4SCC—cada uno de 100 px de alto. No se requieren herramientas adicionales más allá de la biblioteca Aspose.BarCode para .NET. + +## Requisitos previos + +* .NET 6 SDK o posterior (el código también funciona con .NET Framework 4.7+) +* Visual Studio 2022 o cualquier IDE de C# +* Paquete NuGet **Aspose.BarCode** (la biblioteca que proporciona `BarcodeGenerator`) + +## Paso 1: Instalar la biblioteca de códigos de barras + +Abre una terminal en la carpeta de tu proyecto y ejecuta: + +```bash +dotnet add package Aspose.BarCode +``` + +El paquete agrega el espacio de nombres `Aspose.BarCode`, que contiene `BarcodeGenerator` y la enumeración `EncodeTypes` necesaria para los códigos de barras postales. + +## Paso 2: Definir la carpeta de salida + +Crear una ruta de salida confiable evita errores en tiempo de ejecución cuando la carpeta no existe. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Por qué es importante*: `Directory.CreateDirectory` es idempotente—crea la carpeta solo si aún no está presente, evitando excepciones en ejecuciones posteriores. + +## Paso 3: Configurar dimensiones comunes del código de barras + +Establecer la X‑dimensión (ancho de una barra individual) y la altura total de la barra te permite controlar el tamaño visual de la imagen generada. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Cómo establecer las dimensiones del código de barras**: La propiedad `Parameters.Barcode.XDimension.Pixels` define el ancho de la barra estrecha, mientras que `Parameters.Barcode.BarHeight.Pixels` define la altura completa. Ajusta estos valores para cumplir con las especificaciones de tu servicio de mensajería. + +## Paso 4: Generar un código de barras Planet + +Planet es un código de barras postal ampliamente utilizado en el Reino Unido. El siguiente código crea un código de barras Planet de 100 px de alto y lo guarda como PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Por qué funciona**: `EncodeTypes.Planet` indica al generador que use la simbología Planet. El método `Save` escribe un archivo PNG en la ruta especificada, conservando las dimensiones que establecimos antes. + +## Paso 5: Generar un código de barras RM4SCC + +RM4SCC es el estándar de código de barras postal de los Países Bajos. El código a continuación replica el ejemplo de Planet, demostrando **cómo generar un código de barras postal** de un tipo diferente con dimensiones idénticas. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Ambos archivos PNG ahora se encuentran en la carpeta `Barcodes`. Al abrirlos verás códigos de barras limpios, de 100 px de alto, listos para imprimir o incrustar en documentos. + +## Código fuente completo + +A continuación se muestra el programa completo y ejecutable que **crea archivos de imagen de código de barras postal** para los estándares Planet y RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Salida esperada + +Ejecutar el programa muestra las rutas de los archivos y crea dos archivos PNG: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Cada imagen tiene 100 px de alto, con un ancho de barra estrecha de 4 píxeles, coincidiendo con las dimensiones que establecimos. + +## Consejos prácticos y errores comunes + +* **Permisos de carpeta** – Si el programa se ejecuta bajo una cuenta restringida, asegúrate de que la carpeta de destino sea escribible. +* **Dimensiones diferentes** – Para crear un código de barras más alto, aumenta `barHeightPixels`. Para mayor resolución, reduce `xDimensionPixels`, pero mantenlo ≥ 2 para evitar artefactos de renderizado. +* **Otras simbologías postales** – Aspose.BarCode también admite `EncodeTypes.Postnet` y `EncodeTypes.AustralianPost`. Cambia el valor de `EncodeTypes` y conserva la misma lógica de dimensiones. +* **Formato de imagen** – Usa `BarCodeImageFormat.Jpeg` para un tamaño de archivo menor cuando no se requiera calidad sin pérdida. + +## Conclusión + +Ahora sabes cómo **crear archivos de imagen de código de barras postal** en C# configurando dimensiones, seleccionando la simbología adecuada y guardando el resultado como PNG. El tutorial cubrió **cómo generar un código de barras postal**, demostró **generar un código de barras Planet**, y explicó **cómo establecer las dimensiones del código de barras** para una salida consistente. + +A continuación, explora **personalizar colores del código de barras**, agregar **texto legible por humanos**, o integrar las imágenes en facturas PDF. El mismo patrón se aplica a cualquier otro tipo de código de barras soportado por Aspose.BarCode, permitiéndote ampliar esta solución a un flujo de trabajo completo de automatización postal. + +## ¿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ódigos de barras - Tipos de códigos de barras unidimensionales](/barcode/english/net/one-dimensional-barcode-types/) +- [Cómo generar código de barras Aztec con relación de aspecto personalizada usando Aspose.BarCode para .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Cómo generar código de barras java – Código de Australia Post con Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/spanish/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..277528a0e --- /dev/null +++ b/barcode/spanish/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-08-03 +description: Cómo guardar códigos de barras en C# con un ejemplo paso a paso de generador + de códigos de barras. Aprende a generar códigos de barras Planet, establecer dimensiones + y exportar imágenes PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: es +lastmod: 2026-08-03 +og_description: Cómo guardar un código de barras en C# usando un ejemplo de generador + de códigos de barras. Este tutorial muestra cómo generar códigos de barras Planet, + configurar la dimensión X y exportar archivos PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Cómo guardar código de barras en C# – guía paso a paso +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Cómo guardar código de barras en C# – guía completa del generador de códigos + de barras +url: /es/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo guardar códigos de barras en C# – guía completa del generador de códigos de barras + +Guardar imágenes de códigos de barras en C# es un requisito frecuente cuando necesitas incrustar códigos de barras postales en facturas, etiquetas de envío o etiquetas de inventario. Esta guía te lleva a través de un flujo de trabajo práctico de **c# barcode generator**, desde la creación de un código de barras Planet hasta la exportación de archivos PNG con barras rellenas y barras vacías. + +Aprenderás a establecer el ancho de barra, alternar barras rellenas y manejar carpetas de salida de forma fiable. Al final del tutorial tendrás un **barcode generator example** completamente funcional que podrás copiar a cualquier proyecto .NET. + +## Lo que necesitarás + +Antes de escribir código, asegúrate de contar con: + +- .NET 6.0 SDK o posterior (el ejemplo funciona con .NET Core y .NET Framework) +- Visual Studio 2022 o cualquier IDE compatible con C# +- El paquete NuGet **Aspose.BarCode** (u otra biblioteca que admita `EncodeTypes.Planet`). Instálalo con: + +```bash +dotnet add package Aspose.BarCode +``` + +La biblioteca proporciona la clase `BarcodeGenerator` utilizada a lo largo de este tutorial. + +## Configuración del entorno de desarrollo + +Crea un nuevo proyecto de consola y agrega el espacio de nombres requerido: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +El espacio de nombres `System.IO` nos brinda `Directory.CreateDirectory`, que garantiza que la carpeta de salida exista antes de intentar escribir archivos. + +## Cómo guardar imágenes de códigos de barras con el generador de códigos de barras C# + +El núcleo de la solución es un pequeño conjunto de pasos que configuran un **código de barras Planet** y luego persisten la imagen en disco. Las siguientes secciones dividen el proceso en piezas manejables. + +### Paso 1: Definir la carpeta de salida + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**¿Por qué?** +Codificar una ruta de forma rígida puede provocar `DirectoryNotFoundException` en máquinas donde la carpeta no exista. `CreateDirectory` es idempotente: crea el directorio solo si falta, haciendo que el código sea seguro para ejecuciones repetidas. + +### Paso 2: Crear un generador de código de barras Planet (barras rellenas) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**¿Por qué?** +`EncodeTypes.Planet` indica a la biblioteca que produzca un código de barras postal Planet, ampliamente usado por los servicios de correo. La cadena `"123456"` es la carga de ejemplo; reemplázala con cualquier dato numérico requerido por tu lógica de negocio. + +### Paso 3: Configurar el ancho de barra (dimensión X) y mantener las barras rellenas por defecto + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**¿Por qué?** +La dimensión X controla el ancho físico de cada barra. Un valor de `4` píxeles produce un código de barras legible en impresoras estándar de 300 dpi. Dejar `FilledBars` como `true` (valor predeterminado) genera la apariencia clásica de barra sólida. + +### Paso 4: Guardar la imagen del código de barras con barras rellenas + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**¿Por qué?** +Guardar como PNG preserva la calidad de imagen sin pérdidas, lo cual es importante para la precisión del escaneo. El método `Save` crea automáticamente el archivo de imagen; solo necesitas proporcionar la ruta completa y el formato deseado. + +### Paso 5: Crear un segundo generador para la versión de barras vacías + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Crear una nueva instancia asegura que los cambios realizados para la versión de barras vacías no afecten a la imagen de barras rellenas ya guardada. + +### Paso 6: Desactivar las barras rellenas manteniendo la misma dimensión X + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**¿Por qué?** +Establecer `FilledBars = false` renderiza el código de barras solo con el contorno de cada barra, lo que algunos estándares postales requieren para la verificación visual. + +### Paso 7: Guardar la imagen del código de barras con barras vacías + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Ahora tienes dos archivos PNG—uno con barras rellenas y otro con barras vacías—listos para incluirse en PDFs, correos electrónicos HTML o etiquetas impresas. + +## Programa completo ejecutable + +A continuación se muestra el código completo que puedes copiar en `Program.cs`. Compila y se ejecuta sin modificaciones (asumiendo que el paquete Aspose.BarCode está instalado). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Salida esperada + +Al ejecutar el programa se imprimen dos líneas similares a: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Abre la carpeta `Barcodes` y verás los dos archivos PNG. Ambas imágenes pueden abrirse en cualquier visor de imágenes o incrustarse directamente en documentos. + +![cómo guardar código de barras ejemplo](barcode-example.png){: .align-center alt="cómo guardar código de barras ejemplo"} + +## Variaciones comunes y casos límite + +| Escenario | Ajuste | +|----------|------------| +| **Formato de imagen diferente** | Cambia `BarCodeImageFormat.Png` a `Jpeg`, `Gif` o `Bmp` según sea necesario. | +| **Tamaño de salida personalizado** | Usa `filled.Parameters.Image.Width` y `Height` para forzar una dimensión de píxel específica. | +| **Datos dinámicos** | Reemplaza el `"123456"` estático por una variable que contenga números de orden, IDs de seguimiento, etc. | +| **Carpeta inexistente** | `Directory.CreateDirectory` ya maneja carpetas faltantes; no se requiere código adicional. | +| **Impresión de alta resolución** | Incrementa `XDimension.Pixels` a 6–8 para impresoras de 600 dpi, pero verifica la compatibilidad del escáner. | + +**Consejo profesional:** Si necesitas generar muchos códigos de barras en un bucle, reutiliza una única instancia de `BarcodeGenerator` y solo cambia la propiedad `CodeText` antes de cada `Save`. Esto reduce la sobrecarga de asignación de objetos. + +## Cómo generar códigos de barras para otros estándares + +El mismo patrón funciona para otros `EncodeTypes` como `Code128`, `QR` o `DataMatrix`. Simplemente reemplaza `EncodeTypes.Planet` por el tipo deseado y ajusta cualquier parámetro específico del tipo (p. ej., `QRCodeVersion`). + +## ¿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. + +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [How to Generate Barcode – Code 39 Configuration with Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/swedish/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..3b84ef99f --- /dev/null +++ b/barcode/swedish/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-08-03 +description: Barcode‑generator C#‑handledning som visar hur man skapar Planet‑streckkod + med Aspose.BarCode, ställer in X‑dimension och sparar som PNG‑bilder. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: sv +lastmod: 2026-08-03 +og_description: Barcode‑generator C#‑handledning guidar dig genom att skapa en Planet‑streckkod, + justera X‑dimensionen och spara som PNG med Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Streckkodsgenerator C# – skapa Planet‑streckkod steg för steg +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Barcodegenerator C# – skapa Planet-streckkod och RM4SCC‑exempel +url: /sv/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – skapa Planet‑streckkod och RM4SCC‑exempel + +Om du behöver en **barcode generator C#** som kan producera post‑specifika symboler, visar den här guiden exakt hur du **skapar Planet‑streckkod**‑bilder med Aspose.BarCode. Du får se hur du konfigurerar X‑dimensionen, genererar en matchande RM4SCC‑streckkod och sparar båda som PNG‑filer – allt i några koncisa steg. + +Tutorialen täcker allt du behöver för att köra koden på .NET 6 eller senare, förklarar varför varje inställning är viktig och pekar på vanliga fallgropar såsom fel modulbredd eller saknade katalogbehörigheter. I slutet har du två färdiga streckkods‑bilder som kan skrivas ut och som följer Planet‑ och RM4SCC‑standarderna. + +## Förutsättningar + +Innan du börjar, se till att du har: + +* .NET 6 SDK (eller någon .NET‑version som stöds av Aspose.BarCode) +* Visual Studio 2022 eller någon C#‑IDE du föredrar +* Ett NuGet‑referens till **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Skrivbehörighet till den mapp där du planerar att lagra PNG‑filerna + +Inga ytterligare externa tjänster krävs; biblioteket hanterar all kodning lokalt. + +## Steg 1: Initiera barcode generator C#‑objektet + +Den första uppgiften är att skapa en instans av `BarcodeGenerator`. Konstruktorn tar streckkodssymbologin (`EncodeTypes.Planet`) och data som ska kodas. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Varför detta steg?* +`BarcodeGenerator` är startpunkten för varje streckkod du genererar. Genom att välja `EncodeTypes.Planet` talar du om för biblioteket att följa ISO/IEC 24723‑specifikationen som används av många posttjänster. + +## Steg 2: Ställ in X‑dimensionen (modulbredd) för Planet‑streckkoden + +X‑dimensionen definierar bredden på en enskild streckkodmodul (det minsta strecket eller mellanslaget). Ett värde på **4 pixlar** fungerar bra för de flesta etikett‑skrivare. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Varför detta är viktigt* +Om modulen är för smal kan streckkoden bli oläslig; om den är för bred växer etikettens storlek onödigt. Genom att justera `Pixels` kan du finjustera streckkoden för just din skrivarupplösning. + +## Steg 3: Spara Planet‑streckkoden som en PNG‑bild + +Aspose.BarCode beräknar automatiskt streckkodshöjden baserat på den valda symbologin, så du behöver bara ange filsökvägen och formatet. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tips* +Byt ut `YOUR_DIRECTORY` mot en absolut eller relativ sökväg som finns på din maskin. Om katalogen inte finns kastar `Save`‑metoden ett `DirectoryNotFoundException`. + +**Förväntad output** – en PNG‑fil som liknar illustrationen nedan (den faktiska bilden visas inte här, men du kommer att se en klassisk Planet‑streckkod med en numerisk payload på `123456`). + +## Steg 4: Initiera en andra generator för RM4SCC‑streckkoden + +Många postsystem kräver både Planet‑ och RM4SCC‑symboler på samma brev. Skapa en ny `BarcodeGenerator`‑instans för RM4SCC‑symbologin. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Varför en separat instans?* +Varje symbologi har sin egen uppsättning parametrar. Att återanvända samma generator kan oavsiktligt föra över inställningar (som X‑dimension) som inte är optimala för den andra streckkoden. + +## Steg 5: Konfigurera X‑dimensionen för RM4SCC‑streckkoden + +RM4SCC respekterar också X‑dimensionen, så vi använder samma pixelbredd för visuell konsistens. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro‑tips* +Om du behöver en högre streckkod (t.ex. för större etiketter) kan du också sätta `Height.Pixels`. Att låta den vara odefinierad låter biblioteket beräkna den ideala höjden automatiskt. + +## Steg 6: Spara RM4SCC‑streckkoden som en PNG‑bild + +Till sist sparar du RM4SCC‑streckkoden till disk. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Du har nu två PNG‑filer – `PostalPlanetBarHeightNone.png` och `PostalRM4SCCBarHeightNone.png` – som du kan bädda in i postetiketter, skriva ut på kuvert eller skicka till en tredjeparts‑trycktjänst. + +## Valfritt: Justera höjd eller använda andra bildformat + +Om ditt arbetsflöde kräver en specifik streckkodshöjd eller ett annat bildformat (t.ex. JPEG eller BMP) kan du ändra parametrarna innan du anropar `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Edge case** – När du sätter en anpassad höjd, se till att värdet uppfyller den minsta höjd som ISO‑standarden kräver; annars kan streckkoden misslyckas med valideringen. + +## Vanliga fallgropar och hur du undviker dem + +| Fallgrop | Varför det händer | Lösning | +|----------|-------------------|---------| +| `DirectoryNotFoundException` | Målkatalogen finns inte eller är felstavad. | Skapa katalogen först eller använd `Path.Combine` med `Environment.CurrentDirectory`. | +| Streckkod oläslig på lågupplösta skrivare | X‑dimension för liten för skrivarens DPI. | Öka `XDimension.Pixels` till 5 – 6 för 203 dpi‑skrivare, eller testa med en provetikett. | +| Fel symbologi använd | `EncodeTypes.Code128` skickas istället för `EncodeTypes.Planet`. | Dubbelkolla att `EncodeTypes`‑enum‑värdet matchar den krävs poststandard. | +| Null‑referens på `Parameters` | En äldre version av Aspose.BarCode där API:t skiljer sig. | Uppgradera till den senaste NuGet‑paketet (v23.12 eller senare). | + +## Fullt körbart exempel + +Nedan är hela programmet som du kan kopiera, klistra in och köra. Det inkluderar `using`‑satser, felhantering och kommentarer som förklarar varje rad. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +När du kör programmet skapas en `Barcodes`‑mapp bredvid den körbara filen och de två PNG‑filerna placeras där. Öppna dem med någon bildvisare för att verifiera resultatet. + +## Slutsats + +Du har nu en **barcode generator C#**‑lösning som kan **skapa Planet‑streckkod**‑bilder, justera X‑dimensionen för optimal utskrift och producera en matchande RM4SCC‑streckkod – allt med några få kodrader. Metoden fungerar med .NET 6+, kräver bara Aspose.BarCode‑NuGet‑paketet och kan utökas till andra symbologier som Code128, QR eller DataMatrix genom att byta `EncodeTypes`‑värdet. + +### Vad blir nästa steg? + +* Experimentera med olika `XDimension.Pixels`‑värden för att matcha din skrivar‑DPI. +* Generera streckkoder i andra format (PDF, SVG) genom att ändra `BarCodeImageFormat`‑enum. +* Kombinera de två PNG‑filerna till en enda etikett med ett grafikbibliotek som **SkiaSharp**. +* Utforska hela Aspose.BarCode‑API:t för avancerade funktioner som kontrollsiffra‑validering eller anpassade typsnitt. + +Känn dig fri att anpassa koden för batch‑bearbetning eller integrera den i en ASP.NET Core‑webbtjänst som returnerar streckkods‑bilder på begäran. Lycka till med kodningen! + +## Vad bör du lära dig härnäst? + +De följande handledningarna täcker närbesläktade ämnen som bygger vidare på teknikerna 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 implementationssätt i dina egna projekt. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/swedish/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..e48430538 --- /dev/null +++ b/barcode/swedish/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: Barcode‑generator C#‑handledning visar hur man genererar streckkodsbilder + med Aspose.BarCode, ställer in kolumner och rader samt sparar PNG‑filer för DataBar + Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: sv +lastmod: 2026-08-03 +og_description: Barcode generator C#‑handledning förklarar hur man genererar en streckkodbild + med Aspose.BarCode, konfigurerar DataBar Expanded Stacked‑kolumner och -rader samt + sparar PNG‑filer. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Streckkodsgenerator C# – steg‑för‑steg guide för att generera streckkodsbild +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Streckkodsgenerator C# – generera streckkodsbild +url: /sv/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – generera streckkodsbild + +Om du behöver en barcode generator C# som kan generera streckkodsbild för DataBar Expanded Stacked, guidar den här artikeln dig genom hela processen. Du kommer att lära dig hur du konfigurerar kolumn‑ och radinställningar, sparar resultatet som PNG och anpassar koden för andra symbologier. + +Att programatiskt generera streckkodsbilder eliminerar manuella steg och säkerställer konsekvens i fakturor, fraktetiketter och lagersystem. Denna handledning täcker allt du behöver, från projektuppsättning till fullständig källkod, så att du kan köra exemplet omedelbart. + +## Förutsättningar + +Innan du börjar, se till att du har: + +* .NET 6.0 eller senare installerat +* En IDE såsom Visual Studio 2022 (vilken editor som helst som stödjer C# fungerar) +* En licens för **Aspose.BarCode for .NET** – den kostnadsfria utvärderingen fungerar för testning +* Grundläggande kunskap om C#‑syntax + +Om någon av dessa komponenter saknas, installera .NET SDK från dotnet.microsoft.com och hämta Aspose.BarCode NuGet‑paketet med: + +```bash +dotnet add package Aspose.BarCode +``` + +## Steg 1: Skapa ett barcode generator C#‑projekt + +Skapa en ny konsolapplikation och lägg till de nödvändiga `using`‑direktiven: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +Klassen `BarcodeGenerator` är kärnan i barcode generator C#‑API:et. Den tar emot symbology‑typen och texten som ska kodas. + +## Steg 2: Generera en DataBar Expanded Stacked‑streckkod och ange kolumner + +Det första exemplet skapar en streckkod med fyra kolumner. Genom att justera egenskapen `Columns` förändras den visuella tätheten i DataBar Expanded Stacked‑symbologin. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Varför detta är viktigt:** Antalet kolumner påverkar hur mycket data som kan lagras i ett kompakt utrymme. Att sätta det till 4 ger en bredare streckkod som fortfarande är läsbar av de flesta skannrar. + +## Steg 3: Generera en streckkod med anpassat radantal + +Det andra exemplet visar hur du styr den vertikala layouten genom att sätta egenskapen `Rows`. En konfiguration med tre rader är användbar när du behöver en högre streckkod för begränsat horisontellt utrymme. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Varför detta är viktigt:** Genom att justera rader kan du passa streckkoden i en smal kolumn samtidigt som läsbarheten bevaras. barcode generator C# beräknar automatiskt modulstorleken för att uppfylla specifikationen. + +## Steg 4: Fullständigt, körbart exempel + +Nedan finns ett fristående program som kombinerar de föregående stegen. Kopiera koden till `Program.cs`, ersätt `YOUR_DIRECTORY` med en befintlig mappväg och kör applikationen. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Förväntat resultat + +När du kör programmet visas två PNG‑filer i mål‑katalogen: + +* **DatabarCols4.png** – en DataBar Expanded Stacked‑streckkod med fyra kolumner +* **DatabarRows3.png** – samma data kodad i tre rader + +Öppna bilderna med någon bildvisare; de visar skarpa, skannbara streckkoder redo för utskrift eller inbäddning i PDF‑filer. + +## Hur du genererar streckkodsbild med anpassade dimensioner + +Om du behöver en specifik bildstorlek, justera egenskaperna `ImageHeight` och `ImageWidth` innan du anropar `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Att ändra dimensioner påverkar inte den kodade datan; det skalar bara den visuella representationen. Denna teknik är användbar när streckkoder integreras i UI‑komponenter med fasta layout‑restriktioner. + +## Vanliga fallgropar och pro‑tips + +* **Sökvägsseparatorer:** Använd verbatim‑strängar (`@"C:\Path\file.png"`) eller `Path.Combine` för att undvika escape‑tecken‑problem på Windows. +* **Licens‑verkställighet:** Utan en giltig licens innehåller de genererade bilderna ett vattenmärke. Applicera din licens tidigt i applikationen: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Kodningsgränser:** DataBar Expanded Stacked stödjer upp till 74 numeriska tecken. Att överskrida denna gräns kastar ett undantag. Validera inmatningslängden innan du skapar generatorn. +* **Prestanda:** Återanvänd en enda `BarcodeGenerator`‑instans för flera sparningar för att minska minnesallokering. Ändra endast `Rows` eller `Columns` mellan sparningar om den kodade texten förblir densamma. + +## Nästa steg + +Nu när du kan generera streckkodsbilder med barcode generator C#, överväg att utforska: + +* **Olika symbologier** – prova `EncodeTypes.QR`, `EncodeTypes.Code128` eller `EncodeTypes.Pdf417`. +* **Färganpassning** – sätt `Parameters.Barcode.ForeColor` och `BackColor` för att matcha varumärket. +* **Inbäddning i PDF‑filer** – kombinera den genererade PNG‑filen med Aspose.PDF för att skapa utskrivbara dokument. + +Dessa tillägg låter dig bygga en fullständigt funktionell streckkodslösning för lager, logistik eller detaljhandelsapplikationer. + +--- + + +## Vad bör du lära dig härnäst? + + +Följande handledningar täcker närbesläktade ämnen som bygger vidare 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. + +- [Generera streckkodsbild – GS1 Coupon UPC‑A Databar](/barcode/english/net/gs1-barcode-encoding/gs1-coupon-upc-a-databar-configuration/) +- [Skapa DotCode streckkod – rader & kolumner (Aspose.BarCode)](/barcode/english/net/dotcode-barcode-configuration/dotcode-rows-columns-configuration/) +- [Hur man genererar DataMatrix‑streckkoder (ECC 200) med Aspose.BarCode för .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/swedish/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..49e5d262a --- /dev/null +++ b/barcode/swedish/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-08-03 +description: Barcode‑generatorexempel i C# som visar hur man ställer in bredd, hur + man ändrar höjd och hur man genererar en streckkodsbild. Följ steg‑för‑steg‑instruktionerna. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: sv +lastmod: 2026-08-03 +og_description: Barcode‑generator‑exemplet visar hur man ställer in X‑dimensionens + bredd, ändrar stapelhöjden och genererar en streckkodbild i C#. Följ stegen för + att skapa PNG‑filer. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Exempel på streckkodsgenerator – C#‑guide för bredd och höjd +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Exempel på streckkodsgenerator i C# – ange bredd och höjd +url: /sv/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode‑generatorexempel i C# – ange bredd och höjd + +Om du behöver ett **barcode generator example** i C#, visar den här guiden hur du ställer in X‑dimensionens bredd, hur du ändrar stapelhöjden och hur du genererar en streckkodsbildfil. Du kommer att se ett komplett, körbart program som producerar två PNG‑filer med olika höjder. + +Ett typiskt scenario är att skapa produktetiketter där streckkodens storlek måste uppfylla scannerspecifikationer. I slutet av den här handledningen kommer du att kunna justera bredd‑ och höjdpunkter programatiskt och spara resultatet som en PNG‑bild. + +## Förutsättningar + +* .NET 6 (eller senare) installerat – koden riktar sig mot .NET 6 SDK. +* Ett streckkodsbibliotek som stöder `EncodeTypes.DatabarOmniDirectional`. Exemplet använder **Aspose.BarCode for .NET**, men vilket bibliotek som helst som exponerar liknande egenskaper fungerar på samma sätt. +* En IDE eller redigerare (Visual Studio, VS Code, Rider) för att kompilera och köra programmet. +* Skrivrättighet till en katalog där PNG‑filerna kommer att sparas. + +> **Pro tip:** Skapa en mapp med namnet `Barcodes` i projektets rot och referera till den med `Path.Combine` för att undvika hårdkodade absoluta sökvägar. + +## Barcode‑generatorexempel: initiera och konfigurera + +Det första steget är att skapa en `BarcodeGenerator`‑instans med önskad symbologi och datasträng. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +`EncodeTypes.DatabarOmniDirectional`‑enumet väljer Databar Omni‑directional‑symbologi, och den GS1‑formaterade datasträngen `(01)12345678901231` representerar ett typiskt GTIN‑14‑värde. Att initiera generatorn en gång gör att du kan återanvända samma objekt för flera bilder. + +## Hur man ställer in bredd (X‑dimension) + +X‑dimensionen styr modulbredden på streckkoden. Att sätta den till 2 pixlar gör varje smal stapel 2 pixlar bred, vilket är ett vanligt krav för högdensitetstryck. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Varför detta är viktigt: Om bredden är för liten kan scanners ha svårt att lösa enskilda staplar; om den är för stor kan streckkoden överskrida etikettutrymmet. Justera pixelvärdet så att det matchar skrivarens DPI och den önskade etikettstorleken. + +## Hur man ändrar höjd + +Stapelhöjden bestämmer hur höga staplarna visas. Exemplet skapar två bilder: en med 30 pixelhöjd och en annan med 60 pixelhöjd. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +`BarHeight.Pixels`‑egenskapen påverkar direkt den visuella höjden på staplarna. Att ändra den mellan sparningar låter dig generera flera varianter från samma datapayload utan att återskapa generatorn. + +### Förväntat resultat + +När programmet körs produceras två PNG‑filer i mappen `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – staplarna är 30 pixlar höga. +* `DatabarBarHeight60Pixels.png` – staplarna är 60 pixlar höga. + +Båda bilderna har samma bredd (bestämd av X‑dimensionen) och kodar samma GTIN‑14‑data. + +![Två streckkod PNG-filer med olika höjder genererade av C#‑kod](barcode-example.png "Barcode‑generatorexempel som visar höjdvariationer") + +*Bildens alt‑text ovan innehåller det primära nyckelordet för tillgänglighet och SEO.* + +## Hur man genererar streckkodsbild i C# + +`Save`‑metoden hanterar konverteringen från streckkodsdata till en bildfil. Du kan välja andra format (JPEG, BMP, SVG) genom att skicka ett annat `BarCodeImageFormat`‑enum‑värde. Exemplet använder PNG eftersom det bevarar förlustfri kvalitet och är brett stödjat. + +Om du behöver bädda in streckkoden direkt i en PDF eller en webbsida, hämta bilden som en `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Detta tillvägagångssätt eliminerar behovet av temporära filer och är användbart för högkapacitets‑tjänster. + +## Vanliga variationer och kantfall + +| Situation | Anpassning | +|-----------|------------| +| **Olika symbologi** | Byt ut `EncodeTypes.DatabarOmniDirectional` mot ett annat enum‑värde (t.ex. `EncodeTypes.Code128`). | +| **Mycket små etiketter** | Minska `XDimension.Pixels` till 1 pixel, men verifiera scanners läsbarhet. | +| **Högupplöst utskrift** | Öka både X‑dimension och stapelhöjd proportionellt (t.ex. 4 px bredd, 80 px höjd). | +| **Dynamisk data** | Skicka datasträngen vid körning, kanske från en databaspost. | +| **Batch‑generering** | Loopa över en samling datasträngar, återanvänd samma `BarcodeGenerator`‑instans medan du uppdaterar `generator.Text`. | + +När du stöter på ett undantag som `ArgumentOutOfRangeException`, dubbelkolla att pixelvärdena är positiva heltal och att utmatningskatalogen finns. + +## Fullständig källkodssammanfattning + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Kopiera koden till ett nytt konsolprojekt, återställ Aspose.BarCode‑NuGet‑paketet (`dotnet add package Aspose.BarCode`), och kör `dotnet run`. Du kommer att se konsolloggar som bekräftar de sparade filerna. + +## Slutsats + +Detta **barcode generator example** visar hur man ställer in bredd, hur man ändrar höjd och hur man genererar en streckkodsbild i C#. Genom att justera `XDimension.Pixels` och `BarHeight.Pixels` styr du den visuella storleken på streckkoden, och `Save`‑metoden skriver resultatet till PNG‑filer. Experimentera med olika symbologier, utdataformat och datasträngar för att passa dina applikationskrav. + +**Next steps** + +* Utforska **how to generate barcode** i andra bildformat (SVG, JPEG) för webbbruk. +* Lär dig **create barcode image c#** för ASP.NET Core‑endpoints som returnerar PNG‑filen direkt till en webbläsare. +* Kombinera denna kod med ett PDF‑genereringsbibliotek för att bädda in streckkoder i fakturor eller fraktetiketter. + +Känn dig fri att anpassa exemplet, dela dina resultat eller ställa frågor i kommentarerna. Lycka till med kodandet! + +## 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 behärska ytterligare API‑funktioner och utforska alternativa implementeringsmetoder i dina egna projekt. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to Set Border for ITF-14 Barcode Customization](/barcode/english/net/itf-14-barcode-customization/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/swedish/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..80cc08068 --- /dev/null +++ b/barcode/swedish/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-08-03 +description: Skapa streckkod‑PNG i C# och lär dig hur du ändrar bildförhållandet för + DataBar‑bilder. Följ detta kompletta exempel med kod och tips. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: sv +lastmod: 2026-08-03 +og_description: Skapa streckkod PNG i C# och se hur du ändrar bildförhållandet för + DataBar‑streckkoder. Denna guide ger dig färdig‑körbar kod och praktiska tips. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Skapa streckkod PNG i C# – fullständigt exempel med kontroll av bildförhållande +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Skapa streckkod PNG i C# – steg‑för‑steg guide +url: /sv/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa streckkod PNG i C# – steg‑för‑steg guide + +Om du behöver **skapa streckkod PNG** i C#, visar den här handledningen exakt hur du gör. Du kommer att generera en staplad omnidirektionell DataBar‑streckkod, spara den som en PNG‑fil och lära dig **hur du ändrar bildförhållandet** för att passa olika skanningsmiljöer. + +Guiden täcker allt du behöver: nödvändiga paket, ett komplett, körbart program och förklaringar till varför varje inställning är viktig. I slutet kommer du att ha två PNG‑filer—en med ett bildförhållande på 15 och en annan med 30—klara för testning eller produktionsbruk. + +## Förutsättningar + +Innan du börjar, se till att du har: + +- .NET 6.0 SDK eller senare installerat +- Visual Studio 2022 (eller någon C#‑IDE) +- En NuGet‑referens till **Aspose.BarCode** (biblioteket som tillhandahåller `BarcodeGenerator`) +- Skrivbehörighet till den katalog där PNG‑filerna kommer att sparas + +Du kan lägga till Aspose.BarCode‑paketet med följande kommando: + +```bash +dotnet add package Aspose.BarCode +``` + +## Steg 1: Ställ in projektet och importera namnrymder + +Skapa en ny konsolapplikation och importera de namnrymder som krävs för streckkodsgenerering och fil‑I/O. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Varför detta är viktigt:** Att importera `Aspose.BarCode.Generation` ger dig åtkomst till `BarcodeGenerator`. Att hålla koden inom `Main` gör exemplet självständigt och enkelt att köra. + +## Steg 2: Skapa en streckkodsgenerator för en staplad omnidirektionell DataBar + +Instansiera `BarcodeGenerator` med typen `EncodeTypes.DatabarStackedOmniDirectional` och en exempel‑GS1‑128‑datatsträng. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Varför detta är viktigt:** Den valda kodningstypen producerar en högdensitets‑DataBar som kan läsas av de flesta moderna skannrar. Datatsträngen följer GS1 Application Identifier (01)-formatet, vilket är vanligt för produktidentifierare. + +## Steg 3: Definiera X‑dimensionen (modulbredd) i pixlar + +Ställ in modulbredden för att kontrollera streckkodens totala storlek utan att påverka läsbarheten. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Varför detta är viktigt:** En X‑dimension på 2 pixlar ger en streckkod som varken är för liten för skannrar eller för stor för vanliga etikettutrymmen. + +## Steg 4: Spara den första PNG‑filen med ett bildförhållande på 15 + +Justera DataBar‑bildförhållandet och spara sedan bilden som en PNG‑fil. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Varför detta är viktigt:** Bildförhållandet styr förhållandet mellan höjd och bredd för den staplade DataBar. Ett förhållande på 15 är en vanlig standard som balanserar läsbarhet och etikettens höjd. + +## Steg 5: Ändra bildförhållandet till 30 och spara en andra PNG + +Ändra samma generatorinstans för att använda ett större bildförhållande och spara sedan den andra bilden. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Varför detta är viktigt:** Att öka bildförhållandet sträcker streckkoden vertikalt, vilket kan förbättra skanningspålitligheten på lågupplösta enheter eller när etiketten skrivs ut på smalt material. + +## Förväntat resultat + +När programmet körs skapas två PNG‑filer: + +| Fil | Bildförhållande | Ungefärliga dimensioner (pixlar) | +|------------------------------------|-----------------|---------------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (bredd × höjd) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (bredd × höjd) | + +Båda bilderna innehåller en tydlig, skannbar DataBar‑streckkod som kodar GS1‑identifieraren `(01)12345678901231`. + +## Vanliga frågor och kantfall + +### Hur ändrar man andra visuella egenskaper? + +Du kan justera förgrundsfärg, bakgrundsfärg eller lägga till mänskligt läsbar text via objektet `generator.Parameters.Barcode`. Till exempel: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Vad gör jag om jag behöver ett annat bildformat? + +Byt ut `BarCodeImageFormat.Png` mot `Jpeg`, `Bmp` eller `Gif` efter behov. PNG förblir det bästa valet för förlustfria streckkods‑bilder. + +### Påverkar bildförhållandet skanningshastigheten? + +Högre bildförhållanden ökar streckkodens höjd, vilket kan förbättra skanningspålitligheten på enheter som har problem med korta staplade symboler. Däremot kan extremt höga streckkoder vara för stora för små etiketter, så testa med din mål‑hardware. + +### Kan jag generera flera streckkoder i en loop? + +Ja. Skapa en ny `BarcodeGenerator`‑instans för varje datatsträng eller återanvänd samma instans genom att uppdatera `CodeText` och `DataBar.AspectRatio`. Detta tillvägagångssätt minskar overheaden för objektallokering. + +## Pro‑tips + +- **Återanvänd generatorn**: Att bara ändra `CodeText` eller `AspectRatio` undviker att återinstansiera objektet, vilket snabbar upp batch‑bearbetning. +- **Validera resultatet**: Använd en handhållen scanner eller en mobilapp för att bekräfta att den genererade PNG‑filen läses korrekt innan du går i produktion. +- **Filnamngivning**: Inkludera bildförhållandet i filnamnet (som visas) för att hålla reda på variationer under testning. + +## Slutsats + +Du vet nu hur du **skapar streckkod PNG**‑filer i C# och exakt **hur du ändrar bildförhållandet** för staplade omnidirektionella DataBar‑symboler. Det kompletta exemplet demonstrerar initiering, inställning av X‑dimension, manipulation av bildförhållande och bildsparande—allt i ett enda körbart program. + +Härifrån kan du utforska ytterligare streckkodstyper, experimentera med färger eller integrera generatorn i ett större rapporterings‑ eller lagersystem. 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 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 streckkod PNG – DataMatrix bildförhållande – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Hur man genererar Aztec‑streckkod med anpassat bildförhållande med Aspose.BarCode för .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Hur man anpassar streckkod – Codablock F bildförhållande med Aspose.BarCode för .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/swedish/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..0cf35059d --- /dev/null +++ b/barcode/swedish/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-08-03 +description: Skapa streckkod‑PNG snabbt med den här guiden. Lär dig hur du genererar + en streckkodsbild med Aspose.BarCode och skapar en planet‑streckkod. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: sv +lastmod: 2026-08-03 +og_description: Skapa streckkod PNG omedelbart. Den här handledningen visar hur man + genererar en streckkodbild och skapar planet‑streckkod med Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Skapa streckkod PNG i Python – komplett programmeringsguide +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Skapa streckkod PNG i Python – steg‑för‑steg guide +url: /sv/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa barcode PNG i Python – steg‑för‑steg guide + +Om du behöver **skapa barcode PNG**‑filer från ditt Python‑program visar den här handledningen exakt hur. Vi går igenom **hur man genererar barcode image** med Aspose.BarCode och specifikt **generera planet barcode** med anpassade dimensioner. + +Du kommer att lära dig hur du installerar biblioteket, konfigurerar Planet‑symbologi, justerar storleksparametrar och sparar resultatet som en högkvalitativ PNG. Guiden förutsätter grundläggande kunskaper i Python och en recent version av Python 3 (3.8 eller nyare). Ingen tidigare erfarenhet av barcode‑standarder krävs. + +--- + +## Så skapar du barcode PNG med Aspose.BarCode + +Detta avsnitt innehåller de grundläggande stegen som krävs för att **skapa barcode PNG**. Varje steg inkluderar ett kodexempel, en förklaring till varför det är viktigt, och praktiska tips du kan tillämpa omedelbart. + +### 1. Installera Aspose.BarCode‑paketet + +Aspose tillhandahåller ett rent Python‑paket som omsluter dess .NET‑kärnmotor. Installera det med `pip`: + +```bash +pip install aspose-barcode +``` + +*Varför detta steg är viktigt:* Paketet tillhandahåller klassen `BarcodeGenerator` som används genom hela exemplet. Att installera det globalt säkerställer att tolken kan hitta assemblyn vid körning. + +### 2. Importera nödvändiga klasser + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Tips:* Importera endast de symboler du behöver; detta håller namnrymden ren och snabbar upp modulens laddning. + +### 3. Skapa en barcode‑generator för Planet‑symbologi + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Varför detta är viktigt:* `EncodeTypes.Planet` instruerar motorn att använda Planet‑barcode‑standarden, medan det andra argumentet tillhandahåller data som ska kodas. Att ändra symbologin (t.ex. `EncodeTypes.Code128`) skulle producera ett helt annat visuellt mönster. + +### 4. Ställ in X‑dimensionen (modulbredd) i pixlar + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Förklaring:* X‑dimensionen styr den smala stapelns bredd. Ett värde på 4 pixlar ger en måttligt tät barcode som fortfarande kan skannas på de flesta enheter. + +### 5. Definiera en manuell stapelhöjd i pixlar + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Varför du kan vilja justera detta:* Vissa detaljhandels‑skrivare kräver högre staplar för pålitlig skanning. Standardhöjden är vanligtvis 50 px; att öka den till 100 px förbättrar läsbarheten utan att filstorleken ökas dramatiskt. + +### 6. Spara den genererade barcode som en PNG‑bild + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Resultat:* En PNG‑fil med namnet **PlanetBarHeight100.png** visas i mappen `output`. PNG är förlustfri, vilket gör den idealisk för utskrift och för inbäddning i webbsidor. + +### 7. Verifiera resultatet (valfritt) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Tips:* Att visa bilden bekräftar att dimensionerna matchar de parametrar du angav. Om barcode ser förvrängd ut, gå tillbaka till X‑dimensionen eller stapelhöjdsinställningarna. + +--- + +## Hur man genererar barcode‑bild i PNG‑format (alternativa inställningar) + +Om du behöver ett annat bildformat eller vill bädda in barcode i en PDF senare, kan du ändra `BarCodeImageFormat`‑enumet: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Varför detta är viktigt:* PNG bevarar varje pixel, vilket är avgörande för högkontrast‑barcode. JPEG introducerar komprimeringsartefakter som kan störa skanning, medan BMP erbjuder kompatibilitet med äldre verktyg. + +--- + +## Generera planet barcode med anpassade färger (avancerat) + +Förutom storlek kan du anpassa förgrunds‑ och bakgrundsfärger: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Praktiskt tips:* Högkontrast‑färgpar (mörkt på ljust) maximerar skannerns pålitlighet. Undvik att använda liknande nyanser för förgrund och bakgrund. + +--- + +## Vanliga fallgropar och hur man undviker dem + +| Symptom | Orsak | Lösning | +|---------|-------|-----| +| Barcode does not scan | X‑dimension för liten (≤ 2 px) | Öka `x_dimension.pixels` till minst 3 px | +| Bild blir suddig | PNG sparad med låg DPI | Använd `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` för att ange 300 DPI (om stöds) | +| Undantag `ImportError` | Aspose.BarCode är inte installerat | Kör `pip install aspose-barcode` i samma miljö som ditt skript | +| Fel symbologi | Använde `EncodeTypes.Code128` istället för `EncodeTypes.Planet` | Byt till `EncodeTypes.Planet` när generatorn skapas | + +--- + +## Sammanfattning av den kompletta lösningen + +Nedan är det fullständiga, körbara skriptet som **skapar barcode PNG** från början till slut: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Att köra detta skript producerar en skarp **Planet barcode PNG** som du kan bädda in i HTML, bifoga i e‑mail eller skriva ut på produktetiketter. + +--- + +## Nästa steg och relaterade ämnen + +* **Integrera med Flask eller Django** – servera den genererade PNG‑filen direkt från en webb‑endpoint. +* **Batch‑generering** – loopa över en lista med produkt‑ID:n för att skapa en mapp med barcode PNG‑filer. +* **Kombinera med PDF‑generering** – använd `aspose-pdf` för att placera PNG‑filen i en faktura eller fraktetikett. +* **Utforska andra symbologier** – ersätt `EncodeTypes.Planet` med `EncodeTypes.QR`, `EncodeTypes.DataMatrix` eller `EncodeTypes.Code128` för att möta olika affärsbehov. + +Genom att behärska stegen ovan vet du nu **hur man genererar barcode image** programatiskt och kan utöka mönstret till vilken barcode‑standard som helst som stöds av Aspose.BarCode. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/swedish/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..594a23439 --- /dev/null +++ b/barcode/swedish/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-08-03 +description: Skapa poststreckkodbild i C# snabbt. Lär dig hur du genererar en poststreckkod, + ställer in streckkodens dimensioner och genererar en Planet‑streckkod. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: sv +lastmod: 2026-08-03 +og_description: Skapa en poststreckkodsbild i C# med den här kompletta handledningen; + lär dig hur du ställer in streckkodens dimensioner, genererar en Planet‑streckkod + och producerar RM4SCC‑streckkoder. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Skapa poststreckkodbild i C# – fullständig programmeringsguide +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Skapa poststreckkodsbild i C# – steg‑för‑steg‑guide +url: /sv/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa poststreckkod bild i C# – steg‑för‑steg guide + +Om du behöver **skapa poststreckkod bild** i C#, visar den här guiden exakt hur du gör. Vi går igenom **hur man genererar poststreckkod**, **hur man ställer in streckkodens dimensioner**, och hur man **genererar planet‑streckkod** för vanliga poststandarder. + +Du avslutar med två färdiga PNG‑filer – en Planet‑streckkod och en RM4SCC‑streckkod – båda 100 px höga. Inga extra verktyg behövs utöver Aspose.BarCode för .NET‑biblioteket. + +## Förutsättningar + +* .NET 6 SDK eller senare (koden fungerar också med .NET Framework 4.7+) +* Visual Studio 2022 eller någon C#‑IDE +* NuGet‑paketet **Aspose.BarCode** (biblioteket som tillhandahåller `BarcodeGenerator`) + +## Steg 1: Installera streckkodsbiblioteket + +Öppna en terminal i din projektmapp och kör: + +```bash +dotnet add package Aspose.BarCode +``` + +Paketet lägger till `Aspose.BarCode`‑namnutrymmet, som innehåller `BarcodeGenerator` och uppräkningen `EncodeTypes` som behövs för poststreckkoder. + +## Steg 2: Definiera utdatamappen + +Att skapa en pålitlig sökväg för utdata förhindrar körningsfel när mappen inte finns. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Varför detta är viktigt*: `Directory.CreateDirectory` är idempotent – den skapar mappen endast om den ännu inte finns, vilket undviker undantag vid efterföljande körningar. + +## Steg 3: Konfigurera vanliga streckkodsdimensioner + +Genom att ange X‑dimensionen (bredden på en enskild stapel) och den totala stapelhöjden kan du kontrollera den visuella storleken på den genererade bilden. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Hur man ställer in streckkodsdimensioner**: Egenskapen `Parameters.Barcode.XDimension.Pixels` definierar den smala stapelns bredd, medan `Parameters.Barcode.BarHeight.Pixels` definierar den fulla höjden. Justera dessa värden för att uppfylla specifikationerna för din posttjänst. + +## Steg 4: Generera en Planet‑streckkod + +Planet är en mycket använd poststreckkod i Storbritannien. Följande kod skapar en 100 px‑hög Planet‑streckkod och sparar den som PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Varför detta fungerar**: `EncodeTypes.Planet` talar om för generatorn att använda Planet‑symboliken. Metoden `Save` skriver en PNG‑fil till den angivna sökvägen och bevarar de dimensioner vi satte tidigare. + +## Steg 5: Generera en RM4SCC‑streckkod + +RM4SCC är den nederländska poststreckkodstandarden. Koden nedan speglar Planet‑exemplet och visar **hur man genererar poststreckkod** av en annan typ med identiska dimensioner. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Båda PNG‑filerna ligger nu i mappen `Barcodes`. När du öppnar dem ser du rena, 100 px‑höga streckkoder som är redo för utskrift eller inbäddning i dokument. + +## Fullständig källkod + +Nedan finns det kompletta, körbara programmet som **skapar poststreckkod bild**‑filer för både Planet‑ och RM4SCC‑standarderna. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Förväntad output + +När programmet körs skrivs filvägarna ut och två PNG‑filer skapas: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Varje bild är 100 px hög, med en 4‑pixel bred smal stapel, vilket matchar de dimensioner vi satte. + +## Praktiska tips och vanliga fallgropar + +* **Mappbehörigheter** – Om programmet körs under ett begränsat konto, se till att mål‑mappen är skrivbar. +* **Olika dimensioner** – För att skapa en högre streckkod, öka `barHeightPixels`. För finare upplösning, minska `xDimensionPixels`, men håll den ≥ 2 för att undvika renderingsartefakter. +* **Andra post‑symboliker** – Aspose.BarCode stödjer även `EncodeTypes.Postnet` och `EncodeTypes.AustralianPost`. Byt ut värdet på `EncodeTypes` och behåll samma dimensionslogik. +* **Bildformat** – Använd `BarCodeImageFormat.Jpeg` för mindre filstorlek när förlustfri kvalitet inte krävs. + +## Slutsats + +Du vet nu hur du **skapar poststreckkod bild**‑filer i C# genom att konfigurera dimensioner, välja rätt symbolik och spara resultatet som PNG. Handledningen täckte **hur man genererar poststreckkod**, demonstrerade **generera planet‑streckkod**, och förklarade **hur man ställer in streckkodsdimensioner** för konsekvent output. + +Nästa steg: utforska **anpassning av streckkodsfärger**, lägga till **mänskligt läsbar text**, eller integrera bilderna i PDF‑fakturor. Samma mönster gäller för alla andra streckkodstyper som stöds av Aspose.BarCode, så att du kan utöka denna lösning till ett komplett postautomatiseringsflöde. + + +## Vad bör du lära dig härnäst? + + +Följande handledningar täcker närbesläktade ämnen som bygger vidare 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. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to generate barcode java – Australia Post Barcode with Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/swedish/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..e0523c6a4 --- /dev/null +++ b/barcode/swedish/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-08-03 +description: Hur man sparar streckkod i C# med ett steg‑för‑steg-exempel på streckkodsgenerator. + Lär dig att generera Planet‑streckkoder, ställa in dimensioner och exportera PNG‑bilder. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: sv +lastmod: 2026-08-03 +og_description: Hur man sparar streckkod i C# med ett streckkodsgeneratorexempel. + Denna handledning visar hur man genererar Planet‑streckkoder, konfigurerar X‑dimension + och exporterar PNG‑filer. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Hur man sparar streckkod i C# – steg‑för‑steg guide +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Hur man sparar streckkod i C# – komplett guide till streckkodsgenerator +url: /sv/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man sparar streckkod i C# – komplett guide för streckkodsgenerator + +Att spara streckkodsbilder i C# är ett vanligt krav när du behöver bädda in poststreckkoder i fakturor, fraktetiketter eller lageretiketter. Denna guide går igenom ett praktiskt **c# barcode generator**‑arbetsflöde, från att skapa en Planet‑streckkod till att exportera både fyllda‑staplar och tomma‑staplar PNG‑filer. + +Du kommer att lära dig hur du ställer in stapelbredden, växlar fyllda staplar och hanterar utdatamappar på ett pålitligt sätt. I slutet av handledningen har du ett fullt fungerande **barcode generator example** som du kan kopiera till vilket .NET‑projekt som helst. + +## Vad du behöver + +- .NET 6.0 SDK eller senare (exemplet fungerar med .NET Core och .NET Framework) +- Visual Studio 2022 eller någon C#‑kompatibel IDE +- **Aspose.BarCode** NuGet‑paketet (eller ett annat bibliotek som stödjer `EncodeTypes.Planet`). Installera det med: + +```bash +dotnet add package Aspose.BarCode +``` + +Biblioteket tillhandahåller klassen `BarcodeGenerator` som används genom hela handledningen. + +## Konfigurera utvecklingsmiljön + +Skapa ett nytt konsolprojekt och lägg till det erforderliga namnutrymmet: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +`System.IO`‑namnutrymmet ger oss `Directory.CreateDirectory`, vilket säkerställer att utdatamappen finns innan vi försöker skriva filer. + +## Hur man sparar streckkodsbilder med C#‑streckkodsgeneratorn + +Kärnan i lösningen är en liten uppsättning steg som konfigurerar en **Planet barcode** och sedan sparar bilden till disk. Följande avsnitt delar upp processen i hanterbara delar. + +### Steg 1: Definiera utdatamappen + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Varför?** +Att hårdkoda en sökväg kan orsaka `DirectoryNotFoundException` på maskiner där mappen inte finns. `CreateDirectory` är idempotent – den skapar katalogen endast om den saknas, vilket gör koden säker för upprepade körningar. + +### Steg 2: Skapa en Planet‑streckkodsgenerator (fyllda staplar) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Varför?** +`EncodeTypes.Planet` instruerar biblioteket att producera en post-Planet‑streckkod, som är allmänt använd av posttjänster. Strängen `"123456"` är ett exempel på data; ersätt den med valfri numerisk data som krävs av din affärslogik. + +### Steg 3: Konfigurera stapelbredd (X‑dimension) och behåll standardinställning för fyllda staplar + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Varför?** +X‑dimensionen styr den fysiska bredden på varje stapel. Ett värde på `4` pixlar ger en läsbar streckkod på standard 300 dpi‑skrivare. Att låta `FilledBars` vara `true` (standard) ger det klassiska solida stapelutseendet. + +### Steg 4: Spara bilden med fyllda staplar + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Varför?** +Att spara som PNG bevarar förlustfri bildkvalitet, vilket är viktigt för skanningsnoggrannhet. `Save`‑metoden skapar automatiskt bildfilen; du behöver bara ange hela sökvägen och önskat format. + +### Steg 5: Skapa en andra generator för versionen med tomma staplar + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Att skapa en ny instans säkerställer att ändringar för versionen med tomma staplar inte påverkar den redan sparade bilden med fyllda staplar. + +### Steg 6: Inaktivera fyllda staplar samtidigt som X‑dimensionen behålls + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Varför?** +Att sätta `FilledBars = false` renderar streckkoden med endast konturen av varje stapel, vilket vissa poststandarder kräver för visuell verifiering. + +### Steg 7: Spara bilden med tomma staplar + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Nu har du två PNG‑filer – en med fyllda staplar och en med tomma staplar – redo för inkludering i PDF‑filer, HTML‑e‑post eller tryckta etiketter. + +## Fullständigt körbart program + +Nedan är den kompletta koden som du kan kopiera till `Program.cs`. Den kompileras och körs utan ändringar (förutsatt att Aspose.BarCode‑paketet är installerat). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Förväntad output + +Running the program prints two lines similar to: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Öppna mappen `Barcodes` så ser du de två PNG‑filerna. Båda bilderna kan öppnas i vilken bildvisare som helst eller bäddas in direkt i dokument. + +![how to save barcode example](barcode-example.png){: .align-center alt="exempel på hur man sparar streckkod"} + +## Vanliga variationer och kantfall + +| Scenario | Adjustment | +|----------|------------| +| **Olika bildformat** | Ändra `BarCodeImageFormat.Png` till `Jpeg`, `Gif` eller `Bmp` efter behov. | +| **Anpassad utskriftsstorlek** | Använd `filled.Parameters.Image.Width` och `Height` för att tvinga en specifik pixeldimension. | +| **Dynamisk data** | Ersätt den statiska `"123456"` med en variabel som innehåller ordernummer, spårnings‑ID osv. | +| **Icke‑existerande mapp** | `Directory.CreateDirectory` hanterar redan saknade kataloger; ingen extra kod behövs. | +| **Högupplöst utskrift** | Öka `XDimension.Pixels` till 6–8 för 600 dpi‑skrivare, men verifiera scanner‑kompatibilitet. | + +**Pro tip:** Om du behöver generera många streckkoder i en loop, återanvänd en enda `BarcodeGenerator`‑instans och ändra bara `CodeText`‑egenskapen innan varje `Save`. Detta minskar overhead för objektallokering. + +## Hur man genererar streckkod för andra standarder + +Samma mönster fungerar för andra `EncodeTypes` såsom `Code128`, `QR` eller `DataMatrix`. Byt helt enkelt ut `EncodeTypes.Planet` mot den önskade typen och justera eventuella typ‑specifika parametrar (t.ex. `QRCodeVersion`). + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ä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. + +- [Hur man sparar PNG med DataMatrix C40 med Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Hur man genererar DataMatrix‑streckkoder (ECC 200) med Aspose.BarCode för .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Hur man genererar streckkod – Code 39‑konfiguration med Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/thai/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..6138ea2b2 --- /dev/null +++ b/barcode/thai/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-08-03 +description: บทเรียนการสร้างบาร์โค้ดด้วย C# แสดงวิธีสร้างบาร์โค้ดแบบ Planet ด้วย Aspose.BarCode + ตั้งค่า X‑dimension และบันทึกเป็นไฟล์ PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: th +lastmod: 2026-08-03 +og_description: บทแนะนำการสร้างบาร์โค้ดด้วย C# จะพาคุณผ่านขั้นตอนการสร้างบาร์โค้ดแบบ + Planet, การปรับค่า X‑dimension, และการบันทึกเป็น PNG ด้วย Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: ตัวสร้างบาร์โค้ด C# – สร้างบาร์โค้ด Planet ทีละขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: ตัวสร้างบาร์โค้ด C# – ตัวอย่างการสร้างบาร์โค้ด Planet และ RM4SCC +url: /th/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ตัวสร้างบาร์โค้ด C# – สร้างตัวอย่าง Planet barcode และ RM4SCC + +หากคุณต้องการ **barcode generator C#** ที่สามารถสร้างสัญลักษณ์เฉพาะไปรษณีย์ได้ คู่มือนี้จะแสดงให้คุณเห็นอย่างชัดเจนว่า **สร้าง Planet barcode** อย่างไรด้วย Aspose.BarCode คุณจะได้เห็นวิธีตั้งค่า X‑dimension, สร้างบาร์โค้ด RM4SCC ที่ตรงกัน, และบันทึกทั้งสองเป็นไฟล์ PNG—ทั้งหมดในไม่กี่ขั้นตอนสั้น ๆ + +บทแนะนำนี้ครอบคลุมทุกอย่างที่คุณต้องการเพื่อรันโค้ดบน .NET 6 หรือรุ่นที่ใหม่กว่า อธิบายว่าทำไมแต่ละการตั้งค่าถึงสำคัญ และชี้ให้เห็นข้อผิดพลาดทั่วไป เช่น ความกว้างโมดูลที่ไม่ถูกต้องหรือการขาดสิทธิ์โฟลเดอร์ เมื่อเสร็จสิ้นคุณจะมีภาพบาร์โค้ดสองภาพพร้อมพิมพ์ที่สอดคล้องกับมาตรฐาน Planet และ RM4SCC + +## Prerequisites + +ก่อนเริ่มทำงาน โปรดตรวจสอบว่าคุณมี: + +* .NET 6 SDK (หรือเวอร์ชัน .NET ใด ๆ ที่รองรับโดย Aspose.BarCode) +* Visual Studio 2022 หรือ IDE C# ใด ๆ ที่คุณชอบ +* การอ้างอิง NuGet ไปยัง **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* สิทธิ์การเขียนไปยังโฟลเดอร์ที่คุณวางแผนจะเก็บไฟล์ PNG + +ไม่จำเป็นต้องใช้บริการภายนอกเพิ่มเติม; ไลบรารีจะจัดการการเข้ารหัสทั้งหมดในเครื่อง + +## Step 1: Initialise the barcode generator C# object + +ขั้นตอนแรกคือการสร้างอินสแตนซ์ของ `BarcodeGenerator` ตัวสร้างรับพารามิเตอร์สัญลักษณ์บาร์โค้ด (`EncodeTypes.Planet`) และข้อมูลที่ต้องเข้ารหัส + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Why this step?* +*ทำไมต้องทำขั้นตอนนี้?* +`BarcodeGenerator` เป็นจุดเริ่มต้นสำหรับบาร์โค้ดทุกประเภทที่คุณสร้าง การเลือก `EncodeTypes.Planet` จะบอกไลบรารีให้ปฏิบัติตามข้อกำหนด ISO/IEC 24723 ที่หลายบริการไปรษณีย์ใช้ + +## Step 2: Set the X‑dimension (module width) for the Planet barcode + +ตั้งค่า X‑dimension (ความกว้างโมดูล) สำหรับ Planet barcode + +X‑dimension กำหนดความกว้างของโมดูลบาร์โค้ดหนึ่งหน่วย (บาร์หรือช่องว่างที่เล็กที่สุด) ค่า **4 pixels** ทำงานได้ดีสำหรับเครื่องพิมพ์ฉลากส่วนใหญ่ + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Why this matters* +*ทำไมเรื่องนี้ถึงสำคัญ* +หากโมดูลแคบเกินไป บาร์โค้ดอาจอ่านไม่ออก; หากกว้างเกินไป ขนาดฉลากจะเพิ่มโดยไม่จำเป็น การปรับ `Pixels` ช่วยให้คุณปรับจูนบาร์โค้ดให้เหมาะกับความละเอียดของเครื่องพิมพ์ของคุณ + +## Step 3: Save the Planet barcode as a PNG image + +บันทึก Planet barcode เป็นภาพ PNG + +Aspose.BarCode คำนวณความสูงของบาร์โค้ดโดยอัตโนมัติตามสัญลักษณ์ที่เลือก ดังนั้นคุณเพียงแค่ระบุเส้นทางไฟล์และรูปแบบ + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Tip* +*เคล็ดลับ* +แทนที่ `YOUR_DIRECTORY` ด้วยเส้นทางแบบ absolute หรือ relative ที่มีอยู่บนเครื่องของคุณ หากโฟลเดอร์ไม่มีอยู่ `Save` จะโยน `DirectoryNotFoundException` + +**Expected output** – a PNG file that looks similar to the illustration below (the actual image is not displayed here, but you’ll see a classic Planet barcode with a numeric payload of `123456`). + +**ผลลัพธ์ที่คาดหวัง** – ไฟล์ PNG ที่มีลักษณะคล้ายภาพตัวอย่างด้านล่าง (ภาพจริงไม่ได้แสดงที่นี่ แต่คุณจะเห็น Planet barcode แบบคลาสสิกที่มีข้อมูลตัวเลข `123456`) + +## Step 4: Initialise a second generator for the RM4SCC barcode + +เริ่มต้นอ็อบเจ็กต์ generator ตัวที่สองสำหรับ RM4SCC barcode + +หลายระบบไปรษณีย์ต้องการสัญลักษณ์ Planet และ RM4SCC บนชิ้นส่วนจดหมายเดียวกัน สร้างอินสแตนซ์ `BarcodeGenerator` ใหม่สำหรับสัญลักษณ์ RM4SCC + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Why a separate instance?* +*ทำไมต้องใช้อินสแตนซ์แยก?* +แต่ละสัญลักษณ์มีชุดพารามิเตอร์ของตนเอง การใช้ generator เดียวกันอาจทำให้การตั้งค่าที่ไม่เหมาะสม (เช่น X‑dimension) ถูกนำไปใช้กับบาร์โค้ดที่สองโดยไม่ได้ตั้งใจ + +## Step 5: Configure the X‑dimension for the RM4SCC barcode + +กำหนดค่า X‑dimension สำหรับ RM4SCC barcode + +RM4SCC ยังคงเคารพการตั้งค่า X‑dimension ดังนั้นเราจึงใช้ความกว้างพิกเซลเดียวกันเพื่อความสอดคล้องด้านภาพ + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +*เคล็ดลับระดับมืออาชีพ* +หากต้องการบาร์โค้ดที่สูงขึ้น (เช่น สำหรับฉลากขนาดใหญ่) คุณสามารถตั้งค่า `Height.Pixels` ได้เช่นกัน การไม่ตั้งค่าให้ไลบรารีคำนวณความสูงที่เหมาะสมโดยอัตโนมัติ + +## Step 6: Save the RM4SCC barcode as a PNG image + +บันทึก RM4SCC barcode เป็นภาพ PNG + +สุดท้ายให้บันทึกบาร์โค้ด RM4SCC ลงดิสก์ + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +ตอนนี้คุณมีไฟล์ PNG สองไฟล์—`PostalPlanetBarHeightNone.png` และ `PostalRM4SCCBarHeightNone.png`—ที่คุณสามารถฝังในฉลากไปรษณีย์, พิมพ์บนซองจดหมาย, หรือส่งให้บริการพิมพ์ของบุคคลที่สามได้ + +## Optional: Adjusting height or using other image formats + +ปรับความสูงหรือใช้รูปแบบภาพอื่น ๆ (Optional) + +หากกระบวนการทำงานของคุณต้องการความสูงของบาร์โค้ดที่กำหนดหรือรูปแบบภาพอื่น (เช่น JPEG หรือ BMP) คุณสามารถแก้ไขพารามิเตอร์ก่อนเรียก `Save` ได้ + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Edge case** – When you set a custom height, make sure the value respects the minimum height required by the ISO standard; otherwise the barcode may fail validation. + +**กรณีขอบ** – เมื่อคุณตั้งค่าความสูงแบบกำหนดเอง ต้องตรวจสอบว่าค่าดังกล่าวสอดคล้องกับความสูงขั้นต่ำตามมาตรฐาน ISO มิฉะนั้นบาร์โค้ดอาจไม่ผ่านการตรวจสอบความถูกต้อง + +## Common pitfalls and how to avoid them + +| Pitfall | Why it happens | Fix | +|---------|----------------|-----| +| `DirectoryNotFoundException` | The target folder does not exist or is misspelled. | Create the folder first or use `Path.Combine` with `Environment.CurrentDirectory`. | +| Barcode unreadable on low‑resolution printers | X‑dimension too small for the printer’s DPI. | Increase `XDimension.Pixels` to 5 – 6 for 203 dpi printers, or test with a sample label. | +| Wrong symbology used | Passing `EncodeTypes.Code128` instead of `EncodeTypes.Planet`. | Double‑check the `EncodeTypes` enum value matches the required postal standard. | +| Null reference on `Parameters` | Using an older version of Aspose.BarCode where the API differs. | Upgrade to the latest NuGet package (v23.12 or later). | + +| ปัญหา | สาเหตุ | วิธีแก้ | +|-------|--------|---------| +| `DirectoryNotFoundException` | โฟลเดอร์เป้าหมายไม่มีอยู่หรือสะกดผิด | สร้างโฟลเดอร์ก่อนหรือใช้ `Path.Combine` ร่วมกับ `Environment.CurrentDirectory` | +| Barcode unreadable on low‑resolution printers | X‑dimension เล็กเกินไปสำหรับ DPI ของเครื่องพิมพ์ | เพิ่มค่า `XDimension.Pixels` เป็น 5 – 6 สำหรับเครื่องพิมพ์ 203 dpi หรือทดสอบด้วยฉลากตัวอย่าง | +| Wrong symbology used | ส่งค่า `EncodeTypes.Code128` แทน `EncodeTypes.Planet` | ตรวจสอบค่าใน enum `EncodeTypes` ให้ตรงกับมาตรฐานไปรษณีย์ที่ต้องการ | +| Null reference on `Parameters` | ใช้ Aspose.BarCode เวอร์ชันเก่าที่ API แตกต่าง | อัปเกรดเป็นแพคเกจ NuGet ล่าสุด (v23.12 หรือใหม่กว่า) | + +## Full runnable example + +ตัวอย่างโปรแกรมเต็มที่คุณสามารถคัดลอก, วาง, และรันได้ รวมถึง `using` statements, การจัดการข้อผิดพลาด, และคอมเมนต์อธิบายแต่ละบรรทัด + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +เมื่อรันโปรแกรมจะสร้างโฟลเดอร์ `Barcodes` ข้างไฟล์ executable และวางไฟล์ PNG สองไฟล์ไว้ภายใน เปิดด้วยโปรแกรมดูภาพใดก็ได้เพื่อยืนยันผลลัพธ์ + +## Conclusion + +คุณตอนนี้มีโซลูชัน **barcode generator C#** ที่สามารถ **สร้าง Planet barcode** ปรับ X‑dimension เพื่อการพิมพ์ที่เหมาะสม และสร้าง RM4SCC barcode ที่ตรงกัน—ทั้งหมดด้วยไม่กี่บรรทัดของโค้ด วิธีนี้ทำงานกับ .NET 6+ เพียงแค่ใช้แพคเกจ NuGet Aspose.BarCode และสามารถขยายไปยังสัญลักษณ์อื่น ๆ เช่น Code128, QR, หรือ DataMatrix โดยเปลี่ยนค่า `EncodeTypes` + +### What’s next? + +* ทดลองเปลี่ยนค่า `XDimension.Pixels` เพื่อให้ตรงกับ DPI ของเครื่องพิมพ์ของคุณ +* สร้างบาร์โค้ดในรูปแบบอื่น (PDF, SVG) โดยเปลี่ยนค่า enum `BarCodeImageFormat` +* รวมไฟล์ PNG สองไฟล์เป็นฉลากเดียวโดยใช้ไลบรารีกราฟิกอย่าง **SkiaSharp** +* สำรวจ API ของ Aspose.BarCode อย่างเต็มที่เพื่อใช้ฟีเจอร์ขั้นสูง เช่น การตรวจสอบ checksum หรือการใช้ฟอนต์แบบกำหนดเอง + +คุณสามารถปรับโค้ดสำหรับการประมวลผลแบบแบตช์หรือรวมเข้ากับบริการเว็บ ASP.NET Core ที่ส่งคืนภาพบาร์โค้ดตามคำขอได้เลย ขอให้สนุกกับการเขียนโค้ด! + +## What Should You Learn Next? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคในคู่มือนี้ แต่ละแหล่งข้อมูลมีโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานอื่น ๆ ในโครงการของคุณ + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/thai/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..f87b695b5 --- /dev/null +++ b/barcode/thai/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-08-03 +description: บทเรียนการสร้างบาร์โค้ดด้วย C# แสดงวิธีสร้างภาพบาร์โค้ดด้วย Aspose.BarCode + ตั้งค่าคอลัมน์และแถว และบันทึกไฟล์ PNG สำหรับ DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: th +lastmod: 2026-08-03 +og_description: บทแนะนำการสร้างบาร์โค้ดด้วย C# อธิบายวิธีสร้างภาพบาร์โค้ดโดยใช้ Aspose.BarCode, + ตั้งค่าคอลัมน์และแถวของ DataBar Expanded Stacked, และบันทึกเป็นไฟล์ PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: เครื่องสร้างบาร์โค้ด C# – คู่มือขั้นตอนต่อขั้นตอนในการสร้างภาพบาร์โค้ด +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: เครื่องสร้างบาร์โค้ด C# – สร้างภาพบาร์โค้ด +url: /th/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ตัวสร้างบาร์โค้ด C# – สร้างภาพบาร์โค้ด + +หากคุณต้องการตัวสร้างบาร์โค้ด C# ที่สามารถสร้างภาพบาร์โค้ดสำหรับ DataBar Expanded Stacked คู่มือนี้จะพาคุณผ่านกระบวนการทั้งหมด คุณจะได้เรียนรู้วิธีกำหนดค่าคอลัมน์และแถว, บันทึกผลลัพธ์เป็น PNG, และปรับโค้ดสำหรับสัญลักษณ์อื่น ๆ + +การสร้างภาพบาร์โค้ดโดยโปรแกรมช่วยลดขั้นตอนที่ทำด้วยมือและทำให้ได้ผลลัพธ์ที่สม่ำเสมอในใบแจ้งหนี้, ป้ายจัดส่ง, และระบบสินค้าคงคลัง คู่มือนี้ครอบคลุมทุกสิ่งที่คุณต้องการ ตั้งแต่การตั้งค่าโครงการจนถึงโค้ดต้นฉบับเต็ม เพื่อให้คุณสามารถรันตัวอย่างได้ทันที + +## ข้อกำหนดเบื้องต้น + +* .NET 6.0 หรือใหม่กว่า ที่ติดตั้งแล้ว +* IDE เช่น Visual Studio 2022 (หรือเครื่องมือแก้ไขใด ๆ ที่รองรับ C#) +* ไลเซนส์สำหรับ **Aspose.BarCode for .NET** – สามารถใช้รุ่นทดลองฟรีสำหรับการทดสอบ +* ความคุ้นเคยพื้นฐานกับไวยากรณ์ C# + +หากมีรายการใดขาดหาย ให้ติดตั้ง .NET SDK จาก dotnet.microsoft.com และรับแพ็กเกจ Aspose.BarCode NuGet ด้วย: + +```bash +dotnet add package Aspose.BarCode +``` + +## ขั้นตอนที่ 1: สร้างโครงการตัวสร้างบาร์โค้ด C# + +สร้างแอปพลิเคชันคอนโซลใหม่และเพิ่ม `using` directives ที่จำเป็น: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +คลาส `BarcodeGenerator` คือหัวใจของ API ตัวสร้างบาร์โค้ด C# มันรับประเภทสัญลักษณ์และข้อความที่ต้องเข้ารหัส + +## ขั้นตอนที่ 2: สร้างบาร์โค้ด DataBar Expanded Stacked และกำหนดคอลัมน์ + +ตัวอย่างแรกสร้างบาร์โค้ดที่มีสี่คอลัมน์ การปรับค่า `Columns` จะเปลี่ยนความหนาแน่นของสัญลักษณ์ DataBar Expanded Stacked + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**ทำไมเรื่องนี้ถึงสำคัญ:** จำนวนคอลัมน์มีผลต่อปริมาณข้อมูลที่สามารถเก็บในพื้นที่กะทัดรัด การตั้งค่าเป็น 4 จะทำให้บาร์โค้ดกว้างขึ้นแต่ยังคงอ่านได้โดยสแกนเนอร์ส่วนใหญ่ + +## ขั้นตอนที่ 3: สร้างบาร์โค้ดด้วยจำนวนแถวที่กำหนดเอง + +ตัวอย่างที่สองแสดงวิธีควบคุมการจัดวางแนวตั้งโดยตั้งค่า `Rows` การกำหนดค่าเป็นสามแถวเป็นประโยชน์เมื่อคุณต้องการบาร์โค้ดที่สูงขึ้นเพื่อใช้พื้นที่แนวนอนที่จำกัด + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**ทำไมเรื่องนี้ถึงสำคัญ:** การปรับแถวช่วยให้คุณใส่บาร์โค้ดลงในคอลัมน์แคบ ๆ ขณะยังคงความอ่านได้ ตัวสร้างบาร์โค้ด C# จะคำนวณขนาดโมดูลใหม่อัตโนมัติเพื่อให้สอดคล้องกับสเปค + +## ขั้นตอนที่ 4: ตัวอย่างเต็มที่สามารถรันได้ + +ด้านล่างเป็นโปรแกรมที่รวมขั้นตอนก่อนหน้าไว้ในไฟล์เดียว คัดลอกโค้ดไปยัง `Program.cs` แทนที่ `YOUR_DIRECTORY` ด้วยเส้นทางโฟลเดอร์ที่มีอยู่แล้ว แล้วรันแอปพลิเคชัน + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +เมื่อคุณรันโปรแกรม จะมีไฟล์ PNG สองไฟล์ปรากฏในโฟลเดอร์เป้าหมาย: + +* **DatabarCols4.png** – บาร์โค้ด DataBar Expanded Stacked ที่มีสี่คอลัมน์ +* **DatabarRows3.png** – ข้อมูลเดียวกันที่เข้ารหัสในสามแถว + +เปิดภาพด้วยโปรแกรมดูรูปใดก็ได้; ภาพจะแสดงบาร์โค้ดที่คมชัดและสแกนได้ พร้อมสำหรับการพิมพ์หรือฝังในไฟล์ PDF + +## วิธีสร้างภาพบาร์โค้ดด้วยขนาดกำหนดเอง + +หากคุณต้องการขนาดภาพเฉพาะ ให้ปรับคุณสมบัติ `ImageHeight` และ `ImageWidth` ก่อนเรียก `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +การเปลี่ยนขนาดไม่ส่งผลต่อข้อมูลที่เข้ารหัส; เพียงแค่ปรับสเกลการแสดงผล เทคนิคนี้มีประโยชน์เมื่อผสานบาร์โค้ดเข้ากับคอมโพเนนต์ UI ที่มีข้อจำกัดการจัดวางคงที่ + +## ปัญหาที่พบบ่อยและเคล็ดลับระดับมืออาชีพ + +* **ตัวคั่นเส้นทาง:** ใช้สตริงแบบ verbatim (`@"C:\Path\file.png"`) หรือ `Path.Combine` เพื่อหลีกเลี่ยงปัญหาอักขระ escape บน Windows +* **การบังคับใช้ไลเซนส์:** หากไม่มีไลเซนส์ที่ถูกต้อง ภาพที่สร้างจะมีลายน้ำ ใส่ไลเซนส์ของคุณตั้งแต่ต้นในแอปพลิเคชัน: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **ขีดจำกัดการเข้ารหัส:** DataBar Expanded Stacked รองรับได้สูงสุด 74 ตัวอักษรตัวเลข การเกินขีดจำกัดจะทำให้เกิดข้อยกเว้น ตรวจสอบความยาวอินพุตก่อนสร้างตัวสร้าง +* **ประสิทธิภาพ:** การใช้ `BarcodeGenerator` ตัวเดียวสำหรับการบันทึกหลายครั้งช่วยลดการจัดสรรหน่วยความจำ ให้เปลี่ยนคุณสมบัติ `Rows` หรือ `Columns` ระหว่างการบันทึกเท่านั้น หากข้อความที่เข้ารหัสยังคงเดิม + +## ขั้นตอนต่อไป + +ตอนนี้คุณสามารถสร้างภาพบาร์โค้ดด้วยตัวสร้างบาร์โค้ด C# แล้ว ลองสำรวจต่อไปนี้: + +* **สัญลักษณ์ต่าง ๆ** – ลอง `EncodeTypes.QR`, `EncodeTypes.Code128`, หรือ `EncodeTypes.Pdf417` +* **การปรับสี** – ตั้งค่า `Parameters.Barcode.ForeColor` และ `BackColor` ให้ตรงกับแบรนด์ของคุณ +* **การฝังใน PDF** – ผสาน PNG ที่สร้างกับ Aspose.PDF เพื่อสร้างเอกสารที่พิมพ์ได้ + +ส่วนขยายเหล่านี้จะช่วยให้คุณสร้างโซลูชันบาร์โค้ดครบวงจรสำหรับการจัดการสินค้าคงคลัง, โลจิสติกส์, หรือการค้าปลีก + +--- + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ 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/) +- [วิธีสร้างบาร์โค้ด DataMatrix (ECC 200) ด้วย Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/thai/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..c7f47fdcc --- /dev/null +++ b/barcode/thai/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-08-03 +description: ตัวอย่างการสร้างบาร์โค้ดด้วย C# แสดงวิธีตั้งค่าความกว้าง วิธีเปลี่ยนความสูง + และวิธีสร้างภาพบาร์โค้ด ปฏิบัติตามขั้นตอนทีละขั้นตอน +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: th +lastmod: 2026-08-03 +og_description: ตัวอย่างการสร้างบาร์โค้ดแสดงการตั้งค่าความกว้างของมิติ X, การปรับความสูงของบาร์, + และการสร้างภาพบาร์โค้ดด้วย C# ทำตามขั้นตอนเพื่อสร้างไฟล์ PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: ตัวอย่างการสร้างบาร์โค้ด – คู่มือความกว้างและความสูงใน C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: ตัวอย่างการสร้างบาร์โค้ดใน C# – ตั้งความกว้างและความสูง +url: /th/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ตัวอย่างการสร้างบาร์โค้ดใน C# – ตั้งค่าความกว้างและความสูง + +หากคุณต้องการ **ตัวอย่างการสร้างบาร์โค้ด** ใน C# คู่มือนี้จะแสดงวิธีตั้งค่าความกว้างของ X‑dimension, วิธีเปลี่ยนความสูงของบาร์, และวิธีสร้างไฟล์ภาพบาร์โค้ด คุณจะได้เห็นโปรแกรมที่ทำงานได้เต็มรูปแบบซึ่งสร้างไฟล์ PNG สองไฟล์ที่มีความสูงต่างกัน + +สถานการณ์ทั่วไปคือการสร้างป้ายสินค้าโดยขนาดบาร์โค้ดต้องตรงตามข้อกำหนดของเครื่องสแกน เมื่อจบบทเรียนนี้คุณจะสามารถปรับพารามิเตอร์ความกว้างและความสูงโดยโปรแกรมและบันทึกผลลัพธ์เป็นภาพ PNG + +## ข้อกำหนดเบื้องต้น + +* .NET 6 (หรือรุ่นใหม่กว่า) ที่ติดตั้งแล้ว – โค้ดนี้ตั้งเป้าหมายที่ .NET 6 SDK. +* ไลบรารีบาร์โค้ดที่รองรับ `EncodeTypes.DatabarOmniDirectional` ตัวอย่างใช้ **Aspose.BarCode for .NET** แต่ไลบรารีใดก็ได้ที่มีคุณสมบัติคล้ายกันก็ทำงานเช่นเดียวกัน +* IDE หรือโปรแกรมแก้ไข (Visual Studio, VS Code, Rider) เพื่อคอมไพล์และรันโปรแกรม +* สิทธิ์การเขียนไปยังไดเรกทอรีที่ไฟล์ PNG จะถูกบันทึก + +> **เคล็ดลับ:** สร้างโฟลเดอร์ชื่อ `Barcodes` ในโฟลเดอร์รากของโปรเจคและอ้างอิงด้วย `Path.Combine` เพื่อหลีกเลี่ยงการกำหนดพาธแบบเต็ม + +## ตัวอย่างการสร้างบาร์โค้ด: การเริ่มต้นและการกำหนดค่า + +ขั้นตอนแรกคือการสร้างอินสแตนซ์ `BarcodeGenerator` ด้วยสัญลักษณ์และสตริงข้อมูลที่ต้องการ + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +`enum` `EncodeTypes.DatabarOmniDirectional` เลือกสัญลักษณ์ Databar Omni‑directional และสตริงข้อมูลรูปแบบ GS1 `(01)12345678901231` แสดงค่าตัวอย่างของ GTIN‑14 การกำหนดค่า generator ครั้งเดียวทำให้คุณสามารถใช้วัตถุเดียวกันสำหรับหลายภาพได้ + +## วิธีตั้งค่าความกว้าง (X‑dimension) + +X‑dimension ควบคุมความกว้างของโมดูลของบาร์โค้ด การตั้งค่าเป็น 2 พิกเซลทำให้บาร์แคบแต่ละบาร์กว้าง 2 พิกเซล ซึ่งเป็นข้อกำหนดทั่วไปสำหรับการพิมพ์ความหนาแน่นสูง + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +เหตุผลที่สำคัญ: หากความกว้างเล็กเกินไป เครื่องสแกนอาจไม่แยกบาร์แต่ละบาร์ได้; หากกว้างเกินไป บาร์โค้ดอาจเกินพื้นที่ของป้าย ปรับค่าพิกเซลให้ตรงกับ DPI ของเครื่องพิมพ์และขนาดป้ายเป้าหมาย + +## วิธีเปลี่ยนความสูง + +ความสูงของบาร์กำหนดว่าบาร์จะสูงเท่าใด ตัวอย่างสร้างภาพสองภาพ: หนึ่งภาพที่ความสูง 30 พิกเซลและอีกภาพที่ความสูง 60 พิกเซล + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +คุณสมบัติ `BarHeight.Pixels` มีผลโดยตรงต่อความสูงของบาร์ที่แสดง การเปลี่ยนค่าระหว่างการบันทึกทำให้คุณสามารถสร้างหลายรูปแบบจากข้อมูลเดียวกันโดยไม่ต้องสร้าง generator ใหม่ + +### ผลลัพธ์ที่คาดหวัง + +การรันโปรแกรมจะสร้างไฟล์ PNG สองไฟล์ในโฟลเดอร์ `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – บาร์สูง 30 พิกเซล +* `DatabarBarHeight60Pixels.png` – บาร์สูง 60 พิกเซล + +ภาพทั้งสองมีความกว้างเท่ากัน (กำหนดโดย X‑dimension) และเข้ารหัสข้อมูล GTIN‑14 เดียวกัน + +![ไฟล์ PNG ของบาร์โค้ดสองไฟล์ที่มีความสูงต่างกันที่สร้างโดยโค้ด C#](barcode-example.png "ตัวอย่างการสร้างบาร์โค้ดแสดงความแตกต่างของความสูง") + +*ข้อความ alt ของภาพด้านบนมีคีย์เวิร์ดหลักสำหรับการเข้าถึงและ SEO* + +## วิธีสร้างภาพบาร์โค้ดใน C# + +เมธอด `Save` จัดการการแปลงข้อมูลบาร์โค้ดเป็นไฟล์ภาพ คุณสามารถเลือกฟอร์แมตอื่น (JPEG, BMP, SVG) โดยส่งค่า enum `BarCodeImageFormat` ที่แตกต่าง ตัวอย่างใช้ PNG เนื่องจากรักษาคุณภาพแบบไม่มีการสูญเสียและได้รับการสนับสนุนอย่างกว้างขวาง + +หากคุณต้องการฝังบาร์โค้ดโดยตรงลงใน PDF หรือหน้าเว็บ ให้ดึงภาพเป็น `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +วิธีนี้ช่วยขจัดความจำเป็นของไฟล์ชั่วคราวและเป็นประโยชน์สำหรับบริการที่ต้องการประมวลผลจำนวนมาก + +## การปรับเปลี่ยนทั่วไปและกรณีขอบ + +| สถานการณ์ | การปรับเปลี่ยน | +|-----------|----------------| +| **สัญลักษณ์ที่แตกต่าง** | แทนที่ `EncodeTypes.DatabarOmniDirectional` ด้วยค่า enum อื่น (เช่น `EncodeTypes.Code128`). | +| **ป้ายขนาดเล็กมาก** | ลด `XDimension.Pixels` ลงเป็น 1 พิกเซล แต่ตรวจสอบความสามารถในการอ่านของเครื่องสแกน | +| **การพิมพ์ความละเอียดสูง** | เพิ่มทั้ง X‑dimension และความสูงของบาร์อย่างสัดส่วน (เช่น ความกว้าง 4 พิกเซล, ความสูง 80 พิกเซล). | +| **ข้อมูลแบบไดนามิก** | ส่งสตริงข้อมูลในเวลารัน, อาจมาจากบันทึกในฐานข้อมูล. | +| **การสร้างเป็นชุด** | วนลูปผ่านคอลเลกชันของสตริงข้อมูล, ใช้ `BarcodeGenerator` อินสแตนซ์เดียวกันโดยอัปเดต `generator.Text`. | + +เมื่อคุณเจอข้อยกเว้นเช่น `ArgumentOutOfRangeException` ให้ตรวจสอบอีกครั้งว่าค่าพิกเซลเป็นจำนวนเต็มบวกและไดเรกทอรีปลายทางมีอยู่ + +## สรุปโค้ดต้นฉบับทั้งหมด + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +คัดลอกโค้ดไปยังโปรเจคคอนโซลใหม่, เรียกคืนแพคเกจ NuGet ของ Aspose.BarCode (`dotnet add package Aspose.BarCode`), และรัน `dotnet run`. คุณจะเห็นข้อความในคอนโซลยืนยันการบันทึกไฟล์ + +## สรุป + +**ตัวอย่างการสร้างบาร์โค้ด** นี้แสดงวิธีตั้งค่าความกว้าง, วิธีเปลี่ยนความสูง, และวิธีสร้างภาพบาร์โค้ดใน C# โดยการปรับ `XDimension.Pixels` และ `BarHeight.Pixels` คุณจะควบคุมขนาดการแสดงผลของบาร์โค้ด, และเมธอด `Save` จะเขียนผลลัพธ์เป็นไฟล์ PNG ทดลองใช้สัญลักษณ์ต่าง ๆ, ฟอร์แมตผลลัพธ์, และสตริงข้อมูลเพื่อให้ตรงกับความต้องการของแอปพลิเคชันของคุณ + +**Next steps** + +* สำรวจ **วิธีสร้างบาร์โค้ด** ในฟอร์แมตภาพอื่น (SVG, JPEG) สำหรับการใช้งานบนเว็บ. +* เรียนรู้ **สร้างภาพบาร์โค้ด c#** สำหรับ endpoint ของ ASP.NET Core ที่ส่ง PNG กลับไปยังเบราว์เซอร์โดยตรง. +* ผสานโค้ดนี้กับไลบรารีการสร้าง PDF เพื่อฝังบาร์โค้ดลงในใบแจ้งหนี้หรือป้ายจัดส่ง. + +คุณสามารถปรับตัวอย่างนี้, แบ่งปันผลลัพธ์ของคุณ, หรือถามคำถามในคอมเมนต์ได้ตามสบาย. ขอให้เขียนโค้ดอย่างสนุกสนาน! + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้ทางเลือกในโปรเจคของคุณ + +- [วิธีสร้างบาร์โค้ด - ประเภทบาร์โค้ดมิติเดียว](/barcode/english/net/one-dimensional-barcode-types/) +- [วิธีตั้งค่าขอบสำหรับการปรับแต่งบาร์โค้ด ITF-14](/barcode/english/net/itf-14-barcode-customization/) +- [วิธีสร้างบาร์โค้ด DataMatrix (ECC 200) ด้วย Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/thai/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..e61012342 --- /dev/null +++ b/barcode/thai/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-08-03 +description: สร้างไฟล์ PNG ของบาร์โค้ดด้วย C# และเรียนรู้วิธีการปรับอัตราส่วนของภาพ + DataBar ทำตามตัวอย่างเต็มรูปแบบนี้พร้อมโค้ดและเคล็ดลับ. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: th +lastmod: 2026-08-03 +og_description: สร้างบาร์โค้ด PNG ด้วย C# และดูวิธีเปลี่ยนอัตราส่วนของบาร์โค้ด DataBar + คู่มือนี้มาพร้อมโค้ดที่พร้อมใช้งานและเคล็ดลับเชิงปฏิบัติ +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: สร้างบาร์โค้ด PNG ด้วย C# – ตัวอย่างเต็มพร้อมการควบคุมอัตราส่วน +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: สร้างบาร์โค้ด PNG ด้วย C# – คู่มือแบบขั้นตอนโดยละเอียด +url: /th/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างไฟล์ PNG ของบาร์โค้ดใน C# – คู่มือขั้นตอนโดยละเอียด + +หากคุณต้องการ **สร้างไฟล์ PNG ของบาร์โค้ด** ด้วย C# คู่มือนี้จะแสดงวิธีทำอย่างละเอียด คุณจะได้สร้างบาร์โค้ด DataBar แบบ stacked omnidirectional, บันทึกเป็นไฟล์ PNG, และเรียนรู้ **วิธีเปลี่ยนอัตราส่วน** เพื่อให้เหมาะกับสภาพแวดล้อมการสแกนที่แตกต่างกัน + +คู่มือนี้ครอบคลุมทุกสิ่งที่คุณต้องการ: แพ็กเกจที่จำเป็น, โปรแกรมที่ทำงานได้เต็มรูปแบบ, และคำอธิบายว่าทำไมแต่ละการตั้งค่าถึงสำคัญ เมื่อเสร็จสิ้นคุณจะมีไฟล์ PNG สองไฟล์ — หนึ่งไฟล์ที่อัตราส่วน 15 และอีกไฟล์ที่อัตราส่วน 30 — พร้อมใช้สำหรับการทดสอบหรือการผลิต + +## ข้อกำหนดเบื้องต้น + +ก่อนเริ่มทำงาน โปรดตรวจสอบว่าคุณมี: + +- .NET 6.0 SDK หรือรุ่นใหม่กว่า +- Visual Studio 2022 (หรือ IDE สำหรับ C# ใดก็ได้) +- การอ้างอิง NuGet ไปยัง **Aspose.BarCode** (ไลบรารีที่ให้ `BarcodeGenerator`) +- สิทธิ์การเขียนในโฟลเดอร์ที่ไฟล์ PNG จะถูกบันทึก + +คุณสามารถเพิ่มแพ็กเกจ Aspose.BarCode ด้วยคำสั่งต่อไปนี้: + +```bash +dotnet add package Aspose.BarCode +``` + +## ขั้นตอนที่ 1: ตั้งค่าโปรเจกต์และนำเข้า namespace + +สร้างแอปพลิเคชันคอนโซลใหม่และนำเข้า namespace ที่จำเป็นสำหรับการสร้างบาร์โค้ดและการทำงานกับไฟล์ + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**ทำไมจึงสำคัญ:** การนำเข้า `Aspose.BarCode.Generation` ทำให้คุณเข้าถึง `BarcodeGenerator` ได้ การวางโค้ดไว้ภายใน `Main` ทำให้ตัวอย่างเป็นอิสระและง่ายต่อการรัน + +## ขั้นตอนที่ 2: สร้างตัวสร้างบาร์โค้ดสำหรับ DataBar stacked omnidirectional + +สร้างอินสแตนซ์ของ `BarcodeGenerator` ด้วยประเภท `EncodeTypes.DatabarStackedOmniDirectional` และสตริงข้อมูล GS1‑128 ตัวอย่าง + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**ทำไมจึงสำคัญ:** ประเภทการเข้ารหัสที่เลือกจะสร้าง DataBar ความหนาแน่นสูงที่สามารถอ่านได้โดยสแกนเนอร์สมัยใหม่ ส่วนสตริงข้อมูลเป็นรูปแบบ GS1 Application Identifier (01) ซึ่งเป็นมาตรฐานสำหรับตัวระบุสินค้า + +## ขั้นตอนที่ 3: กำหนด X‑dimension (ความกว้างโมดูล) เป็นพิกเซล + +ตั้งค่าความกว้างโมดูลเพื่อควบคุมขนาดโดยรวมของบาร์โค้ดโดยไม่กระทบต่อความอ่านได้ + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**ทำไมจึงสำคัญ:** X‑dimension ที่ 2 พิกเซลให้บาร์โค้ดที่ไม่เล็กเกินไปสำหรับสแกนเนอร์และไม่ใหญ่เกินไปสำหรับพื้นที่ป้ายทั่วไป + +## ขั้นตอนที่ 4: บันทึก PNG แรกด้วยอัตราส่วน 15 + +ปรับอัตราส่วนของ DataBar แล้วบันทึกภาพเป็นไฟล์ PNG + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**ทำไมจึงสำคัญ:** อัตราส่วนกำหนดความสัมพันธ์ระหว่างความสูงและความกว้างของ DataBar แบบ stacked อัตราส่วน 15 เป็นค่าเริ่มต้นที่นิยมใช้เพื่อสมดุลระหว่างการอ่านได้และความสูงของป้าย + +## ขั้นตอนที่ 5: เปลี่ยนอัตราส่วนเป็น 30 และบันทึก PNG ที่สอง + +แก้ไขอินสแตนซ์เดียวกันให้ใช้ค่าอัตราส่วนที่ใหญ่ขึ้น แล้วบันทึกภาพที่สอง + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**ทำไมจึงสำคัญ:** การเพิ่มอัตราส่วนทำให้บาร์โค้ดยืดสูงขึ้น ซึ่งอาจช่วยเพิ่มความน่าเชื่อถือในการสแกนบนอุปกรณ์ความละเอียดต่ำหรือเมื่อป้ายพิมพ์บนสื่อแคบ + +## ผลลัพธ์ที่คาดหวัง + +การรันโปรแกรมจะสร้างไฟล์ PNG สองไฟล์: + +| ไฟล์ | อัตราส่วน | มิติประมาณ (พิกเซล) | +|------------------------------------|-----------|----------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (กว้าง × สูง) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (กว้าง × สูง) | + +ทั้งสองภาพมีบาร์โค้ด DataBar ที่ชัดเจนและสามารถสแกนได้ ซึ่งเข้ารหัสตัวระบุ GS1 `(01)12345678901231` + +## คำถามที่พบบ่อยและกรณีขอบ + +### วิธีเปลี่ยนคุณสมบัติดูอื่น ๆ ? + +คุณสามารถปรับสีพื้นหน้า, สีพื้นหลัง, หรือเพิ่มข้อความที่อ่านได้โดยมนุษย์ผ่านอ็อบเจกต์ `generator.Parameters.Barcode` ตัวอย่างเช่น: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### ถ้าต้องการรูปแบบภาพอื่น ? + +เปลี่ยน `BarCodeImageFormat.Png` เป็น `Jpeg`, `Bmp` หรือ `Gif` ตามต้องการ PNG ยังคงเป็นตัวเลือกที่ดีที่สุดสำหรับภาพบาร์โค้ดแบบไม่มีการสูญเสียคุณภาพ + +### อัตราส่วนมีผลต่อความเร็วในการสแกนหรือไม่ ? + +อัตราส่วนที่สูงทำให้บาร์โค้ดสูงขึ้น ซึ่งอาจช่วยเพิ่มความน่าเชื่อถือในการสแกนบนอุปกรณ์ที่มีปัญหาในการอ่านสัญลักษณ์ stacked สั้น ๆ อย่างไรก็ตาม บาร์โค้ดที่สูงเกินไปอาจไม่พอดีกับป้ายขนาดเล็ก จึงควรทดสอบกับฮาร์ดแวร์เป้าหมายของคุณ + +### สามารถสร้างบาร์โค้ดหลายรายการในลูปได้หรือไม่ ? + +ทำได้ โดยสร้างอินสแตนซ์ `BarcodeGenerator` ใหม่สำหรับแต่ละสตริงข้อมูล หรือใช้อินสแตนซ์เดียวกันโดยอัปเดต `CodeText` และ `DataBar.AspectRatio` วิธีนี้ช่วยลดภาระการจัดสรรอ็อบเจกต์ + +## เคล็ดลับระดับมืออาชีพ + +- **ใช้ตัวสร้างซ้ำ**: การเปลี่ยนเฉพาะ `CodeText` หรือ `AspectRatio` แทนการสร้างอ็อบเจกต์ใหม่จะช่วยเร่งการประมวลผลเป็นชุด +- **ตรวจสอบผลลัพธ์**: ใช้สแกนเนอร์พกพาหรือแอปมือถือเพื่อยืนยันว่า PNG ที่สร้างอ่านได้ถูกต้องก่อนนำไปใช้จริง +- **ตั้งชื่อไฟล์**: ใส่อัตราส่วนในชื่อไฟล์ (ตามที่แสดง) เพื่อให้ติดตามเวอร์ชันต่าง ๆ ระหว่างการทดสอบได้ง่าย + +## สรุป + +คุณได้เรียนรู้วิธี **สร้างไฟล์ PNG ของบาร์โค้ด** ด้วย C# และวิธี **เปลี่ยนอัตราส่วน** สำหรับสัญลักษณ์ DataBar stacked omnidirectional อย่างแม่นยำ ตัวอย่างเต็มรูปแบบแสดงการเริ่มต้น, การตั้งค่า X‑dimension, การจัดการอัตราส่วน, และการบันทึกภาพ — ทั้งหมดในโปรแกรมเดียวที่สามารถรันได้ + +จากนี้คุณสามารถสำรวจประเภทบาร์โค้ดเพิ่มเติม, ทดลองใช้สีต่าง ๆ, หรือผสานตัวสร้างเข้ากับระบบรายงานหรือระบบสินค้าคงคลังของคุณได้เลย ขอให้สนุกกับการเขียนโค้ด! + +## สิ่งที่คุณควรเรียนต่อไป + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคในคู่มือนี้ แต่ละแหล่งข้อมูลมีโค้ดตัวอย่างทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้แบบต่าง ๆ ในโครงการของคุณ + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/thai/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..9f7c0809f --- /dev/null +++ b/barcode/thai/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-08-03 +description: สร้างไฟล์ PNG ของบาร์โค้ดอย่างรวดเร็วด้วยคู่มือนี้ เรียนรู้วิธีสร้างภาพบาร์โค้ดโดยใช้ + Aspose.BarCode และสร้างบาร์โค้ดแบบ Planet +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: th +lastmod: 2026-08-03 +og_description: สร้างบาร์โค้ด PNG ได้ทันที บทแนะนำนี้แสดงวิธีการสร้างภาพบาร์โค้ดและสร้างบาร์โค้ดแบบ + planet ด้วย Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: สร้างบาร์โค้ด PNG ด้วย Python – คู่มือการเขียนโปรแกรมครบถ้วน +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: สร้างบาร์โค้ด PNG ด้วย Python – คู่มือแบบทีละขั้นตอน +url: /th/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างไฟล์ PNG ของบาร์โค้ดใน Python – คู่มือขั้นตอนโดยละเอียด + +หากคุณต้องการ **สร้างไฟล์ PNG ของบาร์โค้ด** จากแอปพลิเคชัน Python ของคุณ บทเรียนนี้จะแสดงให้คุณเห็นอย่างชัดเจน เราจะอธิบาย **วิธีสร้างภาพบาร์โค้ด** ด้วย Aspose.BarCode และโดยเฉพาะ **การสร้างบาร์โค้ด Planet** พร้อมขนาดที่กำหนดเอง + +คุณจะได้เรียนรู้วิธีติดตั้งไลบรารี การกำหนดสัญลักษณ์ Planet ปรับพารามิเตอร์ขนาด และบันทึกผลลัพธ์เป็น PNG คุณภาพสูง คู่มือนี้สมมติว่าคุณมีพื้นฐาน Python เบื้องต้นและใช้ Python 3 เวอร์ชันล่าสุด (3.8 ขึ้นไป) ไม่จำเป็นต้องมีประสบการณ์กับมาตรฐานบาร์โค้ดมาก่อน + +--- + +## วิธีสร้างไฟล์ PNG ของบาร์โค้ดด้วย Aspose.BarCode + +ส่วนนี้ประกอบด้วยขั้นตอนหลักที่จำเป็นสำหรับ **การสร้างไฟล์ PNG ของบาร์โค้ด** แต่ละขั้นตอนจะมีโค้ดสแนปช็อต คำอธิบายว่าทำไมจึงสำคัญ และเคล็ดลับที่คุณสามารถนำไปใช้ได้ทันที + +### 1. ติดตั้งแพคเกจ Aspose.BarCode + +Aspose มีแพคเกจ Python แบบ pure‑Python ที่ห่อหุ้มเอนจิน .NET core ของมัน ติดตั้งด้วย `pip`: + +```bash +pip install aspose-barcode +``` + +*ทำไมขั้นตอนนี้สำคัญ:* แพคเกจนี้ให้คลาส `BarcodeGenerator` ที่ใช้ตลอดตัวอย่าง การติดตั้งแบบทั่วโลกทำให้ตัวแปลภาษา (interpreter) สามารถหา assembly ได้ในเวลารันไทม์ + +### 2. นำเข้าคลาสที่ต้องการ + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*เคล็ดลับ:* นำเข้าเฉพาะสัญลักษณ์ที่คุณต้องการ จะช่วยให้เนมสเปซสะอาดและเร่งการโหลดโมดูล + +### 3. สร้างตัวสร้างบาร์โค้ดสำหรับสัญลักษณ์ Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*ทำไมขั้นตอนนี้สำคัญ:* `EncodeTypes.Planet` บอกเอนจินให้ใช้มาตรฐานบาร์โค้ด Planet ส่วนอาร์กิวเมนต์ที่สองเป็นข้อมูลที่ต้องเข้ารหัส การเปลี่ยนสัญลักษณ์ (เช่น `EncodeTypes.Code128`) จะทำให้ได้รูปแบบภาพที่แตกต่างอย่างสิ้นเชิง + +### 4. ตั้งค่า X dimension (ความกว้างโมดูล) เป็นพิกเซล + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*คำอธิบาย:* X dimension ควบคุมความกว้างของบาร์แคบ ค่า 4 พิกเซลให้บาร์โค้ดที่มีความหนาแน่นปานกลางและยังคงสแกนได้บนอุปกรณ์ส่วนใหญ่ + +### 5. กำหนดความสูงของบาร์แบบกำหนดเองเป็นพิกเซล + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*ทำไมคุณอาจต้องปรับ:* เครื่องพิมพ์รีเทลบางรุ่นต้องการบาร์ที่สูงขึ้นเพื่อการสแกนที่เชื่อถือได้ ความสูงเริ่มต้นมักเป็น 50 px; การเพิ่มเป็น 100 px จะช่วยอ่านได้ง่ายขึ้นโดยไม่ทำให้ไฟล์ใหญ่ขึ้นอย่างมาก + +### 6. บันทึกบาร์โค้ดที่สร้างเป็นไฟล์ PNG + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*ผลลัพธ์:* จะได้ไฟล์ PNG ชื่อ **PlanetBarHeight100.png** ปรากฏในโฟลเดอร์ `output` PNG เป็นรูปแบบ loss‑less ทำให้เหมาะสำหรับการพิมพ์และการฝังในหน้าเว็บ + +### 7. ตรวจสอบผลลัพธ์ (ไม่บังคับ) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*เคล็ดลับ:* การดูภาพช่วยยืนยันว่าขนาดตรงกับพารามิเตอร์ที่ตั้งไว้ หากบาร์โค้ดดูบิดเบี้ยว ให้ตรวจสอบการตั้งค่า X dimension หรือความสูงของบาร์อีกครั้ง + +--- + +## วิธีสร้างภาพบาร์โค้ดในรูปแบบ PNG (การตั้งค่าอื่น) + +หากคุณต้องการรูปแบบไฟล์ภาพอื่นหรืออยากฝังบาร์โค้ดลงใน PDF ต่อไป คุณสามารถเปลี่ยนค่า enum `BarCodeImageFormat` ได้: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*ทำไมขั้นตอนนี้สำคัญ:* PNG รักษาพิกเซลทุกพิกเซลซึ่งจำเป็นสำหรับบาร์โค้ดที่มีคอนทราสต์สูง JPEG มีการบีบอัดที่อาจทำให้เกิดศูนย์รบกวนในการสแกน ส่วน BMP มีความเข้ากันได้กับเครื่องมือเก่า + +--- + +## สร้างบาร์โค้ด Planet ด้วยสีที่กำหนดเอง (ขั้นสูง) + +นอกจากขนาดแล้ว คุณยังสามารถปรับสีพื้นหน้าและพื้นหลังได้: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*เคล็ดลับปฏิบัติ:* คู่สีคอนทราสต์สูง (สีเข้มบนพื้นสีอ่อน) จะเพิ่มความเชื่อถือได้ของสแกนเนอร์ หลีกเลี่ยงการใช้สีที่คล้ายกันสำหรับพื้นหน้าและพื้นหลัง + +--- + +## ข้อผิดพลาดทั่วไปและวิธีหลีกเลี่ยง + +| อาการ | สาเหตุ | วิธีแก้ | +|---------|-------|-----| +| บาร์โค้ดสแกนไม่สำเร็จ | X dimension เล็กเกินไป (≤ 2 px) | เพิ่ม `x_dimension.pixels` อย่างน้อยเป็น 3 px | +| ภาพดูเบลอ | PNG บันทึกที่ DPI ต่ำ | ใช้ `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` เพื่อระบุ 300 DPI (หากรองรับ) | +| เกิดข้อยกเว้น `ImportError` | ยังไม่ได้ติดตั้ง Aspose.BarCode | รัน `pip install aspose-barcode` ในสภาพแวดล้อมเดียวกับสคริปต์ | +| สัญลักษณ์ผิด | ใช้ `EncodeTypes.Code128` แทน `EncodeTypes.Planet` | แทนที่ด้วย `EncodeTypes.Planet` เมื่อสร้างตัวสร้าง | + +--- + +## สรุปโซลูชันทั้งหมด + +ด้านล่างเป็นสคริปต์เต็มที่สามารถรันได้ซึ่ง **สร้างไฟล์ PNG ของบาร์โค้ด** ตั้งแต่ต้นจนจบ: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +การรันสคริปต์นี้จะได้ **บาร์โค้ด Planet PNG** ที่คมชัด ซึ่งคุณสามารถฝังใน HTML แนบในอีเมล หรือพิมพ์บนป้ายสินค้าได้ + +--- + +## ขั้นตอนต่อไปและหัวข้อที่เกี่ยวข้อง + +* **รวมกับ Flask หรือ Django** – ให้บริการ PNG ที่สร้างขึ้นโดยตรงจาก endpoint ของเว็บ +* **การสร้างเป็นชุด** – วนลูปรายการรหัสสินค้าเพื่อสร้างโฟลเดอร์ไฟล์ PNG ของบาร์โค้ดหลายไฟล์ +* **รวมกับการสร้าง PDF** – ใช้ `aspose-pdf` เพื่อนำ PNG ไปใส่ในใบแจ้งหนี้หรือป้ายจัดส่ง +* **สำรวจสัญลักษณ์อื่น** – แทนที่ `EncodeTypes.Planet` ด้วย `EncodeTypes.QR`, `EncodeTypes.DataMatrix`, หรือ `EncodeTypes.Code128` เพื่อรองรับความต้องการทางธุรกิจที่ต่างกัน + +ด้วยการเข้าใจขั้นตอนข้างต้น คุณจะรู้ **วิธีสร้างภาพบาร์โค้ด** อย่างเป็นโปรแกรมและสามารถขยายรูปแบบไปยังมาตรฐานบาร์โค้ดใด ๆ ที่ Aspose.BarCode รองรับ + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/thai/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..4f24ca45a --- /dev/null +++ b/barcode/thai/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-08-03 +description: สร้างภาพบาร์โค้ดไปรษณีย์ใน C# อย่างรวดเร็ว เรียนรู้วิธีสร้างบาร์โค้ดไปรษณีย์ + ตั้งค่าขนาดบาร์โค้ด และสร้างบาร์โค้ด Planet +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: th +lastmod: 2026-08-03 +og_description: สร้างภาพบาร์โค้ดไปรษณีย์ใน C# ด้วยบทเรียนฉบับสมบูรณ์นี้; เรียนรู้วิธีตั้งค่าขนาดบาร์โค้ด, + สร้างบาร์โค้ด Planet, และผลิตบาร์โค้ด RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: สร้างภาพบาร์โค้ดไปรษณีย์ใน C# – คู่มือการเขียนโปรแกรมเต็มรูปแบบ +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: สร้างภาพบาร์โค้ดไปรษณีย์ใน C# – คู่มือแบบขั้นตอนต่อขั้นตอน +url: /th/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างภาพบาร์โค้ดไปรษณีย์ใน C# – คู่มือขั้นตอนต่อขั้นตอน + +หากคุณต้องการ **สร้างภาพบาร์โค้ดไปรษณีย์** ใน C# คู่มือนี้จะแสดงให้คุณเห็นอย่างละเอียด เราจะครอบคลุม **วิธีสร้างบาร์โค้ดไปรษณีย์**, **วิธีตั้งค่าขนาดบาร์โค้ด**, และ **วิธีสร้างบาร์โค้ด Planet** สำหรับมาตรฐานไปรษณีย์ทั่วไป + +คุณจะได้ไฟล์ PNG สองไฟล์พร้อมใช้งาน—หนึ่งบาร์โค้ด Planet และหนึ่งบาร์โค้ด RM4SCC—แต่ละไฟล์สูง 100 px ไม่ต้องใช้เครื่องมือเพิ่มเติมใด ๆ นอกจากไลบรารี Aspose.BarCode for .NET + +## ความต้องการเบื้องต้น + +* .NET 6 SDK หรือใหม่กว่า (โค้ดนี้ยังทำงานกับ .NET Framework 4.7+ ด้วย) +* Visual Studio 2022 หรือ IDE สำหรับ C# ใดก็ได้ +* แพ็กเกจ NuGet **Aspose.BarCode** (ไลบรารีที่ให้ `BarcodeGenerator`) + +## ขั้นตอนที่ 1: ติดตั้งไลบรารีบาร์โค้ด + +เปิดเทอร์มินัลในโฟลเดอร์โปรเจกต์ของคุณและรัน: + +```bash +dotnet add package Aspose.BarCode +``` + +แพ็กเกจนี้จะเพิ่มเนมสเปซ `Aspose.BarCode` ซึ่งประกอบด้วย `BarcodeGenerator` และ enumeration `EncodeTypes` ที่จำเป็นสำหรับบาร์โค้ดไปรษณีย์ + +## ขั้นตอนที่ 2: กำหนดโฟลเดอร์ผลลัพธ์ + +การสร้างเส้นทางผลลัพธ์ที่เชื่อถือได้ช่วยป้องกันข้อผิดพลาดระหว่างรันเมื่อโฟลเดอร์ไม่มีอยู่ + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*ทำไมเรื่องนี้ถึงสำคัญ*: `Directory.CreateDirectory` มีคุณสมบัติเป็น idempotent—จะสร้างโฟลเดอร์เฉพาะเมื่อยังไม่มีอยู่เท่านั้น ช่วยหลีกเลี่ยงข้อยกเว้นในการรันครั้งต่อไป + +## ขั้นตอนที่ 3: กำหนดขนาดบาร์โค้ดทั่วไป + +การตั้งค่า X‑dimension (ความกว้างของบาร์เดียว) และความสูงรวมของบาร์ช่วยให้คุณควบคุมขนาดภาพที่สร้างขึ้นได้ + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**วิธีตั้งค่าขนาดบาร์โค้ด**: คุณสมบัติ `Parameters.Barcode.XDimension.Pixels` กำหนดความกว้างของบาร์แคบ, ส่วน `Parameters.Barcode.BarHeight.Pixels` กำหนดความสูงเต็ม ปรับค่าต่าง ๆ เหล่านี้ให้ตรงกับสเปคของบริการไปรษณีย์ของคุณ + +## ขั้นตอนที่ 4: สร้างบาร์โค้ด Planet + +Planet เป็นบาร์โค้ดไปรษณีย์ที่ใช้กันอย่างแพร่หลายในสหราชอาณาจักร โค้ดต่อไปนี้จะสร้างบาร์โค้ด Planet สูง 100 px และบันทึกเป็น PNG + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**ทำไมวิธีนี้ถึงได้ผล**: `EncodeTypes.Planet` บอกให้ตัวสร้างใช้สัญลักษณ์ Planet. เมธอด `Save` จะเขียนไฟล์ PNG ไปยังพาธที่ระบุ, รักษาขนาดที่เราตั้งไว้ก่อนหน้านี้ + +## ขั้นตอนที่ 5: สร้างบาร์โค้ด RM4SCC + +RM4SCC เป็นมาตรฐานบาร์โค้ดไปรษณีย์ของดัตช์ โค้ดด้านล่างเป็นการทำซ้ำตัวอย่าง Planet, แสดง **วิธีสร้างบาร์โค้ดไปรษณีย์** ประเภทอื่นด้วยขนาดเดียวกัน + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +ไฟล์ PNG ทั้งสองไฟล์ตอนนี้อยู่ในโฟลเดอร์ `Barcodes`. การเปิดไฟล์เหล่านี้จะแสดงบาร์โค้ดที่คมชัด สูง 100 px พร้อมใช้สำหรับพิมพ์หรือฝังในเอกสาร + +## โค้ดต้นฉบับเต็ม + +ด้านล่างเป็นโปรแกรมที่ทำงานได้เต็มรูปแบบซึ่ง **สร้างไฟล์ภาพบาร์โค้ดไปรษณีย์** สำหรับมาตรฐาน Planet และ RM4SCC + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +การรันโปรแกรมจะแสดงพาธไฟล์และสร้างไฟล์ PNG สองไฟล์: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +แต่ละภาพมีความสูง 100 px, มีความกว้างบาร์แคบ 4 pixel, ตรงกับขนาดที่เราตั้งค่า + +## เคล็ดลับปฏิบัติและข้อผิดพลาดทั่วไป + +* **Folder permissions** – หากโปรแกรมทำงานภายใต้บัญชีที่มีสิทธิ์จำกัด, ให้ตรวจสอบว่าโฟลเดอร์เป้าหมายสามารถเขียนได้ +* **Different dimensions** – เพื่อสร้างบาร์โค้ดที่สูงขึ้น, เพิ่มค่า `barHeightPixels`. หากต้องการความละเอียดสูงกว่า, ลดค่า `xDimensionPixels`, แต่ควรให้ค่า ≥ 2 เพื่อหลีกเลี่ยงข้อบกพร่องการเรนเดอร์ +* **Other postal symbologies** – Aspose.BarCode ยังรองรับ `EncodeTypes.Postnet` และ `EncodeTypes.AustralianPost`. เปลี่ยนค่า `EncodeTypes` และใช้ตรรกะขนาดเดียวกัน +* **Image format** – ใช้ `BarCodeImageFormat.Jpeg` เพื่อให้ไฟล์มีขนาดเล็กลงเมื่อไม่จำเป็นต้องรักษาคุณภาพ lossless + +## สรุป + +ตอนนี้คุณรู้วิธี **สร้างไฟล์ภาพบาร์โค้ดไปรษณีย์** ใน C# ด้วยการกำหนดขนาด, เลือกสัญลักษณ์ที่เหมาะสม, และบันทึกผลลัพธ์เป็น PNG แล้ว คู่มือได้ครอบคลุม **วิธีสร้างบาร์โค้ดไปรษณีย์**, แสดง **การสร้างบาร์โค้ด Planet**, และอธิบาย **วิธีตั้งค่าขนาดบาร์โค้ด** เพื่อให้ได้ผลลัพธ์ที่สม่ำเสมอ + +ต่อไป, ลองสำรวจ **การปรับแต่งสีของบาร์โค้ด**, การเพิ่ม **ข้อความที่มนุษย์อ่านได้**, หรือการรวมภาพเหล่านี้เข้าในใบแจ้งหนี้ PDF. รูปแบบเดียวกันนี้ใช้ได้กับบาร์โค้ดประเภทอื่นใด ๆ ที่ Aspose.BarCode รองรับ, ทำให้คุณสามารถขยายโซลูชันนี้เป็นกระบวนการอัตโนมัติไปรษณีย์เต็มรูปแบบ + +## สิ่งที่คุณควรเรียนต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนต่อขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการดำเนินการทางเลือกในโครงการของคุณ + +- [วิธีสร้างบาร์โค้ด - ประเภทบาร์โค้ดมิติเดียว](/barcode/english/net/one-dimensional-barcode-types/) +- [วิธีสร้างบาร์โค้ด Aztec ด้วยอัตราส่วนภาพกำหนดเองโดยใช้ Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [วิธีสร้างบาร์โค้ด java – บาร์โค้ด Australia Post ด้วย Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/thai/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..6b4788770 --- /dev/null +++ b/barcode/thai/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-08-03 +description: วิธีบันทึกบาร์โค้ดใน C# ด้วยตัวอย่างเครื่องสร้างบาร์โค้ดแบบขั้นตอนต่อขั้นตอน + เรียนรู้การสร้างบาร์โค้ด Planet ตั้งค่าขนาด และส่งออกเป็นภาพ PNG +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: th +lastmod: 2026-08-03 +og_description: วิธีบันทึกบาร์โค้ดใน C# ด้วยตัวอย่างเครื่องสร้างบาร์โค้ด บทเรียนนี้แสดงวิธีสร้างบาร์โค้ดแบบ + Planet ตั้งค่า X‑dimension และส่งออกไฟล์ PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: วิธีบันทึกบาร์โค้ดใน C# – คู่มือแบบทีละขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: วิธีบันทึกบาร์โค้ดใน C# – คู่มือสร้างบาร์โค้ดครบถ้วน +url: /th/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีบันทึกบาร์โค้ดใน C# – คู่มือสร้างบาร์โค้ดอย่างครบถ้วน + +การบันทึกภาพบาร์โค้ดใน C# เป็นความต้องการทั่วไปเมื่อคุณต้องฝังบาร์โค้ดไปรษณีย์ลงในใบแจ้งหนี้, ป้ายจัดส่ง, หรือแท็กสินค้าคงคลัง คู่มือนี้จะพาคุณผ่านกระบวนการทำงานของ **c# barcode generator** อย่างเป็นขั้นตอน ตั้งแต่การสร้างบาร์โค้ด Planet ไปจนถึงการส่งออกไฟล์ PNG ทั้งแบบบาร์เต็มและบาร์ว่าง + +คุณจะได้เรียนรู้วิธีตั้งความกว้างของบาร์, สลับการแสดงบาร์เต็ม, และจัดการโฟลเดอร์ผลลัพธ์อย่างมั่นคง เมื่อจบบทเรียนคุณจะมี **barcode generator example** ที่ทำงานเต็มรูปแบบซึ่งคุณสามารถคัดลอกไปใช้ในโปรเจกต์ .NET ใดก็ได้ + +## สิ่งที่คุณต้องมี + +- .NET 6.0 SDK หรือเวอร์ชันใหม่กว่า (ตัวอย่างทำงานกับ .NET Core และ .NET Framework) +- Visual Studio 2022 หรือ IDE ที่รองรับ C# ใดก็ได้ +- แพคเกจ NuGet **Aspose.BarCode** (หรือไลบรารีอื่นที่สนับสนุน `EncodeTypes.Planet`). ติดตั้งด้วย: + +```bash +dotnet add package Aspose.BarCode +``` + +ไลบรารีนี้ให้คลาส `BarcodeGenerator` ที่ใช้ตลอดบทเรียนนี้ + +## การตั้งค่าสภาพแวดล้อมการพัฒนา + +สร้างโปรเจกต์คอนโซลใหม่และเพิ่มเนมสเปซที่จำเป็น: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +เนมสเปซ `System.IO` ให้เราใช้ `Directory.CreateDirectory` ซึ่งทำให้แน่ใจว่าโฟลเดอร์ผลลัพธ์มีอยู่ก่อนที่เราจะพยายามเขียนไฟล์ + +## วิธีบันทึกภาพบาร์โค้ดด้วย C# barcode generator + +หัวใจของวิธีแก้คือชุดขั้นตอนเล็ก ๆ ที่กำหนดค่า **Planet barcode** แล้วบันทึกภาพลงดิสก์ ส่วนต่อไปนี้จะแบ่งกระบวนการเป็นชิ้นย่อยที่จัดการได้ + +### ขั้นตอนที่ 1: กำหนดโฟลเดอร์ผลลัพธ์ + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**ทำไม?** +การกำหนดเส้นทางแบบคงที่อาจทำให้เกิด `DirectoryNotFoundException` บนเครื่องที่ไม่มีโฟลเดอร์นั้น `CreateDirectory` มีคุณสมบัติเป็น idempotent — จะสร้างโฟลเดอร์เฉพาะเมื่อไม่มีอยู่ ทำให้โค้ดปลอดภัยเมื่อต้องรันหลายครั้ง + +### ขั้นตอนที่ 2: สร้าง Planet barcode generator (บาร์เต็ม) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**ทำไม?** +`EncodeTypes.Planet` บอกไลบรารีให้สร้างบาร์โค้ดไปรษณีย์แบบ Planet ซึ่งใช้กันอย่างกว้างขวางโดยบริการไปรษณีย์ สตริง `"123456"` เป็นข้อมูลตัวอย่าง; สามารถเปลี่ยนเป็นข้อมูลตัวเลขใด ๆ ที่ระบบธุรกิจของคุณต้องการได้ + +### ขั้นตอนที่ 3: กำหนดความกว้างของบาร์ (X‑dimension) และคงบาร์เต็มเป็นค่าเริ่มต้น + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**ทำไม?** +X‑dimension ควบคุมความกว้างจริงของแต่ละบาร์ ค่า `4` พิกเซลทำให้บาร์โค้ดอ่านได้บนเครื่องพิมพ์มาตรฐาน 300 dpi การปล่อย `FilledBars` เป็น `true` (ค่าเริ่มต้น) จะให้ลักษณะบาร์เต็มแบบคลาสสิก + +### ขั้นตอนที่ 4: บันทึกภาพบาร์โค้ดบาร์เต็ม + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**ทำไม?** +การบันทึกเป็น PNG จะรักษาคุณภาพภาพแบบ lossless ซึ่งสำคัญต่อความแม่นยำของการสแกน เมธอด `Save` จะสร้างไฟล์ภาพโดยอัตโนมัติ; คุณเพียงแค่ระบุเส้นทางเต็มและรูปแบบที่ต้องการ + +### ขั้นตอนที่ 5: สร้าง generator ตัวที่สองสำหรับเวอร์ชันบาร์ว่าง + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +การสร้างอินสแตนซ์ใหม่ทำให้การเปลี่ยนแปลงสำหรับเวอร์ชันบาร์ว่างไม่กระทบต่อภาพบาร์เต็มที่บันทึกไว้แล้ว + +### ขั้นตอนที่ 6: ปิดการแสดงบาร์เต็มขณะคง X‑dimension เดิม + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**ทำไม?** +การตั้งค่า `FilledBars = false` จะทำให้บาร์โค้ดแสดงเพียงโครงร่างของแต่ละบาร์ ซึ่งบางมาตรฐานไปรษณีย์ต้องการเพื่อการตรวจสอบด้วยสายตา + +### ขั้นตอนที่ 7: บันทึกภาพบาร์โค้ดบาร์ว่าง + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +ตอนนี้คุณมีไฟล์ PNG สองไฟล์ — หนึ่งไฟล์บาร์เต็มและอีกไฟล์บาร์ว่าง — พร้อมใช้ใน PDF, อีเมล HTML หรือป้ายพิมพ์ + +## โปรแกรมที่สามารถรันได้เต็มรูปแบบ + +ด้านล่างเป็นโค้ดเต็มที่คุณสามารถคัดลอกไปใส่ใน `Program.cs`. โค้ดนี้จะคอมไพล์และรันได้โดยไม่ต้องแก้ไข (สมมติว่าได้ติดตั้งแพคเกจ Aspose.BarCode แล้ว) + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +การรันโปรแกรมจะแสดงข้อความสองบรรทัดคล้ายกับ: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +เปิดโฟลเดอร์ `Barcodes` คุณจะเห็นไฟล์ PNG สองไฟล์ ทั้งสองภาพสามารถเปิดด้วยโปรแกรมดูภาพใดก็ได้หรือฝังโดยตรงในเอกสาร + +![ตัวอย่างการบันทึกบาร์โค้ด](barcode-example.png){: .align-center alt="ตัวอย่างการบันทึกบาร์โค้ด"} + +## การปรับเปลี่ยนทั่วไปและกรณีขอบ + +| Scenario | Adjustment | +|----------|------------| +| **รูปแบบภาพที่แตกต่าง** | เปลี่ยน `BarCodeImageFormat.Png` เป็น `Jpeg`, `Gif` หรือ `Bmp` ตามต้องการ | +| **ขนาดผลลัพธ์ที่กำหนดเอง** | ใช้ `filled.Parameters.Image.Width` และ `Height` เพื่อบังคับขนาดพิกเซลที่ต้องการ | +| **ข้อมูลแบบไดนามิก** | แทนที่สตริงคงที่ `"123456"` ด้วยตัวแปรที่เก็บหมายเลขคำสั่งซื้อ, ID การติดตาม ฯลฯ | +| **โฟลเดอร์ที่ไม่มีอยู่** | `Directory.CreateDirectory` จัดการโฟลเดอร์ที่ไม่มีอยู่แล้ว; ไม่ต้องเขียนโค้ดเพิ่มเติม | +| **การพิมพ์ความละเอียดสูง** | เพิ่มค่า `XDimension.Pixels` เป็น 6–8 สำหรับเครื่องพิมพ์ 600 dpi แต่ควรตรวจสอบความเข้ากันได้ของสแกนเนอร์ | + +**เคล็ดลับ:** หากคุณต้องการสร้างบาร์โค้ดจำนวนมากในลูป ให้ใช้อินสแตนซ์ `BarcodeGenerator` เพียงตัวเดียวและเปลี่ยนเฉพาะคุณสมบัติ `CodeText` ก่อนแต่ละการ `Save` วิธีนี้จะลดภาระการจัดสรรอ็อบเจกต์ + +## วิธีสร้างบาร์โค้ดสำหรับมาตรฐานอื่น + +รูปแบบเดียวกันทำงานกับ `EncodeTypes` อื่น ๆ เช่น `Code128`, `QR` หรือ `DataMatrix` เพียงแทนที่ `EncodeTypes.Planet` ด้วยประเภทที่ต้องการและปรับพารามิเตอร์เฉพาะประเภท (เช่น `QRCodeVersion` + +## สิ่งที่คุณควรเรียนต่อไป + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลรวมตัวอย่างโค้ดที่ทำงานครบถ้วนพร้อมคำอธิบายเป็นขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้แบบอื่นในโปรเจกต์ของคุณ + +- [วิธีบันทึก PNG ด้วย DataMatrix C40 ด้วย Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [วิธีสร้างบาร์โค้ด DataMatrix (ECC 200) ด้วย Aspose.BarCode สำหรับ .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [วิธีสร้างบาร์โค้ด – การกำหนดค่า Code 39 ด้วย Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/turkish/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..fa359b9b1 --- /dev/null +++ b/barcode/turkish/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-08-03 +description: Aspose.BarCode ile Planet barkodu oluşturmayı, X‑boyutunu ayarlamayı + ve PNG görüntüleri olarak kaydetmeyi gösteren C# barkod oluşturucu öğreticisi. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: tr +lastmod: 2026-08-03 +og_description: Barkod oluşturucu C# öğreticisi, Planet barkodu oluşturmayı, X‑boyutunu + ayarlamayı ve Aspose.BarCode kullanarak PNG olarak kaydetmeyi adım adım gösterir. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Barkod oluşturucu C# – Planet barkodunu adım adım oluştur. +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Barkod oluşturucu C# – Planet barkodu ve RM4SCC örneği +url: /tr/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – Planet barkod ve RM4SCC örneği oluşturma + +Eğer posta‑spesifik semboller üretebilen bir **barcode generator C#**'a ihtiyacınız varsa, bu rehber Aspose.BarCode ile **Planet barkod** görüntülerini nasıl oluşturacağınızı tam olarak gösterir. X‑dimension'ı nasıl yapılandıracağınızı, eşleşen bir RM4SCC barkodu nasıl üreteceğinizi ve ikisini de PNG dosyaları olarak nasıl kaydedeceğinizi birkaç kısa adımda göreceksiniz. + +Bu öğretici, .NET 6 veya daha yeni bir sürümde kodu çalıştırmak için ihtiyacınız olan her şeyi kapsar, her ayarın neden önemli olduğunu açıklar ve hatalı modül genişliği ya da eksik klasör izinleri gibi yaygın tuzakları işaret eder. Sonunda, Planet ve RM4SCC standartlarına uygun, doğrudan yazdırılabilir iki barkod görüntüsüne sahip olacaksınız. + +## Önkoşullar + +Başlamadan önce şunların kurulu olduğundan emin olun: + +* .NET 6 SDK (veya Aspose.BarCode tarafından desteklenen herhangi bir .NET sürümü) +* Visual Studio 2022 veya tercih ettiğiniz herhangi bir C# IDE +* **Aspose.BarCode** NuGet referansı (`Install-Package Aspose.BarCode`) +* PNG dosyalarını saklayacağınız klasöre yazma izni + +Ek bir dış hizmete ihtiyaç yoktur; kütüphane tüm kodlamayı yerel olarak gerçekleştirir. + +## Adım 1: barcode generator C# nesnesini başlatma + +İlk görev, `BarcodeGenerator` örneği oluşturmaktır. Yapıcı, barkod sembolünü (`EncodeTypes.Planet`) ve kodlanacak veriyi alır. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Bu adım neden?* +`BarcodeGenerator`, oluşturduğunuz her barkodun giriş noktasıdır. `EncodeTypes.Planet` seçimi, kütüphaneye birçok posta servisi tarafından kullanılan ISO/IEC 24723 spesifikasyonunu takip etmesini söyler. + +## Adım 2: Planet barkodu için X‑dimension (modül genişliği) ayarlama + +X‑dimension, tek bir barkod modülünün (en küçük çubuk ya da boşluk) genişliğini tanımlar. **4 piksel** değeri çoğu etiket yazıcısı için iyi çalışır. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Neden önemli?* +Modül çok dar olursa barkod okunamaz; çok geniş olursa etiket boyutu gereksiz yere büyür. `Pixels` ayarı, barkodu belirli bir yazıcı çözünürlüğüne göre ince ayar yapmanızı sağlar. + +## Adım 3: Planet barkodunu PNG görüntüsü olarak kaydetme + +Aspose.BarCode, seçilen sembol tipine göre barkod yüksekliğini otomatik olarak hesaplar; bu yüzden sadece dosya yolunu ve formatını belirtmeniz yeterlidir. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*İpucu* +`YOUR_DIRECTORY` ifadesini, makinenizde mevcut olan mutlak ya da göreli bir yol ile değiştirin. Klasör mevcut değilse `Save` metodu `DirectoryNotFoundException` hatası fırlatır. + +**Beklenen çıktı** – aşağıdaki illüstrasyona benzer bir PNG dosyası (gerçek görüntü burada gösterilmemiştir, ancak `123456` sayısal yükü içeren klasik bir Planet barkodu göreceksiniz). + +## Adım 4: RM4SCC barkodu için ikinci bir üretici başlatma + +Birçok posta sistemi, aynı posta parçasında hem Planet hem de RM4SCC sembollerinin bulunmasını ister. RM4SCC sembolü için yeni bir `BarcodeGenerator` örneği oluşturun. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Neden ayrı bir örnek?* +Her sembol tipinin kendi parametre seti vardır. Aynı üreticiyi yeniden kullanmak, ikinci barkod için optimal olmayan ayarların (örneğin X‑dimension) taşınmasına neden olabilir. + +## Adım 5: RM4SCC barkodu için X‑dimension ayarlama + +RM4SCC de X‑dimension ayarını dikkate alır, bu yüzden görsel tutarlılık için aynı piksel genişliğini uygularız. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Profesyonel ipucu* +Daha uzun bir barkod (ör. büyük etiketler için) gerekiyorsa `Height.Pixels` değerini de ayarlayabilirsiniz. Bunu bırakmazsanız kütüphane ideal yüksekliği otomatik olarak hesaplar. + +## Adım 6: RM4SCC barkodunu PNG görüntüsü olarak kaydetme + +Son olarak, RM4SCC barkodunu diske kaydedin. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Artık iki PNG dosyanız var—`PostalPlanetBarHeightNone.png` ve `PostalRM4SCCBarHeightNone.png`—bu dosyaları posta etiketlerine gömebilir, zarflara yazdırabilir veya üçüncü taraf bir baskı hizmetine gönderebilirsiniz. + +## İsteğe bağlı: Yüksekliği ayarlama veya diğer görüntü formatlarını kullanma + +İş akışınız belirli bir barkod yüksekliği ya da farklı bir görüntü formatı (ör. JPEG veya BMP) gerektiriyorsa, `Save` çağrısından önce parametreleri değiştirebilirsiniz: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Köşe durumu** – Özel bir yükseklik ayarladığınızda, değerin ISO standardı tarafından belirlenen minimum yüksekliğe uygun olduğundan emin olun; aksi takdirde barkod doğrulama hatası alabilirsiniz. + +## Yaygın tuzaklar ve nasıl önlenir + +| Sorun | Neden oluşur | Çözüm | +|-------|--------------|------| +| `DirectoryNotFoundException` | Hedef klasör mevcut değil ya da adı yanlış yazılmış. | Önce klasörü oluşturun veya `Path.Combine` ile `Environment.CurrentDirectory` kullanın. | +| Düşük çözünürlüklü yazıcılarda barkod okunamıyor | X‑dimension, yazıcının DPI'sı için çok küçük. | 203 dpi yazıcılar için `XDimension.Pixels` değerini 5 – 6'ya yükseltin veya örnek bir etiketle test edin. | +| Yanlış sembol tipi kullanıldı | `EncodeTypes.Code128` yerine `EncodeTypes.Planet` gönderildi. | `EncodeTypes` enum değerinin gerekli posta standardına uygun olduğundan emin olun. | +| `Parameters` üzerinde null referans | API farklılığı olan eski bir Aspose.BarCode sürümü kullanılıyor. | En son NuGet paketine (v23.12 veya üzeri) yükseltin. | + +## Tam çalıştırılabilir örnek + +Aşağıda, kopyalayıp yapıştırıp çalıştırabileceğiniz tam program yer alıyor. `using` ifadeleri, hata yönetimi ve her satırı açıklayan yorumlar içerir. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Programı çalıştırdığınızda çalıştırılabilir dosyanın yanına bir `Barcodes` klasörü oluşturulur ve iki PNG dosyası içine yerleştirilir. Çıktıyı doğrulamak için herhangi bir görüntü görüntüleyiciyle açın. + +## Sonuç + +Artık **barcode generator C#** çözümünüz var; **Planet barkod** görüntüleri oluşturabiliyor, optimal baskı için X‑dimension'ı ayarlayabiliyor ve eşleşen bir RM4SCC barkodu üretebiliyorsunuz—bütün bunlar sadece birkaç satır kodla. Yaklaşım .NET 6+ ile çalışır, yalnızca Aspose.BarCode NuGet paketine ihtiyaç duyar ve `EncodeTypes` değerini değiştirerek Code128, QR veya DataMatrix gibi diğer sembollere genişletilebilir. + +### Sırada ne var? + +* Yazıcınızın DPI'ına uygun farklı `XDimension.Pixels` değerleriyle denemeler yapın. +* `BarCodeImageFormat` enum'ını değiştirerek barkodları diğer formatlarda (PDF, SVG) üretin. +* **SkiaSharp** gibi bir grafik kütüphanesi kullanarak iki PNG dosyasını tek bir etikete birleştirin. +* Kontrol toplamı doğrulama veya özel yazı tipleri gibi gelişmiş özellikler için tam Aspose.BarCode API'sını keşfedin. + +Kodunuzu toplu işleme için uyarlamaktan veya isteğe bağlı barkod görüntüleri dönen bir ASP.NET Core web hizmetine entegre etmekten çekinmeyin. Mutlu kodlamalar! + +## Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan ve 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. + +- [Barcode PNG Oluştur – DataMatrix En/Boy Oranı – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [DataMatrix C40 ile PNG Kaydetme – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Code 16K Barkod En/Boy Oranlarını Aspose.BarCode ile .NET için Özelleştirme](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/turkish/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..7b81ee5c5 --- /dev/null +++ b/barcode/turkish/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-08-03 +description: Barcode generator C# öğreticisi, Aspose.BarCode ile barkod görüntüsü + oluşturmayı, sütun ve satırları ayarlamayı ve DataBar Expanded Stacked için PNG + dosyalarını kaydetmeyi gösterir. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: tr +lastmod: 2026-08-03 +og_description: Barcode generator C# öğreticisi, Aspose.BarCode kullanarak barkod + resmi oluşturmayı, DataBar Expanded Stacked sütun ve satırlarını yapılandırmayı + ve PNG dosyalarını kaydetmeyi açıklar. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Barkod oluşturucu C# – barkod görüntüsü oluşturmak için adım adım rehber +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Barkod oluşturucu C# – barkod resmi oluştur +url: /tr/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Barcode generator C# – barkod resmi oluşturma + +DataBar Expanded Stacked için barkod resmi oluşturabilen bir barcode generator C#'a ihtiyacınız varsa, bu kılavuz sizi tam süreç boyunca yönlendirecek. Sütun ve satır ayarlarını nasıl yapılandıracağınızı, sonucu PNG olarak nasıl kaydedeceğinizi ve kodu diğer sembolojilere nasıl uyarlayacağınızı öğreneceksiniz. + +Barkod resimlerini programlı olarak oluşturmak, manuel adımları ortadan kaldırır ve faturalar, gönderi etiketleri ve envanter sistemleri arasında tutarlılığı sağlar. Bu öğretici, proje kurulumundan tam kaynak koduna kadar ihtiyacınız olan her şeyi kapsar, böylece örneği hemen çalıştırabilirsiniz. + +## Prerequisites + +Başlamadan önce şunların yüklü olduğundan emin olun: + +* .NET 6.0 veya daha yeni bir sürüm +* Visual Studio 2022 gibi bir IDE (C# destekleyen herhangi bir editör yeterlidir) +* **Aspose.BarCode for .NET** lisansı – ücretsiz deneme sürümü test için çalışır +* C# sözdizimi hakkında temel bilgi + +Bu öğelerden herhangi biri eksikse, .NET SDK'yı dotnet.microsoft.com adresinden indirip Aspose.BarCode NuGet paketini şu şekilde edinin: + +```bash +dotnet add package Aspose.BarCode +``` + +## Step 1: Create a barcode generator C# project + +Yeni bir konsol uygulaması oluşturun ve gerekli `using` yönergelerini ekleyin: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +`BarcodeGenerator` sınıfı, barcode generator C# API'sinin çekirdeğidir. Semboloji tipini ve kodlanacak metni alır. + +## Step 2: Generate a DataBar Expanded Stacked barcode and set columns + +İlk örnek, dört sütunlu bir barkod oluşturur. `Columns` özelliğini ayarlamak, DataBar Expanded Stacked sembolojisinin görsel yoğunluğunu değiştirir. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Why this matters:** Sütun sayısı, kompakt bir alanda saklanabilecek veri miktarını etkiler.  4  olarak ayarlandığında, çoğu tarayıcı tarafından okunabilir daha geniş bir barkod elde edilir. + +## Step 3: Generate a barcode with custom row count + +İkinci örnek, `Rows` özelliğini ayarlayarak dikey yerleşimi nasıl kontrol edeceğinizi gösterir. Üç satırlı bir yapı, yatay alan sınırlı olduğunda daha yüksek bir barkod gerektiğinde kullanışlıdır. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Why this matters:** Satırları ayarlamak, barkodu dar bir sütuna sığdırırken okunabilirliği korumanızı sağlar. barcode generator C# otomatik olarak modül boyutunu yeniden hesaplayarak spesifikasyona uyar. + +## Step 4: Full, runnable example + +Aşağıda önceki adımları birleştiren bağımsız bir program yer alıyor. Kodu `Program.cs` içine kopyalayın, `YOUR_DIRECTORY` ifadesini mevcut bir klasör yolu ile değiştirin ve uygulamayı çalıştırın. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Expected output + +Programı çalıştırdığınızda hedef klasörde iki PNG dosyası oluşur: + +* **DatabarCols4.png** – dört sütunlu bir DataBar Expanded Stacked barkod +* **DatabarRows3.png** – aynı verinin üç satırda kodlandığı barkod + +Görüntüleri herhangi bir resim görüntüleyiciyle açın; baskı için ya da PDF'lere gömmek üzere hazır, keskin ve taranabilir barkodlar gösterir. + +## How to generate barcode image with custom dimensions + +Belirli bir resim boyutuna ihtiyacınız varsa, `Save` metodunu çağırmadan önce `ImageHeight` ve `ImageWidth` özelliklerini ayarlayın: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Boyutları değiştirmek kodlanan veriyi etkilemez; sadece görsel temsili ölçeklendirir. Bu teknik, sabit düzen kısıtlamalarına sahip UI bileşenlerine barkod eklerken faydalıdır. + +## Common pitfalls and pro tips + +* **Path separators:** Windows'ta kaçış karakteri sorunlarından kaçınmak için verbatim string (`@"C:\Path\file.png"`) ya da `Path.Combine` kullanın. +* **License enforcement:** Geçerli bir lisans olmadan oluşturulan resimler filigran içerir. Lisansınızı uygulamanın başında şu şekilde yükleyin: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Encoding limits:** DataBar Expanded Stacked en fazla 74 sayısal karakteri destekler. Bu limiti aşmak bir istisna fırlatır. Üreteci oluşturmadan önce giriş uzunluğunu doğrulayın. +* **Performance:** Birden fazla kaydetme işlemi için tek bir `BarcodeGenerator` örneği yeniden kullanmak bellek tahsislerini azaltır. Kodlanan metin aynı kalıyorsa, kaydetmeler arasında yalnızca `Rows` veya `Columns` özelliklerini değiştirin. + +## Next steps + +Artık barcode generator C# ile barkod resimleri oluşturabildiğinize göre, aşağıdakileri keşfetmeyi düşünün: + +* **Different symbologies** – `EncodeTypes.QR`, `EncodeTypes.Code128` veya `EncodeTypes.Pdf417` deneyin. +* **Color customization** – `Parameters.Barcode.ForeColor` ve `BackColor` ayarlarıyla marka renklerinize uyum sağlayın. +* **Embedding in PDFs** – Oluşturulan PNG'yi Aspose.PDF ile birleştirerek yazdırılabilir belgeler oluşturun. + +Bu genişletmeler, envanter, lojistik veya perakende uygulamaları için tam özellikli bir barkod çözümü oluşturmanıza olanak tanır. + +--- + + +## What Should You Learn Next? + + +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 tam çalışan kod örnekleri ve adım‑adım açıklamalar içerir. + +- [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 Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/turkish/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..619e08a8a --- /dev/null +++ b/barcode/turkish/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-08-03 +description: C#'ta genişlik ayarlama, yüksekliği değiştirme ve barkod görüntüsü oluşturma + yöntemlerini gösteren barkod oluşturucu örneği. Adım adım talimatları izleyin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: tr +lastmod: 2026-08-03 +og_description: Barkod oluşturucu örneği, X‑boyut genişliğini ayarlamayı, çubuk yüksekliğini + değiştirmeyi ve C#'ta bir barkod resmi oluşturmayı gösterir. PNG dosyaları oluşturmak + için adımları izleyin. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Barkod oluşturucu örneği – C# genişlik ve yükseklik rehberi +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: C#'ta barkod oluşturucu örneği – genişlik ve yüksekliği ayarlama +url: /tr/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta barkod oluşturucu örneği – genişlik ve yükseklik ayarlama + +C#'ta bir **barcode generator example**'a ihtiyacınız varsa, bu rehber X‑dimension genişliğini nasıl ayarlayacağınızı, çubuk yüksekliğini nasıl değiştireceğinizi ve bir barkod görüntü dosyası nasıl oluşturacağınızı gösterir. Farklı yüksekliklerde iki PNG dosyası üreten tam, çalıştırılabilir bir program göreceksiniz. + +Tipik bir senaryo, barkod boyutunun tarayıcı gereksinimlerini karşılaması gereken ürün etiketleri oluşturmaktır. Bu öğreticinin sonunda genişlik ve yükseklik parametrelerini programlı olarak ayarlayabilecek ve sonucu PNG görüntüsü olarak kaydedebileceksiniz. + +## Önkoşullar + +* .NET 6 (veya daha yeni) yüklü – kod .NET 6 SDK'sını hedefler. +* `EncodeTypes.DatabarOmniDirectional`'ı destekleyen bir barkod kütüphanesi. Örnek **Aspose.BarCode for .NET** kullanıyor, ancak benzer özellikleri sunan herhangi bir kütüphane aynı şekilde çalışır. +* Programı derlemek ve çalıştırmak için bir IDE veya editör (Visual Studio, VS Code, Rider). +* PNG dosyalarının kaydedileceği dizine yazma izni. + +> **Pro tip:** Proje kök dizininizde `Barcodes` adlı bir klasör oluşturun ve mutlak yolları sabit kodlamaktan kaçınmak için `Path.Combine` ile referans verin. + +## Barkod oluşturucu örneği: başlatma ve yapılandırma + +İlk adım, istenen semboloji ve veri dizesiyle bir `BarcodeGenerator` örneği oluşturmaktır. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +`EncodeTypes.DatabarOmniDirectional` enum'u Databar Omni‑directional sembolojisini seçer ve GS1‑formatlı veri dizesi `(01)12345678901231` tipik bir GTIN‑14 değerini temsil eder. Üreteci bir kez başlatmak, aynı nesneyi birden fazla görüntü için yeniden kullanmanıza olanak tanır. + +## Genişliği (X‑dimension) nasıl ayarlarsınız + +X‑dimension, barkodun modül genişliğini kontrol eder. 2 piksel olarak ayarlandığında, her dar çubuk 2 piksel genişliğinde olur; bu, yüksek yoğunluklu baskı için yaygın bir gereksinimdir. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Neden önemli: Genişlik çok küçük olursa, tarayıcılar tek tek çubukları ayıramayabilir; çok büyük olursa barkod etiket alanını aşabilir. Piksel değerini, yazıcı DPI'sı ve hedef etiket boyutuyla eşleşecek şekilde ayarlayın. + +## Yüksekliği nasıl değiştirirsiniz + +Çubuk yüksekliği, çubukların ne kadar uzun görüneceğini belirler. Örnek, 30 piksel yüksekliğinde bir ve 60 piksel yüksekliğinde bir olmak üzere iki görüntü oluşturur. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +`BarHeight.Pixels` özelliği, çubukların görsel yüksekliğini doğrudan etkiler. Kaydetmeler arasında değiştirmek, aynı veri yükünden birden fazla varyant üretmenizi, üreticiyi yeniden oluşturmanıza gerek kalmadan sağlar. + +### Beklenen çıktı + +Programı çalıştırmak, `Barcodes` klasöründe iki PNG dosyası üretir: + +* `DatabarBarHeight30Pixels.png` – çubuklar 30 piksel yüksekliğinde. +* `DatabarBarHeight60Pixels.png` – çubuklar 60 piksel yüksekliğinde. + +Her iki görüntü de aynı genişliği (X‑dimension tarafından belirlenir) paylaşır ve aynı GTIN‑14 verisini kodlar. + +![C# kodu ile oluşturulan farklı yüksekliklerde iki barkod PNG dosyası](barcode-example.png "Yükseklik varyasyonlarını gösteren barkod oluşturucu örneği") + +*Yukarıdaki görüntü alt metni, erişilebilirlik ve SEO için birincil anahtar kelimeyi içerir.* + +## C#'ta barkod görüntüsü nasıl oluşturulur + +`Save` yöntemi, barkod verisini bir görüntü dosyasına dönüştürmeyi yönetir. Farklı bir `BarCodeImageFormat` enum değeri geçirerek diğer formatları (JPEG, BMP, SVG) seçebilirsiniz. Örnek, kayıpsız kaliteyi koruduğu ve yaygın olarak desteklendiği için PNG kullanır. + +Barkodu doğrudan bir PDF'e veya web sayfasına yerleştirmeniz gerekiyorsa, görüntüyü bir `byte[]` olarak alın: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Bu yaklaşım geçici dosyalara ihtiyaç duyulmasını ortadan kaldırır ve yüksek verimli hizmetler için faydalıdır. + +## Yaygın varyasyonlar ve uç durumlar + +| Durum | Ayarlama | +|-----------|------------| +| **Farklı semboloji** | `EncodeTypes.DatabarOmniDirectional` yerine başka bir enum değeri (ör. `EncodeTypes.Code128`) ile değiştirin. | +| **Çok küçük etiketler** | `XDimension.Pixels` değerini 1 piksele düşürün, ancak tarayıcı okunabilirliğini doğrulayın. | +| **Yüksek çözünürlüklü baskı** | X‑dimension ve çubuk yüksekliğini orantılı olarak artırın (ör. 4 px genişlik, 80 px yükseklik). | +| **Dinamik veri** | Veri dizesini çalışma zamanında, belki bir veritabanı kaydından geçirin. | +| **Toplu oluşturma** | Veri dizesi koleksiyonu üzerinde döngü yapın, `generator.Text`'i güncellerken aynı `BarcodeGenerator` örneğini yeniden kullanın. | + +`ArgumentOutOfRangeException` gibi bir istisna ile karşılaştığınızda, piksel değerlerinin pozitif tam sayı olduğundan ve çıktı dizininin var olduğundan emin olun. + +## Tam kaynak kodu özeti + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Kodu yeni bir konsol projesine kopyalayın, Aspose.BarCode NuGet paketini geri yükleyin (`dotnet add package Aspose.BarCode`) ve `dotnet run` komutunu çalıştırın. Kaydedilen dosyaları onaylayan konsol mesajlarını göreceksiniz. + +## Sonuç + +Bu **barcode generator example**, genişliği nasıl ayarlayacağınızı, yüksekliği nasıl değiştireceğinizi ve C#'ta bir barkod görüntüsü nasıl oluşturacağınızı gösterir. `XDimension.Pixels` ve `BarHeight.Pixels` ayarlarıyla barkodun görsel boyutunu kontrol eder, `Save` yöntemi sonucu PNG dosyalarına yazar. Uygulamanızın gereksinimlerine uyacak şekilde farklı sembolojiler, çıktı formatları ve veri dizeleriyle deneyler yapın. + +**Sonraki adımlar** + +* Web kullanımı için diğer görüntü formatlarında (SVG, JPEG) **how to generate barcode**'ı keşfedin. +* ASP.NET Core uç noktaları için PNG'yi doğrudan tarayıcıya döndüren **create barcode image c#**'ı öğrenin. +* Bu kodu bir PDF oluşturma kütüphanesiyle birleştirerek barkodları faturalar veya gönderi etiketlerine yerleştirin. + +Örneği özgürce uyarlayın, sonuçlarınızı paylaşın veya yorumlarda sorular sorun. İyi kodlamalar! + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [Barkod Oluşturma - Tek Boyutlu Barkod Türleri](/barcode/english/net/one-dimensional-barcode-types/) +- [ITF-14 Barkod Özelleştirme için Kenar Ayarlama](/barcode/english/net/itf-14-barcode-customization/) +- [Aspose.BarCode for .NET ile DataMatrix Barkodları (ECC 200) Oluşturma](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/turkish/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..67a87636b --- /dev/null +++ b/barcode/turkish/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-08-03 +description: C#'ta barkod PNG oluşturun ve DataBar görüntülerinin en‑boy oranını nasıl + değiştireceğinizi öğrenin. Kod ve ipuçlarıyla bu tam örneği izleyin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: tr +lastmod: 2026-08-03 +og_description: C#'ta barkod PNG'si oluşturun ve DataBar barkodları için en boy oranını + nasıl değiştireceğinizi görün. Bu rehber, çalıştırmaya hazır kod ve pratik ipuçları + sunar. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: C#'ta barkod PNG oluşturma – en‑boy oranı kontrolüyle tam örnek +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: C#'ta barkod PNG oluşturma – adım adım rehber +url: /tr/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#’ta barkod PNG oluşturma – adım adım rehber + +C#’ta **barcode PNG** oluşturmanız gerekiyorsa, bu öğretici size tam olarak nasıl yapılacağını gösterir. Yığılmış çok yönlü DataBar barkodu oluşturacak, PNG dosyası olarak kaydedecek ve **aspect ratio’yu nasıl değiştireceğinizi** farklı tarama ortamlarına uyacak şekilde öğreneceksiniz. + +Kılavuz, ihtiyacınız olan her şeyi kapsar: gerekli paketler, tam ve çalıştırılabilir bir program ve her ayarın neden önemli olduğuna dair açıklamalar. Sonunda iki PNG dosyanız olacak—biri aspect ratio’su 15, diğeri 30—test veya üretim için hazır. + +## Önkoşullar + +- .NET 6.0 SDK veya daha yeni bir sürüm yüklü +- Visual Studio 2022 (veya herhangi bir C# IDE) +- **Aspose.BarCode**’a bir NuGet referansı ( `BarcodeGenerator` sağlayan kütüphane) +- PNG dosyalarının kaydedileceği dizine yazma izni + +Aspose.BarCode paketini aşağıdaki komutla ekleyebilirsiniz: + +```bash +dotnet add package Aspose.BarCode +``` + +## Adım 1: Projeyi kurun ve ad alanlarını içe aktarın + +Yeni bir konsol uygulaması oluşturun ve barkod oluşturma ve dosya I/O için gerekli ad alanlarını içe aktarın. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Neden önemli:** `Aspose.BarCode.Generation`’ı içe aktarmak, `BarcodeGenerator`’a erişmenizi sağlar. Kodu `Main` içinde tutmak, örneği bağımsız ve çalıştırması kolay hâle getirir. + +## Adım 2: Yığılmış çok yönlü DataBar için bir barkod üreticisi oluşturun + +`BarcodeGenerator`’ı `EncodeTypes.DatabarStackedOmniDirectional` türü ve örnek bir GS1‑128 veri dizesi ile örnekleyin. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Neden önemli:** Seçilen kodlama türü, çoğu modern tarayıcı tarafından okunabilen yüksek yoğunluklu bir DataBar üretir. Veri dizesi, ürün tanımlayıcıları için yaygın olan GS1 Application Identifier (01) formatını izler. + +## Adım 3: X‑boyutunu (modül genişliği) piksel olarak tanımlayın + +Barkodun genel boyutunu kontrol etmek, okunabilirliğini etkilemeden modül genişliğini ayarlayın. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Neden önemli:** 2 piksel X‑boyutu, tarayıcılar için ne çok küçük ne de tipik etiket alanları için çok büyük bir barkod üretir. + +## Adım 4: İlk PNG'yi aspect ratio 15 ile kaydedin + +DataBar aspect ratio’sunu ayarlayın, ardından görüntüyü PNG dosyası olarak kaydedin. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Neden önemli:** Aspect ratio, yığılmış DataBar’ın yükseklik‑genişlik ilişkisini kontrol eder. 15 oranı, okunabilirlik ve etiket yüksekliğini dengeleyen yaygın bir varsayılandır. + +## Adım 5: Aspect ratio’yu 30’a değiştirin ve ikinci PNG'yi kaydedin + +Aynı üretici örneğini daha büyük bir aspect ratio kullanacak şekilde değiştirin, ardından ikinci görüntüyü kaydedin. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Neden önemli:** Aspect ratio’nun artırılması barkodu dikey olarak uzatır, bu da düşük çözünürlüklü cihazlarda veya etiket dar bir ortamda basıldığında tarama güvenilirliğini artırabilir. + +## Beklenen çıktı + +Programı çalıştırmak iki PNG dosyası oluşturur: + +| Dosya | Aspect Ratio | Yaklaşık boyutlar (piksel) | +|------------------------------------|--------------|---------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (width × height) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (width × height) | + +Her iki görüntü de `(01)12345678901231` GS1 tanımlayıcısını kodlayan net, taranabilir bir DataBar barkodu içerir. + +## Yaygın sorular ve uç durumlar + +### Diğer görsel özellikler nasıl değiştirilir? + +`generator.Parameters.Barcode` nesnesi aracılığıyla ön plan rengini, arka plan rengini ayarlayabilir veya insan tarafından okunabilir metin ekleyebilirsiniz. Örneğin: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Farklı bir görüntü formatına ihtiyacım olsaydı ne olur? + +Gerektiğinde `BarCodeImageFormat.Png` yerine `Jpeg`, `Bmp` veya `Gif` kullanın. PNG, kayıpsız barkod görüntüleri için en iyi seçim olmaya devam eder. + +### Aspect ratio tarama hızını etkiler mi? + +Daha yüksek aspect ratio’lar barkodun yüksekliğini artırır, bu da kısa yığılmış sembollerle zorlanan cihazlarda tarama güvenilirliğini artırabilir. Ancak, çok yüksek barkodlar küçük etiketlere sığmayabilir, bu yüzden hedef donanımınızla test edin. + +### Döngü içinde birden fazla barkod üretebilir miyim? + +Evet. Her veri dizesi için yeni bir `BarcodeGenerator` örneği oluşturun veya aynı örneği `CodeText` ve `DataBar.AspectRatio` değerlerini güncelleyerek yeniden kullanın. Bu yaklaşım nesne tahsis yükünü azaltır. + +## Profesyonel ipuçları + +- **Generator'ı yeniden kullanın**: Sadece `CodeText` veya `AspectRatio`'yu değiştirerek nesneyi yeniden örneklemeyi önlersiniz, bu da toplu işleme hızını artırır. +- **Çıktıyı doğrulayın**: Üretilen PNG'nin doğru okunduğunu doğrulamak için bir el tipi tarayıcı veya mobil uygulama kullanın, üretime dağıtmadan önce. +- **Dosya adlandırma**: Test sırasında varyasyonları takip etmek için dosya adına aspect ratio'yu (gösterildiği gibi) ekleyin. + +## Sonuç + +Artık C#’ta **barcode PNG** dosyaları oluşturmayı ve yığılmış çok yönlü DataBar sembolleri için **aspect ratio’yu nasıl değiştireceğinizi** tam olarak biliyorsunuz. Tam örnek, başlatmayı, X‑boyut ayarını, aspect‑ratio manipülasyonunu ve görüntü kaydetmeyi—hepsi tek bir çalıştırılabilir programda—gösterir. + +Buradan, ek barkod türlerini keşfedebilir, renklerle deneyler yapabilir veya üreticiyi daha büyük bir raporlama ya da envanter sistemine entegre edebilirsiniz. Kodlamanın tadını çıkarı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 öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [Barcode PNG Oluştur – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [Aspose.BarCode for .NET kullanarak özel aspect ratio ile Aztec barkod nasıl oluşturulur](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Barcode Özelleştirme – Codablock F Aspect Ratio – Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/turkish/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..ce4c1ba17 --- /dev/null +++ b/barcode/turkish/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-08-03 +description: Bu kılavuzla barkod PNG'sini hızlıca oluşturun. Aspose.BarCode kullanarak + barkod görüntüsü oluşturmayı ve gezegen barkodu üretmeyi öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: tr +lastmod: 2026-08-03 +og_description: Barkod PNG'sini anında oluşturun. Bu öğreticide, barkod görüntüsü + oluşturma ve Aspose.BarCode ile gezegen barkodu oluşturma gösterilmektedir. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Python'da barkod PNG oluşturma – tam programlama rehberi +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Python’da barkod PNG oluşturma – adım adım rehber +url: /tr/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python'da barcode PNG oluşturma – adım adım rehber + +Python uygulamanızdan **barcode PNG** dosyaları oluşturmanız gerekiyorsa, bu öğretici tam olarak nasıl yapılacağını gösterir. Aspose.BarCode kullanarak **barcode görüntüsü oluşturmayı** ve özellikle **özel boyutlarla planet barcode** üretmeyi adım adım anlatacağız. + +Kütüphaneyi nasıl kuracağınızı, Planet sembolojisini nasıl yapılandıracağınızı, boyut parametrelerini nasıl ayarlayacağınızı ve sonucu yüksek kaliteli bir PNG olarak nasıl kaydedeceğinizi öğreneceksiniz. Rehber temel Python bilgisi ve Python 3'ün (3.8 veya daha yeni) bir sürümünü varsayar. Barcode standartlarıyla ilgili önceden bir deneyim gerektirmez. + +--- + +## Aspose.BarCode ile barcode PNG oluşturma + +Bu bölüm, **barcode PNG** oluşturmak için gereken temel adımları içerir. Her adım bir kod parçacığı, neden önemli olduğuna dair bir açıklama ve hemen uygulayabileceğiniz pratik ipuçları içerir. + +### 1. Aspose.BarCode paketini kurun + +Aspose, .NET çekirdek motorunu saran saf bir Python paketi sunar. Bunu `pip` ile kurun: + +```bash +pip install aspose-barcode +``` + +*Neden bu adım önemlidir:* Paket, örnek boyunca kullanılan `BarcodeGenerator` sınıfını sağlar. Global olarak kurmak, yorumlayıcının çalışma zamanında assembly'i bulmasını sağlar. + +### 2. Gerekli sınıfları içe aktarın + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*İpucu:* Sadece ihtiyacınız olan sembolleri içe aktarın; bu, ad alanını temiz tutar ve modül yüklemesini hızlandırır. + +### 3. Planet sembolojisi için bir barcode jeneratörü oluşturun + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*Neden bu önemlidir:* `EncodeTypes.Planet`, motorun Planet barcode standardını kullanmasını söyler, ikinci argüman ise kodlanacak veriyi sağlar. Sembolojiyi değiştirmek (ör. `EncodeTypes.Code128`) tamamen farklı bir görsel desen üretir. + +### 4. X boyutunu (modül genişliği) piksel olarak ayarlayın + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*Açıklama:* X boyutu, dar çubuk genişliğini kontrol eder. 4 piksel değeri, çoğu cihazda taranabilir kalacak orta yoğunlukta bir barcode üretir. + +### 5. Manuel çubuk yüksekliğini piksel olarak tanımlayın + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*Neden ayarlamak isteyebilirsiniz:* Bazı perakende yazıcıları güvenilir tarama için daha yüksek çubuklar gerektirir. Varsayılan yükseklik genellikle 50 px'tir; 100 px'e çıkarmak dosya boyutunu büyük ölçüde artırmadan okunabilirliği artırır. + +### 6. Oluşturulan barcode'ı PNG görüntüsü olarak kaydedin + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Sonuç:* **PlanetBarHeight100.png** adlı bir PNG dosyası `output` klasöründe oluşur. PNG kayıpsızdır, bu da baskı ve web sayfalarına gömme için idealdir. + +### 7. Çıktıyı doğrulayın (isteğe bağlı) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*İpucu:* Görüntüyü görmek, boyutların ayarladığınız parametrelerle eşleştiğini doğrular. Barcode bozuk görünüyorsa, X boyutunu veya çubuk yüksekliği ayarlarını yeniden gözden geçirin. + +--- + +## PNG formatında barcode görüntüsü oluşturma (alternatif ayarlar) + +Farklı bir görüntü formatına ihtiyacınız varsa veya barcode'ı daha sonra bir PDF'e gömmek istiyorsanız, `BarCodeImageFormat` enum'ını değiştirebilirsiniz: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*Neden bu önemlidir:* PNG her pikseli korur, bu da yüksek kontrastlı barcode'lar için kritiktir. JPEG sıkıştırma artefaktları ekler ve taramayı engelleyebilir, BMP ise eski araçlarla uyumluluk sağlar. + +--- + +## Özel renklerle planet barcode oluşturma (ileri düzey) + +Boyutun ötesinde, ön plan ve arka plan renklerini özelleştirebilirsiniz: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Pratik ipucu:* Yüksek kontrastlı renk çiftleri (açık üzerinde koyu) tarayıcı güvenilirliğini maksimize eder. Ön plan ve arka plan için benzer tonlar kullanmaktan kaçının. + +--- + +## Yaygın tuzaklar ve nasıl önlenir + +| Belirti | Neden | Çözüm | +|---------|-------|-----| +| Barcode taranmaz | X boyutu çok küçük (≤ 2 px) | `x_dimension.pixels` değerini en az 3 px'e artırın | +| Görüntü bulanık | PNG düşük DPI ile kaydedildi | `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` kullanarak 300 DPI belirtin (destekleniyorsa) | +| `ImportError` istisnası | Aspose.BarCode yüklü değil | Betiğinizle aynı ortamda `pip install aspose-barcode` komutunu çalıştırın | +| Yanlış semboloji | `EncodeTypes.Planet` yerine `EncodeTypes.Code128` kullanıldı | Jeneratör oluştururken `EncodeTypes.Planet` ile değiştirin | + +--- + +## Tam çözümün özeti + +Aşağıda, **barcode PNG** oluşturacak tam, çalıştırılabilir betik yer almaktadır: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Bu betiği çalıştırmak, HTML'ye gömebileceğiniz, e-postalara ekleyebileceğiniz veya ürün etiketlerine basabileceğiniz net bir **Planet barcode PNG** üretir. + +--- + +## Sonraki adımlar ve ilgili konular + +* **Flask veya Django ile bütünleştirin** – oluşturulan PNG'yi doğrudan bir web uç noktasından hizmet verin. +* **Toplu üretim** – ürün kimlikleri listesini döngüye alarak barcode PNG dosyalarından bir klasör oluşturun. +* **PDF üretimiyle birleştirin** – `aspose-pdf` kullanarak PNG'yi bir fatura veya gönderi etiketine yerleştirin. +* **Diğer sembolojileri keşfedin** – farklı iş ihtiyaçlarını karşılamak için `EncodeTypes.Planet` yerine `EncodeTypes.QR`, `EncodeTypes.DataMatrix` veya `EncodeTypes.Code128` kullanın. + +Yukarıdaki adımları kavrayarak, artık programlı bir şekilde **barcode görüntüsü oluşturmayı** biliyorsunuz ve bu deseni Aspose.BarCode tarafından desteklenen herhangi bir barcode standardına genişletebilirsiniz. + +--- + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/turkish/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..69deb28ae --- /dev/null +++ b/barcode/turkish/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-08-03 +description: C#'ta posta barkodu görüntüsü hızlı bir şekilde oluşturun. Posta barkodu + nasıl oluşturulur, barkod boyutları nasıl ayarlanır ve Planet barkodu nasıl üretilir + öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: tr +lastmod: 2026-08-03 +og_description: Bu kapsamlı öğreticiyle C#’ta posta barkodu resmi oluşturun; barkod + boyutlarını nasıl ayarlayacağınızı, Planet barkodu üretmeyi ve RM4SCC barkodları + üretmeyi öğrenin. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: C# ile posta barkodu resmi oluşturma – tam programlama rehberi +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: C#'ta posta barkodu resmi oluşturma – adım adım rehber +url: /tr/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta posta barkod görüntüsü oluşturma – adım adım rehber + +C#'ta **posta barkod görüntüsü oluşturmanız** gerekiyorsa, bu rehber tam olarak nasıl yapılacağını gösterir. **Posta barkodu nasıl oluşturulur**, **barkod boyutları nasıl ayarlanır** ve yaygın posta standartları için **planet barkodu nasıl oluşturulur** konularını ele alacağız. + +İki hazır PNG dosyasıyla—bir Planet barkodu ve bir RM4SCC barkodu—her biri 100 px yüksekliğinde bitireceksiniz. Aspose.BarCode for .NET kütüphanesinin dışında ek bir araç gerekmez. + +## Önkoşullar + +* .NET 6 SDK veya daha yenisi (kod .NET Framework 4.7+ ile de çalışır) +* Visual Studio 2022 veya herhangi bir C# IDE'si +* NuGet paketi **Aspose.BarCode** (`BarcodeGenerator` sağlayan kütüphane) + +## Adım 1: Barkod kütüphanesini kurun + +Proje klasörünüzde bir terminal açın ve şu komutu çalıştırın: + +```bash +dotnet add package Aspose.BarCode +``` + +Paket, posta barkodları için gerekli olan `BarcodeGenerator` ve `EncodeTypes` enumarasyonunu içeren `Aspose.BarCode` ad alanını ekler. + +## Adım 2: Çıktı klasörünü tanımlayın + +Güvenilir bir çıktı yolu oluşturmak, klasör mevcut olmadığında çalışma zamanı hatalarını önler. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Neden önemli*: `Directory.CreateDirectory` idempotenttir—klasör zaten mevcut değilse oluşturur, sonraki çalıştırmalarda istisna oluşmasını engeller. + +## Adım 3: Ortak barkod boyutlarını yapılandırın + +X‑boyutunu (tek bir çubuğun genişliği) ve toplam çubuk yüksekliğini ayarlamak, oluşturulan görüntünün görsel boyutunu kontrol etmenizi sağlar. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Barkod boyutları nasıl ayarlanır**: `Parameters.Barcode.XDimension.Pixels` özelliği dar çubuk genişliğini, `Parameters.Barcode.BarHeight.Pixels` ise tam yüksekliği tanımlar. Bu değerleri posta hizmetinizin gereksinimlerine göre ayarlayın. + +## Adım 4: Planet barkodu oluşturun + +Planet, Birleşik Krallık'ta yaygın olarak kullanılan bir posta barkodudur. Aşağıdaki kod, 100 px yüksekliğinde bir Planet barkodu oluşturur ve PNG olarak kaydeder. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Neden bu çalışır**: `EncodeTypes.Planet`, oluşturucuya Planet sembolojisini kullanmasını söyler. `Save` yöntemi, belirtilen yola bir PNG dosyası yazar ve daha önce ayarladığımız boyutları korur. + +## Adım 5: RM4SCC barkodu oluşturun + +RM4SCC, Hollanda posta barkod standardıdır. Aşağıdaki kod, Planet örneğini yansıtarak **farklı bir tipte posta barkodu nasıl oluşturulur** gösterir ve aynı boyutları kullanır. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Her iki PNG dosyası da artık `Barcodes` klasöründe bulunuyor. Açtığınızda, baskı veya belgeler içine yerleştirme için hazır, 100 px yüksekliğinde temiz barkodlar göreceksiniz. + +## Tam kaynak kodu + +Aşağıda, Planet ve RM4SCC standartları için **posta barkod görüntüsü oluşturur** tam ve çalıştırılabilir program yer almaktadır. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Beklenen çıktı + +Programı çalıştırmak dosya yollarını yazdırır ve iki PNG dosyası oluşturur: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Her görüntü 100 px yüksekliğinde, 4 piksel dar çubuk genişliğinde olup, ayarladığımız boyutlarla eşleşir. + +## Pratik ipuçları ve yaygın tuzaklar + +* **Klasör izinleri** – Program kısıtlı bir hesap altında çalışıyorsa, hedef klasörün yazılabilir olduğundan emin olun. +* **Farklı boyutlar** – Daha uzun bir barkod oluşturmak için `barHeightPixels` değerini artırın. Daha ince çözünürlük için `xDimensionPixels` değerini düşürün, ancak render hatalarını önlemek için ≥ 2 tutun. +* **Diğer posta sembolojileri** – Aspose.BarCode ayrıca `EncodeTypes.Postnet` ve `EncodeTypes.AustralianPost` değerlerini destekler. `EncodeTypes` değerini değiştirin ve aynı boyut mantığını koruyun. +* **Görüntü formatı** – Kayıpsız kalite gerekmediğinde daha küçük dosya boyutu için `BarCodeImageFormat.Jpeg` kullanın. + +## Sonuç + +Artık C#'ta boyutları yapılandırarak, uygun sembolojiyi seçerek ve sonucu PNG olarak kaydederek **posta barkod görüntüsü oluşturma** yöntemini biliyorsunuz. Eğitimde **posta barkodu nasıl oluşturulur**, **planet barkodu nasıl oluşturulur** gösterildi ve tutarlı çıktı için **barkod boyutları nasıl ayarlanır** açıklandı. + +Sonraki adımda **barkod renklerini özelleştirme**, **insan tarafından okunabilir metin ekleme** veya görüntüleri PDF faturalarına entegre etme konularını keşfedin. Aynı desen, Aspose.BarCode tarafından desteklenen diğer tüm barkod tiplerine de uygulanabilir ve bu çözümü tam bir posta otomasyon iş akışına genişletmenizi sağlar. + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki eğitimler, bu rehberde gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalı tam çalışan kod örnekleri içerir. + +- [Barkod Nasıl Oluşturulur - Tek Boyutlu Barkod Tipleri](/barcode/english/net/one-dimensional-barcode-types/) +- [Aspose.BarCode for .NET kullanarak özel en‑boy oranı ile Aztec barkodu nasıl oluşturulur](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [Java'da barkod nasıl oluşturulur – Aspose ile Avustralya Posta Barkodu](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/turkish/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..2061ec1a0 --- /dev/null +++ b/barcode/turkish/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-08-03 +description: C#'ta barkodu nasıl kaydederiz, adım adım barkod oluşturucu örneğiyle. + Planet barkodları oluşturmayı, boyutları ayarlamayı ve PNG görüntülerini dışa aktarmayı + öğrenin. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: tr +lastmod: 2026-08-03 +og_description: C#'ta bir barkod üretici örneği kullanarak barkodu nasıl kaydederiz. + Bu öğreticide Planet barkodları nasıl oluşturulur, X‑boyutu nasıl yapılandırılır + ve PNG dosyaları nasıl dışa aktarılır gösterilmektedir. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: C#'de barkodu kaydetme – adım adım rehber +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: C#'ta barkodu nasıl kaydederim – tam barkod oluşturucu rehberi +url: /tr/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta barkod nasıl kaydedilir – tam barkod oluşturucu rehberi + +C#'ta barkod görüntülerini kaydetmek, faturalara, gönderi etiketlerine veya envanter etiketlerine posta barkodları eklemeniz gerektiğinde yaygın bir gereksinimdir. Bu rehber, bir Planet barkodu oluşturmaktan dolu çubuklar ve boş çubuklar PNG dosyalarını dışa aktarmaya kadar pratik bir **c# barcode generator** iş akışını adım adım gösterir. + +Çubuk genişliğini nasıl ayarlayacağınızı, dolu çubukları nasıl açıp kapatacağınızı ve çıktı klasörlerini güvenilir bir şekilde nasıl yöneteceğinizi öğreneceksiniz. Öğreticinin sonunda, herhangi bir .NET projesine kopyalayabileceğiniz tam işlevsel bir **barcode generator example** elde edeceksiniz. + +## Gereksinimler + +- .NET 6.0 SDK veya daha yeni (örnek .NET Core ve .NET Framework ile çalışır) +- Visual Studio 2022 veya herhangi bir C# uyumlu IDE +- **Aspose.BarCode** NuGet paketi (`EncodeTypes.Planet`'i destekleyen başka bir kütüphane de olabilir). Şu komutla kurun: + +```bash +dotnet add package Aspose.BarCode +``` + +Kütüphane, bu öğreticide kullanılan `BarcodeGenerator` sınıfını sağlar. + +## Geliştirme ortamını kurma + +Yeni bir console projesi oluşturun ve gerekli ad alanını ekleyin: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +`System.IO` ad alanı, dosyaları yazmaya çalışmadan önce çıktı klasörünün var olduğunu garantileyen `Directory.CreateDirectory` metodunu sunar. + +## C# barkod oluşturucu ile barkod görüntülerini nasıl kaydedilir + +Çözümün çekirdeği, bir **Planet barcode**'u yapılandıran ve ardından görüntüyü diske kaydeden bir dizi adımdır. Aşağıdaki bölümler süreci yönetilebilir parçalara ayırır. + +### Adım 1: Çıktı klasörünü tanımlama + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Neden?** +Yolu sabit kodlamak, klasörün bulunmadığı makinelerde `DirectoryNotFoundException` hatasına yol açabilir. `CreateDirectory` idempotenttir—klasör yoksa oluşturur, böylece kod tekrar çalıştırmalarda güvenli olur. + +### Adım 2: Planet barkod oluşturucu (dolu çubuklar) oluşturma + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Neden?** +`EncodeTypes.Planet`, kütüphaneye posta Planet barkodu üretmesini söyler; bu barkod posta hizmetleri tarafından yaygın olarak kullanılır. `"123456"` dizgesi örnek veridir; iş mantığınızın gerektirdiği herhangi bir sayısal veriyle değiştirin. + +### Adım 3: Çubuk genişliğini (X‑dimension) yapılandır ve varsayılan dolu çubukları koru + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Neden?** +X‑dimension, her bir çubuğun fiziksel genişliğini kontrol eder. `4` piksel değeri, standart 300 dpi yazıcılarda okunabilir bir barkod üretir. `FilledBars` değerini `true` (varsayılan) bırakmak, klasik katı çubuk görünümünü oluşturur. + +### Adım 4: Dolu çubuklu barkod görüntüsünü kaydet + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Neden?** +PNG olarak kaydetmek, kayıpsız görüntü kalitesini korur; bu, tarama doğruluğu için önemlidir. `Save` yöntemi görüntü dosyasını otomatik olarak oluşturur; sadece tam yolu ve istenen formatı sağlamanız yeterlidir. + +### Adım 5: Boş çubuklu versiyon için ikinci bir oluşturucu oluştur + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Yeni bir örnek oluşturmak, boş çubuklu versiyon için yapılan değişikliklerin zaten kaydedilmiş dolu çubuklu görüntüyü etkilememesini sağlar. + +### Adım 6: Aynı X‑dimension'ı korurken dolu çubukları devre dışı bırak + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Neden?** +`FilledBars = false` ayarı, barkodu sadece çubukların dış hatlarıyla çizer; bu, bazı posta standartlarının görsel doğrulama için gerektirdiği bir durumdur. + +### Adım 7: Boş çubuklu barkod görüntüsünü kaydet + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Artık iki PNG dosyanız var—biri dolu çubuklu, diğeri boş çubuklu—PDF'lerde, HTML e-postalarda veya basılı etiketlerde kullanıma hazır. + +## Tam çalıştırılabilir program + +Aşağıda `Program.cs` dosyasına kopyalayabileceğiniz tam kod bulunmaktadır. Aspose.BarCode paketi kurulu olduğu varsayıldığında, değişiklik yapmadan derlenir ve çalışır. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Beklenen çıktı + +Programı çalıştırmak, aşağıdakine benzer iki satır yazdırır: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +`Barcodes` klasörünü açtığınızda iki PNG dosyasını göreceksiniz. Her iki görüntü de herhangi bir görüntü görüntüleyicide açılabilir veya doğrudan belgelere gömülebilir. + +![how to save barcode example](barcode-example.png){: .align-center alt="barkod kaydetme örneği"} + +## Yaygın varyasyonlar ve uç durumlar + +| Senaryo | Ayarlama | +|----------|------------| +| **Farklı görüntü formatı** | `BarCodeImageFormat.Png` değerini ihtiyacınıza göre `Jpeg`, `Gif` veya `Bmp` olarak değiştirin. | +| **Özel çıktı boyutu** | Belirli bir piksel boyutu zorlamak için `filled.Parameters.Image.Width` ve `Height` değerlerini kullanın. | +| **Dinamik veri** | Statik `"123456"` değerini sipariş numaraları, takip kimlikleri vb. tutan bir değişkenle değiştirin. | +| **Mevcut olmayan klasör** | `Directory.CreateDirectory` zaten eksik dizinleri yönetir; ek kod gerekmez. | +| **Yüksek çözünürlüklü baskı** | `XDimension.Pixels` değerini 600 dpi yazıcılar için 6–8'e yükseltin, ancak tarayıcı uyumluluğunu doğrulayın. | + +**Pro ipucu:** Bir döngüde çok sayıda barkod üretmeniz gerekiyorsa, tek bir `BarcodeGenerator` örneğini yeniden kullanın ve her `Save` öncesinde sadece `CodeText` özelliğini değiştirin. Bu, nesne tahsis yükünü azaltır. + +## Diğer standartlar için barkod nasıl üretilir + +Aynı desen, `Code128`, `QR` veya `DataMatrix` gibi diğer `EncodeTypes` için de çalışır. Sadece `EncodeTypes.Planet` ifadesini istediğiniz türle değiştirin ve tür‑özel parametreleri (ör. `QRCodeVersion`) ayarlayı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 öğ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. + +- [DataMatrix C40 ile PNG Kaydetme (Aspose.BarCode kullanarak)](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Aspose.BarCode ile .NET için DataMatrix Barkodları (ECC 200) Oluşturma](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Barkod Oluşturma – Code 39 Konfigürasyonu (Aspose.BarCode ile)](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md b/barcode/vietnamese/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md new file mode 100644 index 000000000..78383a82a --- /dev/null +++ b/barcode/vietnamese/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-08-03 +description: Hướng dẫn tạo mã vạch C# cho thấy cách tạo mã vạch Planet với Aspose.BarCode, + thiết lập kích thước X và lưu dưới dạng ảnh PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- create planet barcode +language: vi +lastmod: 2026-08-03 +og_description: Hướng dẫn tạo mã vạch C# giúp bạn tạo mã vạch Planet, điều chỉnh kích + thước X và lưu dưới dạng PNG bằng Aspose.BarCode. +og_image_alt: Screenshot of generated Planet and RM4SCC barcodes in PNG format +og_title: Trình tạo mã vạch C# – tạo mã vạch Planet từng bước +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial showing how to create Planet barcode + with Aspose.BarCode, set X‑dimension, and save as PNG images. + headline: Barcode generator C# – create Planet barcode and RM4SCC example + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Trình tạo mã vạch C# – tạo ví dụ mã vạch Planet và RM4SCC +url: /vi/python-java/general/barcode-generator-c-create-planet-barcode-and-rm4scc-example/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Trình tạo mã vạch C# – tạo ví dụ mã vạch Planet và RM4SCC + +Nếu bạn cần một **barcode generator C#** có thể tạo ra các ký hiệu đặc thù cho bưu chính, hướng dẫn này sẽ chỉ cho bạn cách **tạo hình ảnh mã vạch Planet** bằng Aspose.BarCode. Bạn sẽ thấy cách cấu hình kích thước X, tạo một mã vạch RM4SCC tương ứng, và lưu cả hai dưới dạng tệp PNG—tất cả trong vài bước ngắn gọn. + +Bài học bao gồm mọi thứ bạn cần để chạy mã trên .NET 6 hoặc phiên bản mới hơn, giải thích lý do mỗi thiết lập quan trọng, và chỉ ra các lỗi thường gặp như độ rộng mô-đun không đúng hoặc thiếu quyền ghi thư mục. Khi hoàn thành, bạn sẽ có hai hình ảnh mã vạch sẵn sàng in, tuân thủ tiêu chuẩn Planet và RM4SCC. + +## Các yêu cầu trước + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +* .NET 6 SDK (hoặc bất kỳ phiên bản .NET nào được Aspose.BarCode hỗ trợ) +* Visual Studio 2022 hoặc bất kỳ IDE C# nào bạn thích +* Tham chiếu NuGet tới **Aspose.BarCode** (`Install-Package Aspose.BarCode`) +* Quyền ghi vào thư mục nơi bạn dự định lưu các tệp PNG + +Không cần dịch vụ bên ngoài nào thêm; thư viện sẽ xử lý toàn bộ việc mã hoá cục bộ. + +## Bước 1: Khởi tạo đối tượng barcode generator C# + +Nhiệm vụ đầu tiên là tạo một thể hiện của `BarcodeGenerator`. Hàm khởi tạo nhận vào loại mã vạch (`EncodeTypes.Planet`) và dữ liệu cần mã hoá. + +```csharp +using Aspose.BarCode.Generation; + +// Step 1: Create a Planet barcode generator with the data to encode +BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +*Tại sao lại cần bước này?* +`BarcodeGenerator` là điểm vào cho mọi mã vạch bạn tạo. Việc chọn `EncodeTypes.Planet` báo cho thư viện tuân theo tiêu chuẩn ISO/IEC 24723 được nhiều dịch vụ bưu chính sử dụng. + +## Bước 2: Đặt kích thước X (độ rộng mô-đun) cho mã vạch Planet + +Kích thước X xác định độ rộng của một mô-đun mã vạch duy nhất (vạch hoặc khoảng trống nhỏ nhất). Giá trị **4 pixel** thường phù hợp với hầu hết máy in nhãn. + +```csharp +// Step 2: Define the X‑dimension (module width) in pixels +planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Tại sao lại quan trọng* +Nếu mô-đun quá hẹp, mã vạch có thể không đọc được; nếu quá rộng thì kích thước nhãn sẽ tăng không cần thiết. Điều chỉnh `Pixels` cho phép bạn tinh chỉnh mã vạch cho độ phân giải máy in cụ thể của mình. + +## Bước 3: Lưu mã vạch Planet dưới dạng ảnh PNG + +Aspose.BarCode tự động tính chiều cao mã vạch dựa trên loại symbology đã chọn, vì vậy bạn chỉ cần chỉ định đường dẫn tệp và định dạng. + +```csharp +// Step 3: Save the Planet barcode as a PNG image (height is calculated automatically) +planetGenerator.Save("YOUR_DIRECTORY/PostalPlanetBarHeightNone.png", BarCodeImageFormat.Png); +``` + +*Mẹo* +Thay `YOUR_DIRECTORY` bằng đường dẫn tuyệt đối hoặc tương đối tồn tại trên máy của bạn. Nếu thư mục không tồn tại, phương thức `Save` sẽ ném ra `DirectoryNotFoundException`. + +**Kết quả mong đợi** – một tệp PNG trông giống như hình minh họa dưới đây (hình ảnh thực tế không được hiển thị ở đây, nhưng bạn sẽ thấy một mã vạch Planet cổ điển với dữ liệu số `123456`). + +## Bước 4: Khởi tạo một generator thứ hai cho mã vạch RM4SCC + +Nhiều hệ thống bưu chính yêu cầu cả hai ký hiệu Planet và RM4SCC trên cùng một bưu kiện. Tạo một thể hiện `BarcodeGenerator` mới cho symbology RM4SCC. + +```csharp +// Step 4: Create an RM4SCC barcode generator with the same data +BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); +``` + +*Tại sao lại cần một thể hiện riêng?* +Mỗi symbology có bộ tham số riêng. Việc tái sử dụng cùng một generator có thể vô tình mang các thiết lập (như X‑dimension) không tối ưu cho mã vạch thứ hai. + +## Bước 5: Cấu hình kích thước X cho mã vạch RM4SCC + +RM4SCC cũng tôn trọng thiết lập X‑dimension, vì vậy chúng ta áp dụng cùng độ rộng pixel để đồng nhất về mặt hình ảnh. + +```csharp +// Step 5: Set the X‑dimension for the RM4SCC barcode +rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; +``` + +*Pro tip* +Nếu bạn cần một mã vạch cao hơn (ví dụ, cho nhãn lớn), bạn cũng có thể đặt `Height.Pixels`. Để trống nó sẽ để thư viện tự tính chiều cao lý tưởng. + +## Bước 6: Lưu mã vạch RM4SCC dưới dạng ảnh PNG + +Cuối cùng, ghi mã vạch RM4SCC ra đĩa. + +```csharp +// Step 6: Save the RM4SCC barcode as a PNG image (height is calculated automatically) +rm4sccGenerator.Save("YOUR_DIRECTORY/PostalRM4SCCBarHeightNone.png", BarCodeImageFormat.Png); +``` + +Bây giờ bạn có hai tệp PNG—`PostalPlanetBarHeightNone.png` và `PostalRM4SCCBarHeightNone.png`—có thể nhúng vào nhãn thư, in lên phong bì, hoặc gửi tới dịch vụ in bên thứ ba. + +## Tùy chọn: Điều chỉnh chiều cao hoặc sử dụng các định dạng ảnh khác + +Nếu quy trình của bạn yêu cầu chiều cao mã vạch cụ thể hoặc định dạng ảnh khác (ví dụ, JPEG hoặc BMP), bạn có thể sửa đổi các tham số trước khi gọi `Save`: + +```csharp +// Example: set a fixed height of 100 pixels and save as JPEG +planetGenerator.Parameters.Barcode.Height.Pixels = 100; +planetGenerator.Save("PostalPlanet.jpg", BarCodeImageFormat.Jpeg); +``` + +**Trường hợp đặc biệt** – Khi bạn đặt chiều cao tùy chỉnh, hãy chắc chắn giá trị đó đáp ứng chiều cao tối thiểu yêu cầu bởi tiêu chuẩn ISO; nếu không, mã vạch có thể không vượt qua kiểm tra hợp lệ. + +## Các lỗi thường gặp và cách tránh + +| Lỗi | Nguyên nhân | Cách khắc phục | +|-----|-------------|----------------| +| `DirectoryNotFoundException` | Thư mục đích không tồn tại hoặc viết sai tên. | Tạo thư mục trước hoặc dùng `Path.Combine` với `Environment.CurrentDirectory`. | +| Mã vạch không đọc được trên máy in độ phân giải thấp | X‑dimension quá nhỏ so với DPI của máy in. | Tăng `XDimension.Pixels` lên 5 – 6 cho máy in 203 dpi, hoặc thử nghiệm với mẫu nhãn. | +| Đặt symbology sai | Truyền `EncodeTypes.Code128` thay vì `EncodeTypes.Planet`. | Kiểm tra lại giá trị enum `EncodeTypes` để chắc chắn khớp với tiêu chuẩn bưu chính yêu cầu. | +| Tham chiếu `Parameters` null | Sử dụng phiên bản cũ của Aspose.BarCode có API khác. | Nâng cấp lên gói NuGet mới nhất (v23.12 trở lên). | + +## Ví dụ đầy đủ có thể chạy + +Dưới đây là chương trình hoàn chỉnh bạn có thể sao chép, dán và chạy. Nó bao gồm các câu lệnh `using`, xử lý lỗi, và chú thích giải thích từng dòng. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Define the output directory (change as needed) + string outputDir = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputDir); + + // -------- Planet barcode ---------- + var planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string planetPath = Path.Combine(outputDir, "PostalPlanetBarHeightNone.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + Console.WriteLine($"Planet barcode saved to: {planetPath}"); + + // -------- RM4SCC barcode ---------- + var rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = 4; + string rm4sccPath = Path.Combine(outputDir, "PostalRM4SCCBarHeightNone.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + Console.WriteLine($"RM4SCC barcode saved to: {rm4sccPath}"); + } +} +``` + +Chạy chương trình sẽ tạo một thư mục `Barcodes` bên cạnh file thực thi và đặt hai tệp PNG vào đó. Mở chúng bằng bất kỳ trình xem ảnh nào để xác nhận kết quả. + +## Kết luận + +Bạn đã có một giải pháp **barcode generator C#** có thể **tạo hình ảnh mã vạch Planet**, điều chỉnh X‑dimension để in tối ưu, và tạo ra mã vạch RM4SCC tương ứng—tất cả chỉ với vài dòng mã. Cách tiếp cận này hoạt động với .NET 6+, chỉ cần gói NuGet Aspose.BarCode, và có thể mở rộng sang các symbology khác như Code128, QR, hoặc DataMatrix bằng cách thay đổi giá trị `EncodeTypes`. + +### Bước tiếp theo là gì? + +* Thử nghiệm các giá trị `XDimension.Pixels` khác nhau để phù hợp với DPI máy in của bạn. +* Tạo mã vạch ở các định dạng khác (PDF, SVG) bằng cách thay đổi enum `BarCodeImageFormat`. +* Kết hợp hai tệp PNG thành một nhãn duy nhất bằng thư viện đồ họa như **SkiaSharp**. +* Khám phá toàn bộ API Aspose.BarCode để sử dụng các tính năng nâng cao như kiểm tra checksum hoặc phông chữ tùy chỉnh. + +Bạn có thể tùy chỉnh mã cho xử lý hàng loạt hoặc tích hợp vào dịch vụ web ASP.NET Core trả về hình ảnh mã vạch theo yêu cầu. 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 liên quan chặt chẽ đến các kỹ thuật đã trình bày trong bài viết này. Mỗi tài nguyên đều bao gồm mã mẫu đầy đủ và 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. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to Save PNG using DataMatrix C40 with Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [barcode generator tutorial c# – Customize Code 16K Barcode Aspect Ratios with Aspose.BarCode for .NET](/barcode/english/net/code-16k-encoding/code-16k-aspect-ratio-customization/) + +{{< /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-c-generate-barcode-image/_index.md b/barcode/vietnamese/python-java/general/barcode-generator-c-generate-barcode-image/_index.md new file mode 100644 index 000000000..764e12e5b --- /dev/null +++ b/barcode/vietnamese/python-java/general/barcode-generator-c-generate-barcode-image/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-08-03 +description: Hướng dẫn tạo mã vạch C# cho thấy cách tạo hình ảnh mã vạch bằng Aspose.BarCode, + thiết lập cột và hàng, và lưu các tệp PNG cho DataBar Expanded Stacked. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator c# +- generate barcode image +language: vi +lastmod: 2026-08-03 +og_description: Hướng dẫn tạo mã vạch C# giải thích cách tạo hình ảnh mã vạch bằng + Aspose.BarCode, cấu hình các cột và hàng của DataBar Expanded Stacked, và lưu các + tệp PNG. +og_image_alt: Screenshot of a DataBar Expanded Stacked barcode generated with C# +og_title: Trình tạo mã vạch C# – hướng dẫn từng bước để tạo hình ảnh mã vạch +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator C# tutorial shows how to generate barcode image with + Aspose.BarCode, set columns and rows, and save PNG files for DataBar Expanded + Stacked. + headline: Barcode generator C# – generate barcode image + type: TechArticle +tags: +- barcode +- C# +- Aspose.BarCode +title: Trình tạo mã vạch C# – tạo hình ảnh mã vạch +url: /vi/python-java/general/barcode-generator-c-generate-barcode-image/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Trình tạo mã vạch C# – tạo hình ảnh mã vạch + +Nếu bạn cần một trình tạo mã vạch C# có thể tạo hình ảnh mã vạch cho DataBar Expanded Stacked, hướng dẫn này sẽ đưa bạn qua toàn bộ quá trình. Bạn sẽ học cách cấu hình cài đặt cột và hàng, lưu kết quả dưới dạng PNG, và điều chỉnh mã cho các loại mã vạch khác. + +Tạo hình ảnh mã vạch một cách lập trình loại bỏ các bước thủ công và đảm bảo tính nhất quán trên các hoá đơn, nhãn vận chuyển và hệ thống tồn kho. Bài hướng dẫn này bao gồm mọi thứ bạn cần, từ thiết lập dự án đến mã nguồn đầy đủ, để bạn có thể chạy ví dụ ngay lập tức. + +## Yêu cầu trước + +* .NET 6.0 hoặc mới hơn đã được cài đặt +* Một IDE như Visual Studio 2022 (bất kỳ trình chỉnh sửa nào hỗ trợ C# đều hoạt động) +* Một giấy phép cho **Aspose.BarCode for .NET** – phiên bản dùng thử miễn phí hoạt động cho việc kiểm tra +* Hiểu biết cơ bản về cú pháp C# + +Nếu bất kỳ mục nào trong số này còn thiếu, hãy cài đặt .NET SDK từ dotnet.microsoft.com và lấy gói Aspose.BarCode NuGet bằng: + +```bash +dotnet add package Aspose.BarCode +``` + +## Bước 1: Tạo dự án trình tạo mã vạch C# project + +Tạo một ứng dụng console mới và thêm các chỉ thị `using` cần thiết: + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // The implementation starts in the next sections + } + } +} +``` + +Lớp `BarcodeGenerator` là lõi của API trình tạo mã vạch C#. Nó nhận loại symbology và văn bản cần mã hoá. + +## Bước 2: Tạo mã vạch DataBar Expanded Stacked và đặt số cột + +Ví dụ đầu tiên tạo một mã vạch với bốn cột. Điều chỉnh thuộc tính `Columns` sẽ thay đổi mật độ hiển thị của symbology DataBar Expanded Stacked. + +```csharp +// Step 2: Create a barcode generator for DataBar Expanded Stacked +BarcodeGenerator barcodeGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of columns to 4 +barcodeGenerator.Parameters.Barcode.DataBar.Columns = 4; + +// Save the barcode image as PNG +string colsPath = @"YOUR_DIRECTORY\DatabarCols4.png"; +barcodeGenerator.Save(colsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 4 columns saved to {colsPath}"); +``` + +**Tại sao điều này quan trọng:** Số cột ảnh hưởng đến lượng dữ liệu có thể lưu trữ trong không gian nhỏ gọn. Đặt giá trị thành 4 sẽ tạo ra một mã vạch rộng hơn nhưng vẫn có thể đọc được bởi hầu hết các máy quét. + +## Bước 3: Tạo mã vạch với số hàng tùy chỉnh + +Ví dụ thứ hai cho thấy cách kiểm soát bố cục dọc bằng cách đặt thuộc tính `Rows`. Cấu hình ba hàng hữu ích khi bạn cần một mã vạch cao hơn cho không gian ngang hạn chế. + +```csharp +// Step 3: Create a second barcode generator for the same type +BarcodeGenerator barcodeGeneratorRows = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + +// Set the number of rows to 3 +barcodeGeneratorRows.Parameters.Barcode.DataBar.Rows = 3; + +// Save the barcode image as PNG +string rowsPath = @"YOUR_DIRECTORY\DatabarRows3.png"; +barcodeGeneratorRows.Save(rowsPath, BarCodeImageFormat.Png); + +Console.WriteLine($"Barcode with 3 rows saved to {rowsPath}"); +``` + +**Tại sao điều này quan trọng:** Điều chỉnh số hàng cho phép bạn đặt mã vạch vào một cột hẹp trong khi vẫn duy trì khả năng đọc. Trình tạo mã vạch C# tự động tính lại kích thước module để đáp ứng tiêu chuẩn. + +## Bước 4: Ví dụ đầy đủ, có thể chạy + +Dưới đây là một chương trình tự chứa kết hợp các bước trước. Sao chép mã vào `Program.cs`, thay thế `YOUR_DIRECTORY` bằng đường dẫn thư mục hiện có, và chạy ứng dụng. + +```csharp +using System; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // ---------- Generate barcode with 4 columns ---------- + BarcodeGenerator colsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + colsGenerator.Parameters.Barcode.DataBar.Columns = 4; + + string colsFile = @"YOUR_DIRECTORY\DatabarCols4.png"; + colsGenerator.Save(colsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with columns saved to {colsFile}"); + + // ---------- Generate barcode with 3 rows ---------- + BarcodeGenerator rowsGenerator = new BarcodeGenerator( + EncodeTypes.DatabarExpandedStacked, "Databar Expanded Stacked long"); + + rowsGenerator.Parameters.Barcode.DataBar.Rows = 3; + + string rowsFile = @"YOUR_DIRECTORY\DatabarRows3.png"; + rowsGenerator.Save(rowsFile, BarCodeImageFormat.Png); + Console.WriteLine($"Generated barcode image with rows saved to {rowsFile}"); + } + } +} +``` + +### Kết quả mong đợi + +Khi bạn chạy chương trình, hai tệp PNG sẽ xuất hiện trong thư mục đích: + +* **DatabarCols4.png** – một mã vạch DataBar Expanded Stacked với bốn cột +* **DatabarRows3.png** – cùng dữ liệu được mã hoá trong ba hàng + +Mở các hình ảnh bằng bất kỳ trình xem ảnh nào; chúng hiển thị mã vạch sắc nét, có thể quét được, sẵn sàng để in hoặc nhúng vào PDF. + +## Cách tạo hình ảnh mã vạch với kích thước tùy chỉnh + +Nếu bạn cần kích thước ảnh cụ thể, hãy điều chỉnh các thuộc tính `ImageHeight` và `ImageWidth` trước khi gọi `Save`: + +```csharp +colsGenerator.Parameters.ImageHeight = 150; // pixels +colsGenerator.Parameters.ImageWidth = 300; // pixels +colsGenerator.Save(colsFile, BarCodeImageFormat.Png); +``` + +Thay đổi kích thước không ảnh hưởng đến dữ liệu đã mã hoá; nó chỉ thay đổi tỉ lệ hiển thị. Kỹ thuật này hữu ích khi tích hợp mã vạch vào các thành phần UI có ràng buộc bố cục cố định. + +## Những lỗi thường gặp và mẹo chuyên nghiệp + +* **Path separators:** Sử dụng chuỗi nguyên (`@"C:\Path\file.png"`) hoặc `Path.Combine` để tránh các vấn đề ký tự escape trên Windows. +* **License enforcement:** Nếu không có giấy phép hợp lệ, các hình ảnh được tạo sẽ chứa watermark. Áp dụng giấy phép của bạn sớm trong ứng dụng: + + ```csharp + Aspose.BarCode.License license = new Aspose.BarCode.License(); + license.SetLicense("Aspose.BarCode.lic"); + ``` + +* **Encoding limits:** DataBar Expanded Stacked hỗ trợ tối đa 74 ký tự số. Vượt quá giới hạn này sẽ gây ra ngoại lệ. Kiểm tra độ dài đầu vào trước khi tạo trình tạo. +* **Performance:** Tái sử dụng một thể hiện `BarcodeGenerator` duy nhất cho nhiều lần lưu giảm việc cấp phát bộ nhớ. Chỉ thay đổi các thuộc tính `Rows` hoặc `Columns` giữa các lần lưu nếu văn bản đã mã hoá vẫn giữ nguyên. + +## Các bước tiếp theo + +Bây giờ bạn đã có thể tạo hình ảnh mã vạch với trình tạo mã vạch C#, hãy cân nhắc khám phá: + +* **Different symbologies** – thử `EncodeTypes.QR`, `EncodeTypes.Code128`, hoặc `EncodeTypes.Pdf417`. +* **Color customization** – đặt `Parameters.Barcode.ForeColor` và `BackColor` để phù hợp với thương hiệu. +* **Embedding in PDFs** – kết hợp PNG đã tạo với Aspose.PDF để tạo tài liệu có thể in. + +Các phần mở rộng này cho phép bạn xây dựng một giải pháp mã vạch đầy đủ tính năng cho các ứng dụng quản lý tồn kho, logistics hoặc bán lẻ. + +--- + +## 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 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ã đầy đủ hoạt động cùng 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 mã vạch DataMatrix (ECC 200) với Aspose.BarCode cho .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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/barcode-generator-example-in-c-set-width-and-height/_index.md b/barcode/vietnamese/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md new file mode 100644 index 000000000..774526f0b --- /dev/null +++ b/barcode/vietnamese/python-java/general/barcode-generator-example-in-c-set-width-and-height/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-08-03 +description: Ví dụ trình tạo mã vạch bằng C# cho thấy cách đặt chiều rộng, cách thay + đổi chiều cao và cách tạo hình ảnh mã vạch. Thực hiện theo các hướng dẫn từng bước. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- barcode generator example +- how to change height +- how to set width +- how to generate barcode +- create barcode image c# +language: vi +lastmod: 2026-08-03 +og_description: Ví dụ về trình tạo mã vạch minh họa việc thiết lập độ rộng X‑dimension, + thay đổi chiều cao thanh và tạo hình ảnh mã vạch bằng C#. Thực hiện các bước để + tạo các tệp PNG. +og_image_alt: Two PNG barcode images with different heights generated by C# code +og_title: Ví dụ tạo mã vạch – Hướng dẫn chiều rộng và chiều cao trong C# +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Barcode generator example in C# showing how to set width, how to change + height, and how to generate barcode image. Follow step‑by‑step instructions. + headline: Barcode generator example in C# – set width and height + type: TechArticle +tags: +- barcode +- C# +- image generation +title: Ví dụ tạo mã vạch bằng C# – thiết lập chiều rộng và chiều cao +url: /vi/python-java/general/barcode-generator-example-in-c-set-width-and-height/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ví dụ tạo mã vạch bằng C# – đặt chiều rộng và chiều cao + +Nếu bạn cần một **ví dụ tạo mã vạch** bằng C#, hướng dẫn này sẽ chỉ cho bạn cách đặt chiều rộng X‑dimension, cách thay đổi chiều cao thanh, và cách tạo tệp hình ảnh mã vạch. Bạn sẽ thấy một chương trình hoàn chỉnh, có thể chạy được, tạo ra hai tệp PNG với các chiều cao khác nhau. + +Một kịch bản phổ biến là tạo nhãn sản phẩm trong đó kích thước mã vạch phải đáp ứng các yêu cầu của máy quét. Khi kết thúc bài học này, bạn sẽ có thể điều chỉnh các tham số chiều rộng và chiều cao bằng mã và lưu kết quả dưới dạng hình ảnh PNG. + +## Điều kiện tiên quyết + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +* .NET 6 (hoặc mới hơn) đã được cài đặt – mã này nhắm tới .NET 6 SDK. +* Thư viện mã vạch hỗ trợ `EncodeTypes.DatabarOmniDirectional`. Ví dụ sử dụng **Aspose.BarCode for .NET**, nhưng bất kỳ thư viện nào cung cấp các thuộc tính tương tự cũng hoạt động như nhau. +* Một IDE hoặc trình soạn thảo (Visual Studio, VS Code, Rider) để biên dịch và chạy chương trình. +* Quyền ghi vào thư mục sẽ lưu các tệp PNG. + +> **Mẹo chuyên nghiệp:** Tạo một thư mục có tên `Barcodes` trong thư mục gốc dự án và tham chiếu nó bằng `Path.Combine` để tránh việc mã cứng đường dẫn tuyệt đối. + +## Ví dụ tạo mã vạch: khởi tạo và cấu hình + +Bước đầu tiên là tạo một thể hiện `BarcodeGenerator` với loại symbology và chuỗi dữ liệu mong muốn. + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + // Step 1: Initialize a Databar Omni‑directional barcode generator with the data string + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); +``` + +Enum `EncodeTypes.DatabarOmniDirectional` chọn symbology Databar Omni‑directional, và chuỗi dữ liệu định dạng GS1 `(01)12345678901231` đại diện cho một giá trị GTIN‑14 điển hình. Khởi tạo generator một lần cho phép bạn tái sử dụng cùng một đối tượng cho nhiều hình ảnh. + +## Cách đặt chiều rộng (X‑dimension) + +X‑dimension kiểm soát độ rộng mô-đun của mã vạch. Đặt nó thành 2 pixel sẽ làm cho mỗi thanh hẹp rộng 2 pixel, đây là yêu cầu phổ biến cho việc in mật độ cao. + +```csharp + // Step 2: Set the X‑dimension (module width) to 2 pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +Tại sao lại quan trọng: Nếu chiều rộng quá nhỏ, máy quét có thể không phân biệt được các thanh riêng lẻ; nếu quá lớn, mã vạch có thể vượt quá không gian nhãn. Điều chỉnh giá trị pixel sao cho phù hợp với DPI của máy in và kích thước nhãn mục tiêu. + +## Cách thay đổi chiều cao + +Chiều cao thanh quyết định độ cao của các thanh. Ví dụ tạo hai hình ảnh: một với chiều cao 30 pixel và một với chiều cao 60 pixel. + +```csharp + // Step 3: Configure a 30‑pixel bar height and save the image + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + // Step 4: Change the bar height to 60 pixels and save a second image + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + // Helper method to encapsulate saving logic + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + // Ensure the output directory exists + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + + // Save as PNG + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Thuộc tính `BarHeight.Pixels` ảnh hưởng trực tiếp đến chiều cao hiển thị của các thanh. Thay đổi nó giữa các lần lưu cho phép bạn tạo nhiều biến thể từ cùng một payload dữ liệu mà không cần tạo lại generator. + +### Kết quả mong đợi + +Chạy chương trình sẽ tạo ra hai tệp PNG trong thư mục `Barcodes`: + +* `DatabarBarHeight30Pixels.png` – các thanh cao 30 pixel. +* `DatabarBarHeight60Pixels.png` – các thanh cao 60 pixel. + +Cả hai hình ảnh đều có cùng chiều rộng (được xác định bởi X‑dimension) và mã hoá cùng một dữ liệu GTIN‑14. + +![Hai tệp PNG mã vạch với các chiều cao khác nhau được tạo bằng mã C#](barcode-example.png "Ví dụ tạo mã vạch thể hiện các biến thể chiều cao") + +*Văn bản thay thế hình ảnh ở trên chứa từ khóa chính để hỗ trợ truy cập và SEO.* + +## Cách tạo hình ảnh mã vạch trong C# + +Phương thức `Save` xử lý việc chuyển đổi dữ liệu mã vạch thành tệp hình ảnh. Bạn có thể chọn các định dạng khác (JPEG, BMP, SVG) bằng cách truyền một giá trị enum `BarCodeImageFormat` khác. Ví dụ này sử dụng PNG vì nó giữ nguyên chất lượng không mất dữ liệu và được hỗ trợ rộng rãi. + +Nếu bạn cần nhúng mã vạch trực tiếp vào PDF hoặc trang web, hãy lấy hình ảnh dưới dạng `byte[]`: + +```csharp +byte[] pngBytes = generator.GenerateBarCodeImage(BarCodeImageFormat.Png); +// Use pngBytes with a web API, store in a database, or embed in a PDF. +``` + +Cách tiếp cận này loại bỏ nhu cầu tạo tệp tạm thời và hữu ích cho các dịch vụ có lưu lượng cao. + +## Các biến thể phổ biến và trường hợp đặc biệt + +| Tình huống | Điều chỉnh | +|-----------|------------| +| **Symbology khác** | Thay `EncodeTypes.DatabarOmniDirectional` bằng một giá trị enum khác (ví dụ, `EncodeTypes.Code128`). | +| **Nhãn rất nhỏ** | Giảm `XDimension.Pixels` xuống 1 pixel, nhưng cần kiểm tra khả năng đọc của máy quét. | +| **In độ phân giải cao** | Tăng cả X‑dimension và chiều cao thanh một cách tỷ lệ (ví dụ, 4 px chiều rộng, 80 px chiều cao). | +| **Dữ liệu động** | Truyền chuỗi dữ liệu tại thời gian chạy, có thể lấy từ bản ghi cơ sở dữ liệu. | +| **Tạo hàng loạt** | Lặp qua một tập hợp các chuỗi dữ liệu, tái sử dụng cùng một thể hiện `BarcodeGenerator` đồng thời cập nhật `generator.Text`. | + +Khi gặp ngoại lệ như `ArgumentOutOfRangeException`, hãy kiểm tra lại rằng các giá trị pixel là số nguyên dương và thư mục đầu ra tồn tại. + +## Tổng hợp mã nguồn đầy đủ + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +class Program +{ + static void Main() + { + var generator = new BarcodeGenerator( + EncodeTypes.DatabarOmniDirectional, + "(01)12345678901231"); + + generator.Parameters.Barcode.XDimension.Pixels = 2; + + generator.Parameters.Barcode.BarHeight.Pixels = 30; + SaveBarcode(generator, "DatabarBarHeight30Pixels.png"); + + generator.Parameters.Barcode.BarHeight.Pixels = 60; + SaveBarcode(generator, "DatabarBarHeight60Pixels.png"); + } + + private static void SaveBarcode(BarcodeGenerator generator, string fileName) + { + string outputPath = Path.Combine( + Directory.GetCurrentDirectory(), + "Barcodes", + fileName); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + generator.Save(outputPath, BarCodeImageFormat.Png); + Console.WriteLine($"Saved barcode to {outputPath}"); + } +} +``` + +Sao chép mã vào một dự án console mới, khôi phục gói NuGet Aspose.BarCode (`dotnet add package Aspose.BarCode`), và chạy `dotnet run`. Bạn sẽ thấy các thông báo console xác nhận các tệp đã được lưu. + +## Kết luận + +**Ví dụ tạo mã vạch** này minh họa cách đặt chiều rộng, cách thay đổi chiều cao, và cách tạo hình ảnh mã vạch trong C#. Bằng cách điều chỉnh `XDimension.Pixels` và `BarHeight.Pixels` bạn kiểm soát kích thước hiển thị của mã vạch, và phương thức `Save` ghi kết quả ra các tệp PNG. Hãy thử nghiệm với các symbology, định dạng đầu ra và chuỗi dữ liệu khác nhau để đáp ứng yêu cầu của ứng dụng của bạn. + +**Bước tiếp theo** + +* Khám phá **cách tạo mã vạch** ở các định dạng hình ảnh khác (SVG, JPEG) cho việc sử dụng trên web. +* Học **tạo hình ảnh mã vạch c#** cho các endpoint ASP.NET Core trả về PNG trực tiếp cho trình duyệt. +* Kết hợp đoạn mã này với thư viện tạo PDF để nhúng mã vạch vào hoá đơn hoặc nhãn vận chuyển. + +Bạn có thể tùy chỉnh mẫu, chia sẻ kết quả, hoặc đặt câu hỏi trong phần bình luận. 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 đượ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 chi tiết 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. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to Set Border for ITF-14 Barcode Customization](/barcode/english/net/itf-14-barcode-customization/) +- [How to Generate DataMatrix Barcodes (ECC 200) with Aspose.BarCode for .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-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-barcode-png-in-c-step-by-step-guide/_index.md b/barcode/vietnamese/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..44087cea1 --- /dev/null +++ b/barcode/vietnamese/python-java/general/create-barcode-png-in-c-step-by-step-guide/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-08-03 +description: Tạo mã vạch PNG trong C# và tìm hiểu cách thay đổi tỷ lệ khung hình cho + hình ảnh DataBar. Theo dõi ví dụ đầy đủ này kèm mã và mẹo. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode PNG +- how to change aspect ratio +- Aspose.BarCode C# +- DataBar stacked omnidirectional +- barcode image format PNG +language: vi +lastmod: 2026-08-03 +og_description: Tạo mã vạch PNG bằng C# và xem cách thay đổi tỷ lệ khung hình cho + các mã vạch DataBar. Hướng dẫn này cung cấp cho bạn mã sẵn sàng chạy và các mẹo + thực tế. +og_image_alt: Sample barcode PNG generated with aspect ratio 15 +og_title: Tạo mã vạch PNG trong C# – ví dụ đầy đủ với kiểm soát tỷ lệ khung hình +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + headline: Create barcode PNG in C# – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG in C# and learn how to change aspect ratio for DataBar + images. Follow this complete example with code and tips. + name: Create barcode PNG in C# – step‑by‑step guide + steps: + - name: How to change other visual properties? + text: 'You can adjust foreground color, background color, or add human‑readable + text through the `generator.Parameters.Barcode` object. For example:' + - name: What if I need a different image format? + text: Replace `BarCodeImageFormat.Png` with `Jpeg`, `Bmp`, or `Gif` as needed. + PNG remains the best choice for lossless barcode images. + - name: Does the aspect ratio affect scanning speed? + text: Higher aspect ratios increase the barcode’s height, which can improve scan + reliability on devices that struggle with short stacked symbols. However, extremely + tall barcodes may not fit on small labels, so test with your target hardware. + - name: Can I generate multiple barcodes in a loop? + text: Yes. Create a new `BarcodeGenerator` instance for each data string or reuse + the same instance while updating `CodeText` and `DataBar.AspectRatio`. This + approach reduces object allocation overhead. + type: HowTo +tags: +- barcode +- C# +- PNG +- Aspose +title: Tạo mã vạch PNG trong C# – hướng dẫn từng bước +url: /vi/python-java/general/create-barcode-png-in-c-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo file PNG mã vạch trong C# – hướng dẫn chi tiết + +Nếu bạn cần **tạo file PNG mã vạch** trong C#, hướng dẫn này sẽ chỉ cho bạn cách thực hiện. Bạn sẽ tạo một mã DataBar đa hướng xếp chồng, lưu nó dưới dạng file PNG, và học **cách thay đổi tỷ lệ khung hình** để phù hợp với các môi trường quét khác nhau. + +Hướng dẫn bao gồm mọi thứ bạn cần: các gói cần thiết, một chương trình hoàn chỉnh, có thể chạy ngay, và giải thích lý do mỗi thiết lập quan trọng. Khi hoàn thành, bạn sẽ có hai file PNG—một với tỷ lệ khung hình 15 và một với 30—sẵn sàng để thử nghiệm hoặc sử dụng trong môi trường sản xuất. + +## Các điều kiện tiên quyết + +Trước khi bắt đầu, hãy đảm bảo bạn có: + +- .NET 6.0 SDK hoặc phiên bản mới hơn +- Visual Studio 2022 (hoặc bất kỳ IDE C# nào) +- Tham chiếu NuGet tới **Aspose.BarCode** (thư viện cung cấp `BarcodeGenerator`) +- Quyền ghi vào thư mục sẽ lưu các file PNG + +Bạn có thể thêm gói Aspose.BarCode bằng lệnh sau: + +```bash +dotnet add package Aspose.BarCode +``` + +## Bước 1: Thiết lập dự án và nhập không gian tên + +Tạo một ứng dụng console mới và nhập các không gian tên cần thiết cho việc tạo mã vạch và I/O file. + +```csharp +using System; +using Aspose.BarCode.Generation; +using Aspose.BarCode; + +namespace BarcodePngDemo +{ + class Program + { + static void Main() + { + // All subsequent steps are inside Main +``` + +**Tại sao lại quan trọng:** Nhập `Aspose.BarCode.Generation` cho phép bạn truy cập `BarcodeGenerator`. Giữ mã trong `Main` giúp ví dụ tự chứa và dễ chạy. + +## Bước 2: Tạo trình tạo mã vạch cho DataBar đa hướng xếp chồng + +Khởi tạo `BarcodeGenerator` với kiểu `EncodeTypes.DatabarStackedOmniDirectional` và một chuỗi dữ liệu mẫu GS1‑128. + +```csharp + // Step 2: Create a barcode generator for a stacked omnidirectional DataBar + BarcodeGenerator generator = new BarcodeGenerator( + EncodeTypes.DatabarStackedOmniDirectional, + "(01)12345678901231"); +``` + +**Tại sao lại quan trọng:** Kiểu mã đã chọn tạo ra một DataBar mật độ cao, có thể được đọc bởi hầu hết các máy quét hiện đại. Chuỗi dữ liệu tuân theo định dạng GS1 Application Identifier (01), thường dùng cho các mã sản phẩm. + +## Bước 3: Định nghĩa kích thước X (độ rộng mô-đun) bằng pixel + +Đặt độ rộng mô-đun để kiểm soát kích thước tổng thể của mã vạch mà không ảnh hưởng đến khả năng đọc. + +```csharp + // Step 3: Define the X‑dimension (module width) in pixels + generator.Parameters.Barcode.XDimension.Pixels = 2; +``` + +**Tại sao lại quan trọng:** Kích thước X = 2 pixel tạo ra một mã vạch vừa đủ lớn để máy quét nhận dạng, vừa không quá lớn so với không gian nhãn thường. + +## Bước 4: Lưu PNG đầu tiên với tỷ lệ khung hình 15 + +Điều chỉnh tỷ lệ khung hình của DataBar, sau đó lưu ảnh dưới dạng file PNG. + +```csharp + // Step 4: Set the DataBar aspect ratio to 15 and save the image + generator.Parameters.Barcode.DataBar.AspectRatio = 15; + string outputPath15 = @"YOUR_DIRECTORY\DatabarAspectRatio15.png"; + generator.Save(outputPath15, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath15} (aspect ratio 15)."); +``` + +**Tại sao lại quan trọng:** Tỷ lệ khung hình kiểm soát mối quan hệ chiều cao‑so‑với‑chiều rộng của DataBar xếp chồng. Giá trị 15 là mặc định phổ biến, cân bằng giữa khả năng đọc và chiều cao nhãn. + +## Bước 5: Thay đổi tỷ lệ khung hình thành 30 và lưu PNG thứ hai + +Sửa đổi cùng một đối tượng `generator` để sử dụng tỷ lệ khung hình lớn hơn, rồi lưu ảnh thứ hai. + +```csharp + // Step 5: Change the aspect ratio to 30 and save another image + generator.Parameters.Barcode.DataBar.AspectRatio = 30; + string outputPath30 = @"YOUR_DIRECTORY\DatabarAspectRatio30.png"; + generator.Save(outputPath30, BarCodeImageFormat.Png); + Console.WriteLine($"Barcode saved to {outputPath30} (aspect ratio 30)."); + } + } +} +``` + +**Tại sao lại quan trọng:** Tăng tỷ lệ khung hình kéo dài mã vạch theo chiều dọc, có thể cải thiện độ tin cậy khi quét trên các thiết bị độ phân giải thấp hoặc khi nhãn được in trên vật liệu hẹp. + +## Kết quả mong đợi + +Chạy chương trình sẽ tạo ra hai file PNG: + +| Tệp | Tỷ lệ khung hình | Kích thước xấp xỉ (pixel) | +|-------------------------------------|------------------|---------------------------| +| `DatabarAspectRatio15.png` | 15 | 200 × 300 (rộng × cao) | +| `DatabarAspectRatio30.png` | 30 | 200 × 600 (rộng × cao) | + +Cả hai ảnh đều chứa một mã DataBar rõ ràng, có thể quét được, mã hoá định danh GS1 `(01)12345678901231`. + +## Câu hỏi thường gặp và các trường hợp đặc biệt + +### Làm sao thay đổi các thuộc tính hiển thị khác? + +Bạn có thể điều chỉnh màu nền, màu nền phụ, hoặc thêm văn bản có thể đọc được qua đối tượng `generator.Parameters.Barcode`. Ví dụ: + +```csharp +generator.Parameters.Barcode.ForeColor = System.Drawing.Color.Black; +generator.Parameters.Barcode.BackColor = System.Drawing.Color.White; +generator.Parameters.Barcode.CodeTextParameters.ShowCodeText = true; +``` + +### Nếu tôi muốn dùng định dạng ảnh khác thì sao? + +Thay `BarCodeImageFormat.Png` bằng `Jpeg`, `Bmp`, hoặc `Gif` tùy nhu cầu. PNG vẫn là lựa chọn tốt nhất cho ảnh mã vạch không mất dữ liệu. + +### Tỷ lệ khung hình có ảnh hưởng đến tốc độ quét không? + +Tỷ lệ khung hình cao hơn làm tăng chiều cao của mã vạch, có thể cải thiện độ tin cậy khi quét trên các thiết bị gặp khó khăn với các ký hiệu xếp chồng ngắn. Tuy nhiên, mã vạch quá cao có thể không vừa trên các nhãn nhỏ, vì vậy hãy thử nghiệm với phần cứng mục tiêu của bạn. + +### Tôi có thể tạo nhiều mã vạch trong một vòng lặp không? + +Có. Tạo một đối tượng `BarcodeGenerator` mới cho mỗi chuỗi dữ liệu hoặc tái sử dụng cùng một đối tượng bằng cách cập nhật `CodeText` và `DataBar.AspectRatio`. Cách này giảm tải việc cấp phát đối tượng. + +## Mẹo chuyên nghiệp + +- **Tái sử dụng trình tạo**: Chỉ thay đổi `CodeText` hoặc `AspectRatio` mà không tạo lại đối tượng, giúp tăng tốc xử lý hàng loạt. +- **Xác thực đầu ra**: Dùng máy quét cầm tay hoặc ứng dụng di động để kiểm tra PNG tạo ra đọc đúng trước khi đưa vào sản xuất. +- **Đặt tên file**: Bao gồm tỷ lệ khung hình trong tên file (như ví dụ) để dễ theo dõi các biến thể trong quá trình thử nghiệm. + +## Kết luận + +Bây giờ bạn đã biết cách **tạo file PNG mã vạch** trong C# và **thay đổi tỷ lệ khung hình** cho các ký hiệu DataBar đa hướng xếp chồng. Ví dụ hoàn chỉnh minh họa việc khởi tạo, thiết lập kích thước X, điều chỉnh tỷ lệ khung hình và lưu ảnh—tất cả trong một chương trình có thể chạy ngay. + +Từ đây, bạn có thể khám phá thêm các loại mã vạch khác, thử nghiệm màu sắc, hoặc tích hợp trình tạo vào hệ thống báo cáo hay quản lý tồn kho lớn hơn. 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 viết này. Mỗi tài nguyên đều bao gồm mã mẫu đầy đủ, kèm 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. + +- [Create Barcode PNG – DataMatrix Aspect Ratio – Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-aspect-ratio-customization/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to Customize Barcode - Codablock F Aspect Ratio with Aspose.BarCode for .NET](/barcode/english/net/codablock-f-encoding/codablock-f-aspect-ratio-customization/) + +{{< /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-png-in-python-step-by-step-guide/_index.md b/barcode/vietnamese/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..c307916c1 --- /dev/null +++ b/barcode/vietnamese/python-java/general/create-barcode-png-in-python-step-by-step-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-08-03 +description: Tạo mã vạch PNG nhanh chóng với hướng dẫn này. Tìm hiểu cách tạo hình + ảnh mã vạch bằng Aspose.BarCode và tạo mã vạch Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create barcode png +- how to generate barcode image +- generate planet barcode +- Python barcode generation +- Aspose.BarCode tutorial +language: vi +lastmod: 2026-08-03 +og_description: Tạo mã vạch PNG ngay lập tức. Hướng dẫn này cho thấy cách tạo hình + ảnh mã vạch và tạo mã vạch hành tinh với Aspose.BarCode. +og_image_alt: Example of a Planet barcode saved as a PNG image +og_title: Tạo mã vạch PNG trong Python – hướng dẫn lập trình toàn diện +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + headline: Create barcode PNG in Python – step‑by‑step guide + type: TechArticle +- description: Create barcode PNG quickly with this guide. Learn how to generate barcode + image using Aspose.BarCode and generate planet barcode. + name: Create barcode PNG in Python – step‑by‑step guide + steps: + - name: 1. Install the Aspose.BarCode package + text: 'Aspose provides a pure‑Python package that wraps its .NET core engine. + Install it with `pip`:' + - name: 2. Import required classes + text: '```python from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat + ```' + - name: 3. Create a barcode generator for the Planet symbology + text: '```python # Step 1: Create a barcode generator for the Planet symbology + with the desired data barcode_generator = BarcodeGenerator(EncodeTypes.Planet, + "123456") ```' + - name: 4. Set the X dimension (module width) in pixels + text: '```python # Step 2: Set the X dimension (module width) in pixels barcode_generator.parameters.barcode.x_dimension.pixels + = 4 ```' + - name: 5. Define a manual bar height in pixels + text: '```python # Step 3: Define a manual bar height in pixels barcode_generator.parameters.barcode.bar_height.pixels + = 100 ```' + - name: 6. Save the generated barcode as a PNG image + text: '```python # Step 4: Save the generated barcode as a PNG image output_path + = "output/PlanetBarHeight100.png" barcode_generator.save(output_path, BarCodeImageFormat.Png) + print(f"Barcode saved to {output_path}") ```' + - name: 7. Verify the output (optional) + text: '```python from PIL import Image' + - name: ' ## 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 Create Barcode Aspose Java - Adjust Image Quality](/barcode/english/java/image-manipulation/adjusting-image-quality-barcode/) + - [Generate Barcode Java – Set Image Resolution with Aspose.BarCode](/barcode/english/java/advanced-settings-and-optimization/setting-image-resolution-barcode/) + - [How to generate barcode java: Create an Exact Barcode Image](/barcode/english/java/barcode-basics/creating-image-exact-barcode/) + + {{< /blocks/products/pf/tutorial-page-section >}}' + text: '{{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class + >}} {{< blocks/products/products-backtop-button >}}' + type: HowTo +tags: +- barcode +- PNG +- Python +- Aspose +title: Tạo mã vạch PNG trong Python – hướng dẫn từng bước +url: /vi/python-java/general/create-barcode-png-in-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo barcode PNG trong Python – hướng dẫn từng bước + +Nếu bạn cần **tạo barcode PNG** từ ứng dụng Python của mình, hướng dẫn này sẽ chỉ cho bạn cách thực hiện. Chúng tôi sẽ hướng dẫn **cách tạo hình ảnh barcode** bằng Aspose.BarCode và cụ thể là **tạo barcode planet** với kích thước tùy chỉnh. + +Bạn sẽ học cách cài đặt thư viện, cấu hình ký hiệu Planet, điều chỉnh các tham số kích thước và lưu kết quả dưới dạng PNG chất lượng cao. Hướng dẫn giả định bạn có kiến thức cơ bản về Python và phiên bản Python 3 mới (3.8 trở lên). Không yêu cầu kinh nghiệm trước về các tiêu chuẩn barcode. + +--- + +## Cách tạo barcode PNG với Aspose.BarCode + +Phần này chứa các bước cốt lõi cần thiết để **tạo barcode PNG**. Mỗi bước bao gồm một đoạn mã, giải thích lý do quan trọng và các mẹo thực tế bạn có thể áp dụng ngay. + +### 1. Cài đặt gói Aspose.BarCode + +Aspose cung cấp một gói pure‑Python bao bọc engine .NET core của nó. Cài đặt bằng `pip`: + +```bash +pip install aspose-barcode +``` + +*​Tại sao bước này quan trọng:* Gói cung cấp lớp `BarcodeGenerator` được sử dụng trong toàn bộ ví dụ. Cài đặt toàn cục đảm bảo trình thông dịch có thể tìm thấy assembly tại thời gian chạy. + +### 2. Nhập các lớp cần thiết + +```python +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +``` + +*Mẹo:* Chỉ nhập các ký hiệu bạn cần; điều này giữ cho không gian tên sạch sẽ và tăng tốc tải mô-đun. + +### 3. Tạo một barcode generator cho ký hiệu Planet + +```python +# Step 1: Create a barcode generator for the Planet symbology with the desired data +barcode_generator = BarcodeGenerator(EncodeTypes.Planet, "123456") +``` + +*​Tại sao điều này quan trọng:* `EncodeTypes.Planet` báo cho engine sử dụng tiêu chuẩn barcode Planet, trong khi đối số thứ hai cung cấp dữ liệu để mã hoá. Thay đổi ký hiệu (ví dụ, `EncodeTypes.Code128`) sẽ tạo ra một mẫu hình ảnh hoàn toàn khác. + +### 4. Đặt kích thước X (độ rộng mô-đun) tính bằng pixel + +```python +# Step 2: Set the X dimension (module width) in pixels +barcode_generator.parameters.barcode.x_dimension.pixels = 4 +``` + +*​Giải thích:* Kích thước X kiểm soát độ rộng của thanh mảnh. Giá trị 4 pixel tạo ra barcode có độ dày vừa phải và vẫn có thể quét được trên hầu hết các thiết bị. + +### 5. Định nghĩa chiều cao thanh thủ công tính bằng pixel + +```python +# Step 3: Define a manual bar height in pixels +barcode_generator.parameters.barcode.bar_height.pixels = 100 +``` + +*​Tại sao bạn có thể điều chỉnh điều này:* Một số máy in bán lẻ yêu cầu thanh cao hơn để quét đáng tin cậy. Chiều cao mặc định thường là 50 px; tăng lên 100 px cải thiện khả năng đọc mà không làm tăng kích thước tệp đáng kể. + +### 6. Lưu barcode đã tạo dưới dạng ảnh PNG + +```python +# Step 4: Save the generated barcode as a PNG image +output_path = "output/PlanetBarHeight100.png" +barcode_generator.save(output_path, BarCodeImageFormat.Png) +print(f"Barcode saved to {output_path}") +``` + +*Kết quả:* Một tệp PNG có tên **PlanetBarHeight100.png** sẽ xuất hiện trong thư mục `output`. PNG không mất dữ liệu, rất phù hợp cho việc in ấn và nhúng vào trang web. + +### 7. Xác minh đầu ra (tùy chọn) + +```python +from PIL import Image + +with Image.open(output_path) as img: + img.show() # Opens the default image viewer + print(f"Image size: {img.size} (width, height)") +``` + +*Mẹo:* Xem ảnh để xác nhận các kích thước khớp với tham số bạn đã đặt. Nếu barcode bị biến dạng, hãy kiểm tra lại kích thước X hoặc chiều cao thanh. + +--- + +## Cách tạo hình ảnh barcode ở định dạng PNG (cài đặt thay thế) + +Nếu bạn cần một định dạng ảnh khác hoặc muốn nhúng barcode vào PDF sau này, bạn có thể thay đổi enum `BarCodeImageFormat`: + +```python +# Save as JPEG instead of PNG +barcode_generator.save("output/PlanetBar.jpeg", BarCodeImageFormat.Jpeg) + +# Save as BMP for legacy Windows applications +barcode_generator.save("output/PlanetBar.bmp", BarCodeImageFormat.Bmp) +``` + +*​Tại sao điều này quan trọng:* PNG giữ nguyên mọi pixel, điều này rất quan trọng đối với barcode có độ tương phản cao. JPEG tạo ra các artefact nén có thể gây cản trở việc quét, trong khi BMP cung cấp khả năng tương thích với các công cụ cũ. + +--- + +## Tạo barcode planet với màu tùy chỉnh (nâng cao) + +Ngoài kích thước, bạn có thể tùy chỉnh màu nền và màu chữ: + +```python +from aspose.barcode import Color + +# Set foreground to dark blue and background to light gray +barcode_generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +barcode_generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +barcode_generator.save("output/PlanetColored.png", BarCodeImageFormat.Png) +``` + +*Mẹo thực tế:* Các cặp màu độ tương phản cao (đậm trên nền sáng) tối đa hoá độ tin cậy của máy quét. Tránh sử dụng các màu gần nhau cho nền và màu chữ. + +--- + +## Những lỗi thường gặp và cách tránh chúng + +| Symptom | Cause | Fix | +|---------|-------|-----| +| Barcode không quét được | Kích thước X quá nhỏ (≤ 2 px) | Tăng `x_dimension.pixels` lên ít nhất 3 px | +| Hình ảnh bị mờ | PNG được lưu ở DPI thấp | Sử dụng `barcode_generator.save(..., BarCodeImageFormat.Png, 300)` để chỉ định 300 DPI (nếu hỗ trợ) | +| Ngoại lệ `ImportError` | Chưa cài đặt Aspose.BarCode | Chạy `pip install aspose-barcode` trong cùng môi trường với script của bạn | +| Ký hiệu sai | Sử dụng `EncodeTypes.Code128` thay vì `EncodeTypes.Planet` | Thay thế bằng `EncodeTypes.Planet` khi tạo generator | + +--- + +## Tóm tắt giải pháp hoàn chỉnh + +Đoạn script đầy đủ, có thể chạy được dưới đây **tạo barcode PNG** từ đầu đến cuối: + +```python +# full_example.py +# ------------------------------------------------- +# Demonstrates how to generate a Planet barcode PNG +# ------------------------------------------------- + +from aspose.barcode import BarcodeGenerator, EncodeTypes, BarCodeImageFormat +import os + +# Ensure output directory exists +output_dir = "output" +os.makedirs(output_dir, exist_ok=True) + +# 1️⃣ Create generator with Planet symbology +generator = BarcodeGenerator(EncodeTypes.Planet, "123456") + +# 2️⃣ Configure dimensions +generator.parameters.barcode.x_dimension.pixels = 4 # module width +generator.parameters.barcode.bar_height.pixels = 100 # bar height + +# 3️⃣ Optional: set colors (uncomment to use) +# from aspose.barcode import Color +# generator.parameters.barcode.barcode_color = Color(0, 0, 139) # DarkBlue +# generator.parameters.barcode.back_color = Color(211, 211, 211) # LightGray + +# 4️⃣ Save as PNG +png_path = os.path.join(output_dir, "PlanetBarHeight100.png") +generator.save(png_path, BarCodeImageFormat.Png) + +print(f"✅ Barcode PNG created at: {png_path}") + +# 5️⃣ Verify (opens the image on most OSes) +try: + from PIL import Image + with Image.open(png_path) as img: + img.show() + print(f"Image size: {img.size}") +except Exception as e: + print(f"Verification step skipped: {e}") +``` + +Chạy script này sẽ tạo ra một **Planet barcode PNG** sắc nét mà bạn có thể nhúng vào HTML, đính kèm vào email, hoặc in lên nhãn sản phẩm. + +--- + +## Các bước tiếp theo và các chủ đề liên quan + +* **Tích hợp với Flask hoặc Django** – phục vụ PNG đã tạo trực tiếp từ endpoint web. +* **Tạo hàng loạt** – lặp qua danh sách ID sản phẩm để tạo một thư mục chứa các file barcode PNG. +* **Kết hợp với tạo PDF** – sử dụng `aspose-pdf` để chèn PNG vào hoá đơn hoặc nhãn vận chuyển. +* **Khám phá các ký hiệu khác** – thay thế `EncodeTypes.Planet` bằng `EncodeTypes.QR`, `EncodeTypes.DataMatrix`, hoặc `EncodeTypes.Code128` để đáp ứng các nhu cầu kinh doanh khác. + +Bằng cách nắm vững các bước trên, bạn giờ đã biết **cách tạo hình ảnh barcode** một cách lập trình và có thể mở rộng mẫu này cho bất kỳ tiêu chuẩn barcode nào được Aspose.BarCode hỗ trợ. + +### + +{{< /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-postal-barcode-image-in-c-step-by-step-guide/_index.md b/barcode/vietnamese/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md new file mode 100644 index 000000000..b57e432f1 --- /dev/null +++ b/barcode/vietnamese/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-08-03 +description: Tạo nhanh hình ảnh mã vạch bưu chính bằng C#. Tìm hiểu cách tạo mã vạch + bưu chính, thiết lập kích thước mã vạch và tạo mã vạch Planet. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- create postal barcode image +- how to generate postal barcode +- generate planet barcode +- how to set barcode dimensions +language: vi +lastmod: 2026-08-03 +og_description: Tạo hình ảnh mã vạch bưu chính bằng C# với hướng dẫn đầy đủ này; học + cách thiết lập kích thước mã vạch, tạo mã Planet và sản xuất mã RM4SCC. +og_image_alt: Generated postal barcode image saved as PNG using C# BarcodeGenerator +og_title: Tạo hình ảnh mã vạch bưu chính trong C# – hướng dẫn lập trình đầy đủ +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: Create postal barcode image in C# quickly. Learn how to generate postal + barcode, set barcode dimensions, and generate a Planet barcode. + headline: Create postal barcode image in C# – step‑by‑step guide + type: TechArticle +tags: +- barcode +- C# +- postal barcode +title: Tạo hình ảnh mã vạch bưu chính trong C# – hướng dẫn từng bước +url: /vi/python-java/general/create-postal-barcode-image-in-c-step-by-step-guide/ +--- + +{{< 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 bưu chính trong C# – hướng dẫn chi tiết + +Nếu bạn cần **tạo hình ảnh mã vạch bưu chính** trong C#, hướng dẫn này sẽ chỉ cho bạn cách thực hiện. Chúng tôi sẽ đề cập tới **cách tạo mã vạch bưu chính**, **cách đặt kích thước mã vạch**, và cách **tạo mã vạch Planet** cho các tiêu chuẩn bưu chính phổ biến. + +Bạn sẽ có hai tệp PNG sẵn sàng sử dụng — một mã vạch Planet và một mã vạch RM4SCC — mỗi tệp có chiều cao 100 px. Không cần công cụ bổ sung nào ngoài thư viện Aspose.BarCode cho .NET. + +## Yêu cầu trước + +* .NET 6 SDK hoặc phiên bản mới hơn (mã cũng hoạt động với .NET Framework 4.7+) +* Visual Studio 2022 hoặc bất kỳ IDE C# nào +* Gói NuGet **Aspose.BarCode** (thư viện cung cấp `BarcodeGenerator`) + +## Bước 1: Cài đặt thư viện mã vạch + +Mở terminal trong thư mục dự án của bạn và chạy: + +```bash +dotnet add package Aspose.BarCode +``` + +Gói này sẽ thêm namespace `Aspose.BarCode`, trong đó chứa `BarcodeGenerator` và enum `EncodeTypes` cần thiết cho các mã vạch bưu chính. + +## Bước 2: Định nghĩa thư mục đầu ra + +Tạo một đường dẫn đầu ra đáng tin cậy giúp tránh lỗi thời gian chạy khi thư mục chưa tồn tại. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure the directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); +``` + +*Lý do quan trọng*: `Directory.CreateDirectory` là idempotent — nó chỉ tạo thư mục nếu chưa có, tránh ngoại lệ khi chạy lại. + +## Bước 3: Cấu hình kích thước chung cho mã vạch + +Đặt X‑dimension (chiều rộng của một thanh mảnh) và chiều cao tổng thể của thanh cho phép bạn kiểm soát kích thước hình ảnh được tạo. + +```csharp + // Common dimension settings + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Desired barcode height +``` + +**Cách đặt kích thước mã vạch**: Thuộc tính `Parameters.Barcode.XDimension.Pixels` xác định độ rộng thanh mảnh, trong khi `Parameters.Barcode.BarHeight.Pixels` xác định chiều cao đầy đủ. Điều chỉnh các giá trị này để đáp ứng yêu cầu của dịch vụ bưu chính bạn sử dụng. + +## Bước 4: Tạo mã vạch Planet + +Planet là một mã vạch bưu chính được sử dụng rộng rãi ở Vương quốc Anh. Đoạn mã dưới đây tạo một mã vạch Planet cao 100 px và lưu dưới dạng PNG. + +```csharp + // Step 4: Generate Planet barcode + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); +``` + +**Tại sao lại hoạt động**: `EncodeTypes.Planet` báo cho trình tạo sử dụng ký hiệu Planet. Phương thức `Save` ghi tệp PNG vào đường dẫn đã chỉ định, giữ nguyên các kích thước chúng ta đã thiết lập trước đó. + +## Bước 5: Tạo mã vạch RM4SCC + +RM4SCC là tiêu chuẩn mã vạch bưu chính của Hà Lan. Mã dưới đây sao chép ví dụ Planet, minh họa **cách tạo mã vạch bưu chính** loại khác với cùng kích thước. + +```csharp + // Step 5: Generate RM4SCC barcode + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); +``` + +Hai tệp PNG bây giờ nằm trong thư mục `Barcodes`. Mở chúng sẽ thấy các mã vạch sạch sẽ, cao 100 px, sẵn sàng in hoặc nhúng vào tài liệu. + +## Toàn bộ mã nguồn + +Dưới đây là chương trình hoàn chỉnh, có thể chạy được, **tạo hình ảnh mã vạch bưu chính** cho cả tiêu chuẩn Planet và RM4SCC. + +```csharp +using System; +using System.IO; +using Aspose.BarCode; +using Aspose.BarCode.Generation; + +class PostalBarcodeDemo +{ + static void Main() + { + // Ensure output directory exists + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // Dimension settings – reusable for all barcodes + const int xDimensionPixels = 4; // Width of a single bar + const int barHeightPixels = 100; // Height of the barcode + + // ---- Generate Planet barcode ---- + BarcodeGenerator planetGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + planetGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + planetGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string planetPath = Path.Combine(outputFolder, "PostalPlanetBarHeight100Pixels.png"); + planetGenerator.Save(planetPath, BarCodeImageFormat.Png); + + // ---- Generate RM4SCC barcode ---- + BarcodeGenerator rm4sccGenerator = new BarcodeGenerator(EncodeTypes.RM4SCC, "123456"); + rm4sccGenerator.Parameters.Barcode.XDimension.Pixels = xDimensionPixels; + rm4sccGenerator.Parameters.Barcode.BarHeight.Pixels = barHeightPixels; + string rm4sccPath = Path.Combine(outputFolder, "PostalRM4SCCBarHeight100Pixels.png"); + rm4sccGenerator.Save(rm4sccPath, BarCodeImageFormat.Png); + + Console.WriteLine("Barcodes generated:"); + Console.WriteLine($"• {planetPath}"); + Console.WriteLine($"• {rm4sccPath}"); + } +} +``` + +### Kết quả mong đợi + +Chạy chương trình sẽ in ra các đường dẫn tệp và tạo hai tệp PNG: + +``` +Barcodes/ + ├─ PostalPlanetBarHeight100Pixels.png + └─ PostalRM4SCCBarHeight100Pixels.png +``` + +Mỗi hình ảnh có chiều cao 100 px, với độ rộng thanh mảnh 4 pixel, khớp với các kích thước chúng ta đã đặt. + +## Mẹo thực tế và các lỗi thường gặp + +* **Quyền thư mục** – Nếu chương trình chạy dưới tài khoản bị hạn chế, hãy đảm bảo thư mục đích có quyền ghi. +* **Kích thước khác nhau** – Để tạo mã vạch cao hơn, tăng `barHeightPixels`. Để có độ phân giải mịn hơn, giảm `xDimensionPixels`, nhưng giữ ≥ 2 để tránh hiện tượng lỗi hiển thị. +* **Các ký hiệu bưu chính khác** – Aspose.BarCode cũng hỗ trợ `EncodeTypes.Postnet` và `EncodeTypes.AustralianPost`. Chỉ cần thay giá trị `EncodeTypes` và giữ nguyên logic kích thước. +* **Định dạng ảnh** – Dùng `BarCodeImageFormat.Jpeg` để giảm dung lượng tệp khi không cần chất lượng không mất dữ liệu. + +## Kết luận + +Bây giờ bạn đã biết cách **tạo hình ảnh mã vạch bưu chính** trong C# bằng cách cấu hình kích thước, chọn ký hiệu phù hợp và lưu kết quả dưới dạng PNG. Bài hướng dẫn đã đề cập **cách tạo mã vạch bưu chính**, trình bày **cách tạo mã vạch Planet**, và giải thích **cách đặt kích thước mã vạch** để có đầu ra nhất quán. + +Tiếp theo, hãy khám phá **tùy chỉnh màu sắc mã vạch**, thêm **văn bản có thể đọc được**, hoặc tích hợp các hình ảnh vào hoá đơn PDF. Mẫu này áp dụng cho bất kỳ loại mã vạch nào khác được Aspose.BarCode hỗ trợ, giúp bạn mở rộng giải pháp này thành một quy trình tự động hoá bưu chính hoàn chỉnh. + +## 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 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 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. + +- [How to Generate Barcode - One-Dimensional Barcode Types](/barcode/english/net/one-dimensional-barcode-types/) +- [How to generate Aztec barcode with custom aspect ratio using Aspose.BarCode for .NET](/barcode/english/net/aztec-barcode-encoding/aztec-aspect-ratio-customization/) +- [How to generate barcode java – Australia Post Barcode with Aspose](/barcode/english/java/barcode-configuration/generating-australia-post-barcode/) + +{{< /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-save-barcode-in-c-complete-barcode-generator-guide/_index.md b/barcode/vietnamese/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md new file mode 100644 index 000000000..a1100e070 --- /dev/null +++ b/barcode/vietnamese/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-08-03 +description: Cách lưu mã vạch trong C# với ví dụ tạo mã vạch từng bước. Tìm hiểu cách + tạo mã vạch Planet, đặt kích thước và xuất ảnh PNG. +draft: false +images: +- PLACEHOLDER_URL/og-image.png +keywords: +- how to save barcode +- c# barcode generator +- barcode generator example +- how to generate barcode +- generate planet barcode +language: vi +lastmod: 2026-08-03 +og_description: Cách lưu mã vạch trong C# bằng ví dụ trình tạo mã vạch. Hướng dẫn + này cho thấy cách tạo mã vạch Planet, cấu hình kích thước X và xuất file PNG. +og_image_alt: Screenshot showing saved Planet barcode PNG files generated by C# barcode + generator +og_title: Cách lưu mã vạch trong C# – hướng dẫn từng bước +schemas: +- author: Aspose + dateModified: '2026-08-03' + description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + headline: How to save barcode in C# – complete barcode generator guide + type: TechArticle +- description: How to save barcode in C# with a step‑by‑step barcode generator example. + Learn to generate Planet barcodes, set dimensions, and export PNG images. + name: How to save barcode in C# – complete barcode generator guide + steps: + - name: Define the output folder + text: '```csharp // Define where the barcode images will be saved string outputFolder + = Path.Combine(Environment.CurrentDirectory, "Barcodes");' + - name: Create a Planet barcode generator (filled bars) + text: '```csharp // Initialize a generator for the Planet barcode with data "123456" + BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, + "123456"); ```' + - name: Configure bar width (X‑dimension) and keep default filled bars + text: '```csharp // Set each bar to be 4 pixels wide filledBarsGenerator.Parameters.Barcode.XDimension.Pixels + = 4;' + - name: Save the filled‑bars barcode image + text: '```csharp string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); Console.WriteLine($"Filled‑bars + barcode saved to: {filledPath}"); ```' + - name: Create a second generator for the empty‑bars version + text: '```csharp // Separate generator instance for the empty‑bars variant BarcodeGenerator + emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); ```' + - name: Disable filled bars while keeping the same X‑dimension + text: '```csharp emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid + bars ```' + - name: Save the empty‑bars barcode image + text: '```csharp string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); Console.WriteLine($"Empty‑bars + barcode saved to: {emptyPath}"); ```' + - name: Expected output + text: 'Running the program prints two lines similar to:' + type: HowTo +tags: +- barcode +- C# +- .NET +- imaging +title: Cách lưu mã vạch trong C# – hướng dẫn đầy đủ về trình tạo mã vạch +url: /vi/python-java/general/how-to-save-barcode-in-c-complete-barcode-generator-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách lưu mã vạch trong C# – hướng dẫn đầy đủ về trình tạo mã vạch + +Cách lưu hình ảnh mã vạch trong C# là một yêu cầu phổ biến khi bạn cần nhúng mã vạch bưu chính vào hoá đơn, nhãn vận chuyển, hoặc thẻ tồn kho. Hướng dẫn này sẽ đưa bạn qua quy trình **c# barcode generator** thực tế, từ việc tạo mã Planet đến xuất cả hai file PNG có thanh đầy và thanh rỗng. + +Bạn sẽ học cách đặt độ rộng của thanh, bật/tắt thanh đầy, và xử lý thư mục đầu ra một cách đáng tin cậy. Khi kết thúc tutorial, bạn sẽ có một **barcode generator example** hoạt động đầy đủ mà bạn có thể sao chép vào bất kỳ dự án .NET nào. + +## Những gì bạn cần + +- .NET 6.0 SDK hoặc phiên bản mới hơn (ví dụ hoạt động với .NET Core và .NET Framework) +- Visual Studio 2022 hoặc bất kỳ IDE nào hỗ trợ C# +- Gói NuGet **Aspose.BarCode** (hoặc thư viện khác hỗ trợ `EncodeTypes.Planet`). Cài đặt bằng: + +```bash +dotnet add package Aspose.BarCode +``` + +Thư viện cung cấp lớp `BarcodeGenerator` được sử dụng xuyên suốt tutorial này. + +## Cài đặt môi trường phát triển + +Tạo một dự án console mới và thêm namespace cần thiết: + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; +``` + +Namespace `System.IO` cung cấp `Directory.CreateDirectory`, giúp đảm bảo thư mục đầu ra tồn tại trước khi chúng ta cố gắng ghi file. + +## Cách lưu hình ảnh mã vạch bằng trình tạo mã vạch C# + +Cốt lõi của giải pháp là một tập hợp các bước nhỏ để cấu hình **Planet barcode** và sau đó lưu ảnh vào đĩa. Các phần sau sẽ chia quá trình thành các đoạn dễ quản lý. + +### Bước 1: Xác định thư mục đầu ra + +```csharp +// Define where the barcode images will be saved +string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + +// Ensure the folder exists; creates it if missing +Directory.CreateDirectory(outputFolder); +``` + +**Tại sao?** +Việc mã cứng một đường dẫn có thể gây ra `DirectoryNotFoundException` trên các máy mà thư mục không tồn tại. `CreateDirectory` là idempotent — nó chỉ tạo thư mục nếu chưa có, làm cho mã an toàn khi chạy nhiều lần. + +### Bước 2: Tạo trình tạo Planet barcode (các thanh đầy) + +```csharp +// Initialize a generator for the Planet barcode with data "123456" +BarcodeGenerator filledBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +**Tại sao?** +`EncodeTypes.Planet` chỉ cho thư viện tạo ra một mã Planet bưu chính, được các dịch vụ bưu điện sử dụng rộng rãi. Chuỗi `"123456"` là dữ liệu mẫu; bạn có thể thay thế bằng bất kỳ dữ liệu số nào cần thiết cho logic kinh doanh của mình. + +### Bước 3: Cấu hình độ rộng thanh (X‑dimension) và giữ mặc định thanh đầy + +```csharp +// Set each bar to be 4 pixels wide +filledBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; + +// Filled bars are enabled by default, so no extra code is needed here +``` + +**Tại sao?** +X‑dimension điều khiển độ rộng thực tế của mỗi thanh. Giá trị `4` pixel tạo ra mã vạch có thể đọc được trên máy in tiêu chuẩn 300 dpi. Giữ `FilledBars` là `true` (mặc định) sẽ tạo ra dạng thanh đặc truyền thống. + +### Bước 4: Lưu ảnh mã vạch với thanh đầy + +```csharp +string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); +filledBarsGenerator.Save(filledPath, BarCodeImageFormat.Png); +Console.WriteLine($"Filled‑bars barcode saved to: {filledPath}"); +``` + +**Tại sao?** +Lưu dưới dạng PNG giữ nguyên chất lượng ảnh không mất dữ liệu, điều này quan trọng cho độ chính xác khi quét. Phương thức `Save` tự động tạo file ảnh; bạn chỉ cần cung cấp đường dẫn đầy đủ và định dạng mong muốn. + +### Bước 5: Tạo trình tạo thứ hai cho phiên bản thanh rỗng + +```csharp +// Separate generator instance for the empty‑bars variant +BarcodeGenerator emptyBarsGenerator = new BarcodeGenerator(EncodeTypes.Planet, "123456"); +``` + +Tạo một instance mới đảm bảo các thay đổi cho phiên bản thanh rỗng không ảnh hưởng đến ảnh thanh đầy đã lưu. + +### Bước 6: Tắt thanh đầy trong khi giữ nguyên X‑dimension + +```csharp +emptyBarsGenerator.Parameters.Barcode.XDimension.Pixels = 4; +emptyBarsGenerator.Parameters.Barcode.FilledBars = false; // Turn off solid bars +``` + +**Tại sao?** +Đặt `FilledBars = false` sẽ vẽ mã vạch chỉ với viền của mỗi thanh, một số tiêu chuẩn bưu chính yêu cầu để kiểm tra trực quan. + +### Bước 7: Lưu ảnh mã vạch thanh rỗng + +```csharp +string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); +emptyBarsGenerator.Save(emptyPath, BarCodeImageFormat.Png); +Console.WriteLine($"Empty‑bars barcode saved to: {emptyPath}"); +``` + +Bây giờ bạn có hai file PNG — một với thanh đầy và một với thanh rỗng — sẵn sàng để chèn vào PDF, email HTML, hoặc nhãn in. + +## Chương trình đầy đủ có thể chạy + +Dưới đây là mã hoàn chỉnh bạn có thể sao chép vào `Program.cs`. Nó biên dịch và chạy mà không cần sửa đổi (giả sử gói Aspose.BarCode đã được cài đặt). + +```csharp +using System; +using System.IO; +using Aspose.BarCode.Generation; + +namespace BarcodeDemo +{ + class Program + { + static void Main() + { + // 1️⃣ Output folder preparation + string outputFolder = Path.Combine(Environment.CurrentDirectory, "Barcodes"); + Directory.CreateDirectory(outputFolder); + + // 2️⃣ Filled‑bars Planet barcode + BarcodeGenerator filled = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + filled.Parameters.Barcode.XDimension.Pixels = 4; // bar width + string filledPath = Path.Combine(outputFolder, "PostalPlanetFilledBars.png"); + filled.Save(filledPath, BarCodeImageFormat.Png); + Console.WriteLine($"Filled‑bars saved: {filledPath}"); + + // 3️⃣ Empty‑bars Planet barcode + BarcodeGenerator empty = new BarcodeGenerator(EncodeTypes.Planet, "123456"); + empty.Parameters.Barcode.XDimension.Pixels = 4; + empty.Parameters.Barcode.FilledBars = false; // disable solid bars + string emptyPath = Path.Combine(outputFolder, "PostalPlanetEmptyBars.png"); + empty.Save(emptyPath, BarCodeImageFormat.Png); + Console.WriteLine($"Empty‑bars saved: {emptyPath}"); + } + } +} +``` + +### Đầu ra dự kiến + +Chạy chương trình sẽ in ra hai dòng tương tự như: + +``` +Filled‑bars saved: C:\MyProject\Barcodes\PostalPlanetFilledBars.png +Empty‑bars saved: C:\MyProject\Barcodes\PostalPlanetEmptyBars.png +``` + +Mở thư mục `Barcodes` và bạn sẽ thấy hai file PNG. Cả hai ảnh đều có thể mở bằng bất kỳ trình xem ảnh nào hoặc nhúng trực tiếp vào tài liệu. + +![ví dụ cách lưu mã vạch](barcode-example.png){: .align-center alt="ví dụ cách lưu mã vạch"} + +## Các biến thể phổ biến và trường hợp đặc biệt + +| Kịch bản | Điều chỉnh | +|----------|------------| +| **Định dạng ảnh khác** | Thay `BarCodeImageFormat.Png` thành `Jpeg`, `Gif`, hoặc `Bmp` tùy nhu cầu. | +| **Kích thước đầu ra tùy chỉnh** | Sử dụng `filled.Parameters.Image.Width` và `Height` để ép một kích thước pixel cụ thể. | +| **Dữ liệu động** | Thay chuỗi tĩnh `"123456"` bằng một biến chứa số đơn hàng, ID theo dõi, v.v. | +| **Thư mục không tồn tại** | `Directory.CreateDirectory` đã xử lý việc thiếu thư mục; không cần mã bổ sung. | +| **In độ phân giải cao** | Tăng `XDimension.Pixels` lên 6–8 cho máy in 600 dpi, nhưng hãy kiểm tra tính tương thích của máy quét. | + +**Mẹo:** Nếu bạn cần tạo nhiều mã vạch trong một vòng lặp, hãy tái sử dụng một instance `BarcodeGenerator` duy nhất và chỉ thay đổi thuộc tính `CodeText` trước mỗi lần `Save`. Điều này giảm tải việc cấp phát đối tượng. + +## Cách tạo mã vạch cho các tiêu chuẩn khác + +Mẫu tương tự hoạt động cho các `EncodeTypes` khác như `Code128`, `QR`, hoặc `DataMatrix`. Chỉ cần thay `EncodeTypes.Planet` bằng loại mong muốn và điều chỉnh bất kỳ tham số đặc thù nào của loại đó (ví dụ, `QRCodeVersion`). + +## Bạn nên học gì tiếp theo? + +Các tutorial 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ã hoàn chỉnh 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 lưu PNG sử dụng DataMatrix C40 với Aspose.BarCode](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-encoding-mode-c40/) +- [Cách tạo mã DataMatrix (ECC 200) với Aspose.BarCode cho .NET](/barcode/english/net/datamatrix-barcode-configuration/datamatrix-ecc-200-configuration/) +- [Cách tạo mã vạch – Cấu hình Code 39 với Aspose.BarCode](/barcode/english/net/one-dimensional-barcode-types/one-dimensional-code-39-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