- ติดตั้ง BarcodeLib
- เพิ่ม References System.Drawing
- ทดลองสร้าง Barcode
- WebApi return เป็นภาพ PNG
1. ติดตั้ง BarcodeLib
VS 2013 เลือกติดตั้ง BarcodeLib เวอร์ชัน 1.3.0
PM> Install-Package BarcodeLib -Version 1.3.0
2.เพิ่ม References System.Drawing
System.Drawing
3.ทดลองสร้าง Barcode
ทดลองสร้าง Barcode แล้วบันทึกเป็นไฟล์ภาพ
using System.Drawing;
namespace ConsoleAppBarcode
{
class Program
{
static void Main(string[] args)
{
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
Image img = b.Encode(BarcodeLib.TYPE.UPCA, "038000356216", Color.Black, Color.White, 290, 120);
img.Save("barcode.bmp");
img.Save("barcode.jpg");
img.Save("barcode.png");
}
}
}
กำหนด format ชองภาพด้วย ImageFormat.Png
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
Image img1 = b.Encode(BarcodeLib.TYPE.UPCA, "038000356216"
, Color.Black, Color.White, 290, 120);
img1.Save("upca.png", ImageFormat.Png);
Image img2 = b.Encode(BarcodeLib.TYPE.CODE128, "038000356216"
, Color.Black, Color.White, 290, 120);
img2.Save("code128.png", ImageFormat.Png);
ทดลองสร้าง Barcode แล้วเก็บไว้ในตัวแปร Byte[]
using BarcodeLib;
using System;
using System.IO;
namespace ConsoleAppBarcode
{
class Program
{
static void Main(string[] args)
{
Barcode brcode = new Barcode();
string BarcodeText = "038000356216";
brcode.Encode(TYPE.CODE128, BarcodeText, 1000, 250);
MemoryStream ms = new MemoryStream();
brcode.SaveImage(ms, SaveTypes.PNG);
Byte[] barcodeByte = ms.ToArray();
}
}
}
4.WebApi return เป็นภาพ PNG
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(string id)
{
BarcodeLib.Barcode b = new BarcodeLib.Barcode();
Image img = b.Encode(BarcodeLib.TYPE.CODE128, id
, Color.Black, Color.White, 290, 120);
img.Save("code128.png", ImageFormat.Png);
Byte[] b1 = System.IO.File.ReadAllBytes("code128.png");
return File(b1, "image/png");
}