I use the Fujitsu series (5000 series, 6000 series) of scanners. I am using the software detection of barcode. I read the image and detect if a barcode exisits in the image. All code is derived from examples provided in your documentation over the years, so I may be using outdated techniques.
Code: Select all
using System;
using System.Linq;
using Vintasoft.Twain;
using Vintasoft.Barcode;
using System.Xml.Linq;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
namespace InvoiceTracking
{
class ScannerModal
{
private Device _device;
private Device _cleandevice;
private string _barcode = "";
private BarcodeReader _barcodeReader = new BarcodeReader();
private IBarcodeInfo[] _infos;
private string _fileLocation = @"C:\ScannedInvoices\";
protected bool _autoCleanBuffer;
protected bool _automaticRecognition;
protected int _bitDepth;
protected bool _disableAfterAcquire;
protected int _fileJpegQuality;
protected ImageFilter _imageFilter;
protected bool _modalUI;
protected NoiseFilter _noiseFilter;
protected PixelFlavor _pixelFlavor;
protected PixelType _pixelType;
protected float _resolution;
protected bool _showIndicators;
protected bool _showUI;
protected float _threshold;
protected TransferMode _transferMode;
protected Vintasoft.Twain.UnitOfMeasure _unitOfMeasure;
protected bool _useADF;
protected bool _useDuplex;
protected short _xferCount;
protected bool _pdfMultiPage;
private bool _noBarcode;
private string ShiftDate;
private string Location;
private int _Invoices;
private int _Errors;
private Label _customerName;
private ListBox _invoiceList;
private ListBox _invoiceErrors;
private int _primaryCustomerNumber;
private int _customerNumber;
private string _prevBarcode;
private string _scannedInvoice;
private string _scanLogs;
private bool _ignoreErrors;
public string _FluidsConnectionString;
public string _AdminConnectionString;
public string _CustomersConnectionString;
public string _InvoiceTrackingConnectionString;
public ScannerModal(Device device)
{
this._barcode = "";
this._barcodeReader = new BarcodeReader();
this._fileLocation = "C:\\ScannedInvoices\\";
this._cleandevice = device;
this._device = this._cleandevice;
_Invoices = 0;
_Errors = 0;
}
private void _device_ImageAcquired()
{
Image _image = this._device.AcquiredImages.Last.GetAsBitmap();
Bitmap tmp = (Bitmap)_image;
AcquiredImage _imageInfo = this._device.AcquiredImages.Last;
this._infos = this.ReadBarcodes(tmp);
int i;
switch (_noBarcode)
{
case true:
noBarcode();
break;
case false:
Barcode();
break;
}
}
private void noBarcode()
{
// if noBarcode and no previous barcode read, throw error
if (_prevBarcode == null || _prevBarcode.Trim() == "")
{
this._barcode = "";
MessageBox.Show("No Barcode was detected. The image will be discarded. Correct issue and resubmit.\n ");
return;
}
if (MessageBox.Show("No Barcode was detected. Do you want to append this page to " + this._prevBarcode +
"\n Select Yes to append it or No to discard the page. \n." +
"in the package or Cancel to Bypass",
"No Barcode ws detected", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
this._barcode = _prevBarcode;
this._noBarcode = true;
AppendMultiPage();
return;
}
this._device.AcquiredImages.RemoveAt(this._device.AcquiredImages.Count - 1);
}
private void Barcode()
{
int i = 0;
this._barcode = this._infos[0].Value;
if (!(int.TryParse(this._infos[0].Value, out i)))
{
{
MessageBox.Show("The Barcode ( " + this._barcode + " ) appears to be invalid. The image will be discarded. Correct issue and resubmit.\n " +
"If Barcode is correct, please contact support");
this._barcode = "";
return;
}
}
if (i < 250000 || i > 1000000)
{
MessageBox.Show("The Barcode ( " + _barcode + " ) appears to be out of the normal range. The image will be discarded. Correct issue and resubmit.\n " +
"If Barcode is correct, please contact support");
this._barcode = "";
return;
}
BarcodeFound(i);
this._barcode = i.ToString();
_invoiceList.Items.Add(RemoveLeadingZeros(this._barcode.ToString()));
RemoveDuplicates(ref _invoiceList);
this.BSaveImage_Click(false);
_prevBarcode = this._barcode;
}
private string BarcodeFound(int result)
{
FluidsDataContext fdc = new FluidsDataContext(_FluidsConnectionString);
_prevBarcode = this._barcode;
if (_ignoreErrors == false)
{
BillingDetail bdtl = (from p in fdc.BillingDetails where p.InvoiceNumber.ToString() == this._barcode select p).FirstOrDefault();
if (bdtl == null)
{
if (MessageBox.Show("The following Invoice was not found in the Pinnergy System \n " +
this._barcode + " / " + _primaryCustomerNumber.ToString() +
"\n Select OK to keep it in the package or Cancel to Bypass",
"Invoice Not found", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
_invoiceList.Items.Add(RemoveLeadingZeros(this._barcode.ToString()));
}
else
{
}
return result.ToString();
}
else
{
if (bdtl.CustomerNumber != _primaryCustomerNumber)
{
_invoiceErrors.Items.Add(RemoveLeadingZeros(this._barcode.ToString()));
}
else
{
_invoiceList.Items.Add(RemoveLeadingZeros(this._barcode.ToString()));
}
}
}
else
{
}
return result.ToString();
}
public string AcquireImages(ref ListBox listBox1, ref ListBox listBox2, ref int CustomerNumber, ref string PrevBarcode, bool ignoreErrors, string scannedImageDirectory)
{
_invoiceList = listBox1;
_invoiceErrors = listBox2;
_ignoreErrors = ignoreErrors;
_primaryCustomerNumber = CustomerNumber;
_prevBarcode = PrevBarcode;
_scannedInvoice = scannedImageDirectory;
try
{
this._device.Open();
this.GetOptions();
this._device.AcquiredImages.AutoClean = this._autoCleanBuffer;
this._device.AcquiredImages.PdfMultiPage = this._pdfMultiPage;
this._device.DisableAfterAcquire = this._disableAfterAcquire;
this._device.ModalUI = this._modalUI;
this._device.ShowIndicators = this._showIndicators;
this._device.ShowUI = this._showUI;
this._device.BitDepth = this._bitDepth;
this._device.ImageFilter = this._imageFilter;
this._device.NoiseFilter = this._noiseFilter;
this._device.PixelFlavor = this._pixelFlavor;
this._device.PixelType = this._pixelType;
this._device.Resolution = new Resolution((float)this._resolution, (float)this._resolution);
this._device.Threshold = this._threshold;
this._device.TransferMode = this._transferMode;
this._device.UnitOfMeasure = this._unitOfMeasure;
string paramString = "1 - PdfMultiPage " + _device.AcquiredImages.PdfMultiPage.ToString() + "\n";
paramString += "2 - AutoClean " + _device.AcquiredImages.AutoClean + "\n";
paramString += "3 - BitDepth " + _device.BitDepth.ToString() + "\n";
// paramString += "4 - Brightness " + _device.Brightness.ToString() + "\n";
paramString += "5 - DisableAfterAcquire " + _device.DisableAfterAcquire + "\n";
paramString += "6 - FileJpegQuality " + _device.FileJpegQuality.ToString() + "\n";
paramString += "7 - ImageFilter " + _device.ImageFilter.ToString() + "\n";
paramString += "8- ImageLayout " + _device.ImageLayout.ToString() + "\n";
paramString += "9- ModalUI " + _device.ModalUI.ToString() + "\n";
paramString += "10- NoiseFilter " + _device.NoiseFilter.ToString() + "\n";
paramString += "11- PixelFlavor " + _device.PixelFlavor.ToString() + "\n";
paramString += "12- PixelType " + _device.PixelType.ToString() + "\n";
paramString += "13- Resolution " + _device.Resolution.ToString() + "\n";
paramString += "14- ShowIndicators " + _device.ShowIndicators.ToString() + "\n";
paramString += "25- ShowUI " + _device.ShowUI.ToString() + "\n";
paramString += "26- Threshold " + _device.Threshold.ToString() + "\n";
paramString += "17- TransferMode " + _device.TransferMode + "\n";
paramString += "18- UnitOfMeasure " + _device.UnitOfMeasure.ToString() + "\n";
paramString += "19- XferCount " + _device.XferCount.ToString() + "\n";
// MessageBox.Show("Scanner Settings" + "\n" + paramString);
AcquireModalState acquireModalState = AcquireModalState.None;
do
{
acquireModalState = this._device.AcquireModal();
AcquireModalState acquireModalState1 = acquireModalState;
switch (acquireModalState1)
{
case AcquireModalState.ImageAcquired:
{
this._device_ImageAcquired();
}
break;
case AcquireModalState.ScanCompleted:
{
this._device.Close();
}
break;
case AcquireModalState.ScanFailed:
{
this._device.Close();
}
break;
case AcquireModalState.ScanCanceled:
{
this._device.Close();
}
break;
case AcquireModalState.UserInterfaceClosed:
{
this._device.Close();
}
break;
}
}
while (acquireModalState != AcquireModalState.None);
}
catch (TwainException twainException)
{
TwainException ex = twainException;
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
// MessageBox.Show("Stage 3" + _scannedImageDirectory);
listBox1 = _invoiceList;
listBox2 = _invoiceErrors;
CustomerNumber = _primaryCustomerNumber;
PrevBarcode = _prevBarcode;
RemoveDuplicates(ref listBox1);
return "Invoices Processed : " + "\t" + _Invoices.ToString() + "\n" +
"Errors Processed : " + "\t" + _Errors.ToString() + "\n";
}
private void BarcodeError()
{
string errorlevel = "";
try
{
FluidsDataContext fdc = new FluidsDataContext(_FluidsConnectionString);
string dirLocation = _scannedInvoice ;//+ this.ShiftDate != null? this.ShiftDate : "";
//if (!Directory.Exists(_scannedImageDirectory.Trim()))
//{
// Directory.CreateDirectory(dirLocation.Trim());
// errorlevel += "Directory Created - " + dirLocation.Trim() + "\n";
//}
//else
//{
// errorlevel += "Directory Already Exists - " + dirLocation.Trim() + "\n";
//}
// _route = string.Concat("\\Receiving\\" + this.Location.Trim() + "\\", this.ShiftDate.Replace("/", "_"), "\\");
errorlevel += "Error Image will be created/appended - " + string.Concat(dirLocation, this._barcode, ".pdf") + "\n";
string _errorInScan = string.Concat("ERR", System.DateTime.Now.ToFileTime());
_invoiceErrors.Items.Add(_errorInScan);
this._device.AcquiredImages.Last.Save(string.Concat(dirLocation, _errorInScan, ".pdf"));
errorlevel += "Error Image created/appended - " + string.Concat(dirLocation, _errorInScan, ".pdf") + "\n";
this._device.AcquiredImages.RemoveAt(this._device.AcquiredImages.Count - 1);
}
catch (Exception ex)
{
MessageBox.Show("Error Scanning Previous Invoice" + "\n" + errorlevel); // + " / " + this.ShiftDate.ToString() != null ? this.ShiftDate : "");
}
}
private void AppendMultiPage()
{
string errorlevel = "";
try
{
FluidsDataContext fdc = new FluidsDataContext(_FluidsConnectionString);
string dirLocation = _scannedInvoice;// +"\\Invoice\\";//+ this.ShiftDate != null? this.ShiftDate : "";
//if (!Directory.Exists(_scannedInvoice.Trim()))
//{
// Directory.CreateDirectory(dirLocation.Trim());
// errorlevel += "Directory Created - " + dirLocation.Trim() + "\n";
//}
//else
//{
// errorlevel += "Directory Already Exists - " + dirLocation.Trim() + "\n";
//}
if (File.Exists(string.Concat(dirLocation, this._barcode, ".pdf")))
{
errorlevel += "Image will be created/appended - " + string.Concat(dirLocation, this._barcode, ".pdf") + "\n";
this._device.AcquiredImages.Last.Save(string.Concat(dirLocation, RemoveLeadingZeros(this._barcode), ".pdf"));
errorlevel += "Image created/appended - " + string.Concat(dirLocation, this._barcode, ".pdf") + "\n";
}
else
{
errorlevel += "Error Image will be created/appended - " + string.Concat(dirLocation, this._barcode, ".pdf") + "\n";
string _errorInScan = string.Concat("ERR", System.DateTime.Now.ToFileTime());
this._device.AcquiredImages.Last.Save(string.Concat(dirLocation, _errorInScan, ".pdf"));
errorlevel += "Error Image created/appended - " + string.Concat(dirLocation, _errorInScan, ".pdf") + "\n";
MessageBox.Show("Error Scanning Previous Invoice" + "\n" + errorlevel); // + " / " + this.ShiftDate.ToString() != null ? this.ShiftDate : "");
}
this._device.AcquiredImages.RemoveAt(this._device.AcquiredImages.Count - 1);
// MessageBox.Show("Stage 2" + _scannedImageDirectory);
}
catch (Exception ex)
{
MessageBox.Show("Error Scanning Previous Invoice" + "\n" + errorlevel); // + " / " + this.ShiftDate.ToString() != null ? this.ShiftDate : "");
// MessageBox.Show(ex.Message.ToString() + " / " + ex.InnerException.ToString());
}
}
private void BSaveImage_Click(bool nodelete)
{
string errorlevel = "";
try
{
FluidsDataContext fdc = new FluidsDataContext(_FluidsConnectionString);
string dirLocation = _scannedInvoice;// +"\\Invoice\\";//+ this.ShiftDate != null? this.ShiftDate : "";
//if (!Directory.Exists(_scannedInvoice.Trim()))
//{
// Directory.CreateDirectory(dirLocation.Trim());
// errorlevel += "Directory Created - " + dirLocation.Trim() + "\n";
//}
//else
//{
// errorlevel += "Directory Already Exists - " + dirLocation.Trim() + "\n";
//}
if (File.Exists(string.Concat(dirLocation, this._barcode, ".pdf")))
{
if (!nodelete)
{
File.Delete(string.Concat(dirLocation, this._barcode, ".pdf"));
errorlevel += "Image Deleted - " + string.Concat(dirLocation, this._barcode, ".pdf") + "\n";
}
}
if (!this._noBarcode)
{
errorlevel += "Image will be created/appended - " + string.Concat(dirLocation, this._barcode, ".pdf") + "\n";
this._device.AcquiredImages.Last.Save(string.Concat(dirLocation, RemoveLeadingZeros(this._barcode), ".pdf"));
errorlevel += "Image created/appended - " + string.Concat(dirLocation, this._barcode, ".pdf") + "\n";
}
else
{
errorlevel += "Error Image will be created/appended - " + string.Concat(dirLocation, this._barcode, ".pdf") + "\n";
DateTime now = DateTime.Now;
TimeSpan timeOfDay = now.TimeOfDay;
string _errorInScan = string.Concat("ERR", timeOfDay.ToString().Replace(":", "").Replace(".", ""));
this._device.AcquiredImages.Last.Save(string.Concat(dirLocation, _errorInScan, ".pdf"));
errorlevel += "Error Image created/appended - " + string.Concat(dirLocation, _errorInScan, ".pdf") + "\n";
MessageBox.Show("Error Scanning Previous Invoice" + "\n" + errorlevel); // + " / " + this.ShiftDate.ToString() != null ? this.ShiftDate : "");
}
this._device.AcquiredImages.RemoveAt(this._device.AcquiredImages.Count - 1);
}
catch (Exception ex)
{
MessageBox.Show("Error Scanning Previous Invoice" + "\n" + errorlevel); // + " / " + this.ShiftDate.ToString() != null ? this.ShiftDate : "");
// MessageBox.Show(ex.Message.ToString() + " / " + ex.InnerException.ToString());
}
}
protected virtual void GetOptions()
{
string Folder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
XDocument xDocument = XDocument.Load(string.Concat(Folder, "\\options.xml"));
this._scannedInvoice = xDocument.Element("root").Element("scannedInvoice").Value;
this._scanLogs = xDocument.Element("root").Element("scanLogs").Value;
this._autoCleanBuffer = Convert.ToBoolean(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("AutoCleanBuffer").Value);
this._automaticRecognition = Convert.ToBoolean(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("AutomaticRecognition").Value);
this._bitDepth = Convert.ToInt32(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("BitDepth").Value);
this._disableAfterAcquire = Convert.ToBoolean(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("DisableAfterAcquire").Value);
this._fileJpegQuality = Convert.ToInt32(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("FileJpegQuality").Value);
this._imageFilter = (ImageFilter)Enum.Parse(typeof(ImageFilter), xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("ImageFilter").Value);
this._modalUI = Convert.ToBoolean(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("ModalUI").Value);
this._noiseFilter = (NoiseFilter)Enum.Parse(typeof(NoiseFilter), xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("NoiseFilter").Value);
this._pixelFlavor = (PixelFlavor)Enum.Parse(typeof(PixelFlavor), xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("PixelFlavor").Value);
this._pixelType = (PixelType)Enum.Parse(typeof(PixelType), xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("PixelType").Value);
this._resolution = (float)Convert.ToInt32(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("Resolution").Value);
this._showIndicators = Convert.ToBoolean(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("ShowIndicators").Value);
this._showUI = Convert.ToBoolean(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("ShowUI").Value);
this._threshold = (float)Convert.ToInt32(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("Threshold").Value);
this._transferMode = (TransferMode)Enum.Parse(typeof(TransferMode), xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("TransferMode").Value);
this._unitOfMeasure = (Vintasoft.Twain.UnitOfMeasure)Enum.Parse(typeof(Vintasoft.Twain.UnitOfMeasure), xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("UnitOfMeasure").Value);
this._pdfMultiPage = Convert.ToBoolean(xDocument.Element("root").Element("Peripherals").Element("BatchScanner").Element("PdfMultiPage").Value);
}
private void InitScanDirection()
{
this._barcodeReader.Settings.ScanDirection = ScanDirection.LeftToRight;
}
protected IBarcodeInfo[] ReadBarcodes(Bitmap bmp)
{
this.SetBarcodeTypes();
this._barcodeReader.Settings.AutomaticRecognition = this._automaticRecognition;
this._barcodeReader.Settings.ScanDirection = ScanDirection.LeftToRight;
IBarcodeInfo[] iBarcodeInfos = this._barcodeReader.ReadBarcodes(bmp);
if (iBarcodeInfos.Count<IBarcodeInfo>() <= 0)
{
this._barcodeReader.Settings.ScanDirection = ScanDirection.BottomToTop;
iBarcodeInfos = this._barcodeReader.ReadBarcodes(bmp);
if (iBarcodeInfos.Count<IBarcodeInfo>() <= 0)
{
this._barcodeReader.Settings.ScanDirection = ScanDirection.RightToLeft;
iBarcodeInfos = this._barcodeReader.ReadBarcodes(bmp);
if (iBarcodeInfos.Count<IBarcodeInfo>() <= 0)
{
this._barcodeReader.Settings.ScanDirection = ScanDirection.TopToBottom;
iBarcodeInfos = this._barcodeReader.ReadBarcodes(bmp);
if (iBarcodeInfos.Count<IBarcodeInfo>() <= 0)
{
// no barcode found
_noBarcode = true;
return iBarcodeInfos;
}
else
{
_noBarcode = false;
return iBarcodeInfos;
}
}
else
{
_noBarcode = false;
return iBarcodeInfos;
}
}
else
{
_noBarcode = false;
return iBarcodeInfos;
}
}
else
{
_noBarcode = false;
return iBarcodeInfos;
}
}
private void SetBarcodeTypes()
{
BarcodeType scanBarcodeTypes = (BarcodeType)((long)0);
scanBarcodeTypes = scanBarcodeTypes | (BarcodeType)((long)4);
scanBarcodeTypes = scanBarcodeTypes | (BarcodeType)((long)32);
this._barcodeReader.Settings.ScanBarcodeTypes = scanBarcodeTypes;
}
protected string RemoveLeadingZeros(string s)
{
char[] charsToTrim = { '0' };
string nvarchar = s;
string newString = nvarchar.TrimStart(charsToTrim);
return newString;
}
private void RemoveDuplicates(ref ListBox listBox1)
{
// if item is empty or duplicate, remove it. only works for sorted listbox
listBox1.Sorted = true;
listBox1.Refresh();
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
if (listBox1.Items[i].ToString().Trim() == "")
listBox1.Items.RemoveAt(i);
else
if (listBox1.Items.IndexOf(listBox1.Items[i].ToString()) < i)
listBox1.Items.RemoveAt(i);
}
}
}
}