so. i downloaded a dll of the net and im trying parse data through it.
this bit of code i pretty much ported from VB so i expect a reason its not working for me is the syntax is incorrect. iv tried to make it as c# as i know how. but no joy. i get 'canot convert image to bitmap' on line 2, error on line 3, and empty statement error on 'if (barcodes.Count > 0);' and bC not defined i think.
help please:)

ArrayList barcodes = new ArrayList();
            BarcodeImaging.FullScanPageCode39(ref barcodes, pictureBox1.Image, 10);
            bC as object;
            //check data is in array, show msgbox and put result in lblResult else show msgbox (no code found)
            if (barcodes.Count > 0);
            {
                MessageBox.Show("barcode found :)");
                lblResult.Text = bC;
            }
            MessageBox.Show("No Barcode Found :(");

the VB code i took it from:

Private Sub MenuItem6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem6.Click
        If Not Me.PictureBox1.Image Is Nothing Then
            Dim barcodes As New System.Collections.ArrayList

            BarcodeImaging.FullScanPageCode39(barcodes, Me.PictureBox1.Image, 10)

            If barcodes.Count > 0 Then
                Dim Message As String = "Found barcodes:" & vbNewLine
                Dim bc As Object
                For Each bc In barcodes
                    Message = Message & bc & vbNewLine
                Next
                MsgBox(Message, MsgBoxStyle.OKOnly)
            Else
                MsgBox("Failed to find a barcode")
            End If
            Me.Refresh()
        End If
    End Sub

Recommended Answers

All 8 Replies

Here is a C# translation:

private void MenuItem6_Click(Object sender, EventArgs e) {
    if ((this.PictureBox1.Image != null)) {
        ArrayList barcodes = new ArrayList();

        BarcodeImaging.FullScanPageCode39(barcodes, this.PictureBox1.Image, 10);

        if (barcodes.Count > 0) {
            StringBuilder message = new StringBuilder();
            message.Append("Found barcodes:" + Environment.NewLine);
            foreach (object bc in barcodes) {
                message.Append(bc.ToString() + Environment.NewLine);
            }
            MessageBox.Show(message.ToString(), MessageBoxButtons.OK);
        } else {
            MessageBox.Show("Failed to find a barcode");
        }
        this.Refresh();
    }
}

Without knowing more about BarCodeImaging I don't know if line 5 is what it wants. Also line 10 most likely has a better type than 'object' for use, probably 'barcode' but again I know nothing about your barcode library.

sure. thankyou. i dont really know what to tell you. ur code looks good. iv put it in to my code and for some reason its come back saying pictureBox1 does not contain a definition and it doesnt like line 13. here is a bit from barcodeimaging.cs

public static void FullScanPageCode39(ref System.Collections.ArrayList CodesRead, Bitmap bmp, int numscans)
{
	for (int i=0; i<4; i++)
	{
		bmp.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
		VScanPageCode39(ref CodesRead, bmp,numscans);
	}
}

public static void VScanPageCode39(ref System.Collections.ArrayList CodesRead, Bitmap bmp, int numscans)
{
	string read;
	bool test;
	for (int i=0;i<numscans;i++)
	{
		read = ReadCode39(bmp,i * (bmp.Height / numscans), (i * (bmp.Height / numscans))+ (bmp.Height / numscans));
			
		test = false;
		foreach (object tester in CodesRead)
		{
			if ((tester.ToString() == read) || (read.Trim() == "")) test=true;
		}
		if (!(test)) CodesRead.Add(read);
	}
}

I changed a bit your code, but I dont know what "ReadCode" on line 26 from the code bellow, would be. So I couldnt test it:

static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add("Test1");
            list.Add("Test2");
            Bitmap bmp = new Bitmap(@"C:\myTestPic.jpg", true);
            int numScans = 2;
            FullScanPageCode39(list, bmp, numScans);
        }

        public static void FullScanPageCode39(ArrayList CodesRead, Bitmap bmp, int numscans)
        {
            for (int i = 0; i < 4; i++)
            {
                bmp.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                VScanPageCode39(CodesRead, bmp, numscans);
            }
        }

        public static void VScanPageCode39(ArrayList CodesRead, Bitmap bmp, int numscans)
        {
            string read;
            bool test;
            for (int i = 0; i < numscans; i++)
            {
                read = ReadCode39(bmp, i * (bmp.Height / numscans), (i * (bmp.Height / numscans)) + (bmp.Height / numscans));

                test = false;
                foreach (object tester in CodesRead)
                {
                    if ((tester.ToString() == read) || (read.Trim() == "")) test = true;
                }
                if (!(test)) CodesRead.Add(read);
            }
        }

http://www.codeproject.com/KB/graphics/barcodeimaging2.aspx

here is a link to where i got the file from. i believe its open source so we're aloud to download it. the code u changed came from the dll i think, not what i coded. im still learning. i just added it as a reference and looked through the code to try and discern what i had to parse to it to make it work. being a complete novice i have failed i guess.
i hope its not to much to ask for u to have a little look and tell me where i went wrong. as i said b4. the code is in VB and i tried to import it to c#
i also hope im not breaking any forum rules by putting a link in my post.
thanks for your time on this.
steve

here is more of the code from the dll. the is another part to the codewhich contains all the barcode outputs if u want that to.

public static string ReadCode39(Bitmap bmp, int startheight, int endheight)
	{
		// To find a horizontal barcode, find the vertical histogram to find individual barcodes, 
		// then get the vertical histogram to decode each
		histogramResult vertHist = verticalHistogram(bmp,startheight,endheight);
		// Set the threshold for determining dark/light bars to half way between the histograms min/max
		float threshold = vertHist.min + ((vertHist.max - vertHist.min)/2);
		// Variables needed to check for
		string patternString = "";
		int nBarStart = -1;
		int nNarrowBarWidth = -1;
		bool bDarkBar = false;
		// Find the narrow and wide bars
		for (int i = 0; i < vertHist.histogram.Length; ++i)
		{
			// First find the narrow bar width
			if (nNarrowBarWidth < 0)
			{
				if (nBarStart < 0)
				{
					// The code doesn't start until we see a dark bar
					if (vertHist.histogram[i] <= threshold)
					{
						// We detected a dark bar, save it's start position
						nBarStart = i;
					}
				}
				else
				{
					if (vertHist.histogram[i] > threshold)
					{
						// We detected the end of first the dark bar, save the narrow bar width and 
						// start the rest of the barcode  
						nNarrowBarWidth = i - nBarStart + 1;
						patternString += "n";
						nBarStart = i;
						bDarkBar = false;
					}
				}
			}
			else
			{
				if (bDarkBar)
				{
					// We're on a dark bar, detect when the bar becomes light again
					if (vertHist.histogram[i] > threshold)
					{
						if ((i-nBarStart) > (nNarrowBarWidth))
						{
							// The light bar was wider than the narrow bar width, it's a wide bar
							patternString += "w";
							nBarStart = i;
						}
						else
						{
							// The light bar is a narrow bar
							patternString += "n";
							nBarStart = i;
						}
						bDarkBar = false;
					}
				}
				else
				{
					// We're on a light bar, detect when the bar becomes dark
					if (vertHist.histogram[i] <= threshold)
					{
						if ((i-nBarStart) > (nNarrowBarWidth))
						{
							// The dark bar was wider than the narrow bar width, it's a wide bar
							patternString += "w";
							nBarStart = i;
						}
						else
						{
							// The dark bar is a narrow bar
							patternString += "n";
							nBarStart = i;
						}
						bDarkBar = true;
					}
				}
			}
		}

		// We now have a barcode in terms of narrow & wide bars... Parse it!
		string dataString = "";

		// Each pattern within code 39 is nine bars with one white bar between each pattern
		int index=0;
		string somedata;
		if (patternString.Length > 9)
		{
			while (index<patternString.Length-8)
			{
				// Create an array of charachters to hold the pattern to be tested
				char[] pattern = new char[9];
				// Stuff the pattern with data from the pattern string
				patternString.CopyTo(index,pattern,0,9);
		
				somedata= parsePattern(new string(pattern));
				dataString += somedata;

				if (somedata == null)
				{
					index++;
				} 
				else 
				{
					index += 10;
				}
			}
		}

		return dataString;
	}

		/// <summary>
		/// Vertical histogram of an image
		/// </summary>
		/// <param name="bmp">the bitmap to be processed</param>
		/// <param name="showDiagnostics">if true, draws an overlay on the image</param>
		/// <param name="diagnosticsColor">the color of the overlay</param>
		/// <returns>a histogramResult representing the vertical histogram</returns>
		private static histogramResult verticalHistogram(Bitmap bmp, int startheight, int endheight)
		{
			// Create the return value
			float[] histResult = new float[bmp.Width]; 
			
			float[] vertSum = new float[bmp.Width];
			// Start the max value at zero
			float maxValue = 0;
			// Start the min value at the absolute maximum
			float minValue = 255;

			// GDI+ still lies to us - the return format is BGR, NOT RGB.
			BitmapData bmData = bmp.LockBits(new Rectangle(0, startheight, bmp.Width, endheight - startheight), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
			
				
		

			int stride = bmData.Stride;
			System.IntPtr Scan0 = bmData.Scan0;

			unsafe
			{
				
				byte * p = (byte *)(void *)Scan0;
				
				int nOffset = stride - bmp.Width*3;
				int nWidth = bmp.Width * 3;

				for(int y=startheight;y<endheight;++y)
				{
					for(int x=0; x < bmp.Width; ++x )
					{
						// Add up all the pixel values vertically (average the R,G,B channels)
						vertSum[x] += ((p[0] + (p+1)[0] + (p+2)[0])/3);
						
						p+=3;
					}
					p += nOffset;
				}
			}

			bmp.UnlockBits(bmData);

			// Now get the average of the row by dividing the pixel by num pixels
			for(int i=0; i<bmp.Width; i++)
			{
				histResult[i] = (vertSum[i] / (endheight - startheight));
				//Save the max value for later
				if (histResult[i] > maxValue) maxValue = histResult[i];
				// Save the min value for later
				if (histResult[i] < minValue) minValue = histResult[i];
			}
			
			histogramResult retVal = new histogramResult();
			retVal.histogram = histResult;
			retVal.max = maxValue;
			retVal.min = minValue;
			return retVal;
		}

This code is incomplete, as is the project you have found on the codeprocejct.com.
There is missinf main() method and some parameters.

This is the 1st method which can be called from the Main() method:

public static void FullScanPageCode39(ArrayList CodesRead, Bitmap bmp, int numscans){}

ok well iv been looking arround the net a bit and have found another imaging project. tho the test vb code compiles and runs for me and the demo app works, is it missing an important method for c then. it seems like the only problem im having when trying to build my project is an error ' cannot implicitly convert system.drawing.image to ......bitmap. iv tried using "bitmap bmp = pictureBox1.image" but still i get the same error. how do i convert the contents of a picture box to bitmap?

well managed to get this function working in the end. i just wasnt parsing the bitmap properly and had the syntax wrong (marked in red) anyway thanks for ur help guys

private void btnScan_Click(object sender, EventArgs e)
        {
            btnScan.Text = "Scaning!";
            if ((this.pictureBox1.Image != null)) 
            { 
                
                ArrayList barcodes = new ArrayList();

                Bitmap bmp = new Bitmap(pictureBox1.Image); 
                BarcodeImaging.FullScanPageCode39(ref barcodes, bmp, 10);
                                
                if (barcodes.Count > 0) 
                { 
                    StringBuilder message = new StringBuilder();
                    message.Append("Found barcodes:" + Environment.NewLine);
                    foreach (object bc in barcodes) 
                    { 
                        message.Append(bc.ToString() + Environment.NewLine);
                    } 
                    MessageBox.Show(message.ToString());//, MessageBoxButtons.OK);
                    string result = message.ToString();
                    //    String[] codeArray = codeView.Split(new char[] { '*' });
                    string[] nResult = result.Split(new string[]{ "*" }, StringSplitOptions.RemoveEmptyEntries);

                    lblResult.Text = nResult.ToString() ;
                } else 
                { 
                    MessageBox.Show("Failed to find a barcode"); 
                }
                this.Refresh(); 
                btnScan.Text = "Scan For Code";
            }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.