Bee Eee Blog

c# getting rid of the jitter!

by brian on Apr.18, 2008, under .NET, GUI, c#, c# coding GUI, coding, graphics

I recently was getting greatly annoyed with some drawing code in my program.  I was drawing a photo that I could zoom and move around.  When I zoomed with the wheel though it would briefly draw the image in two positions.  The first position after it was zoomed, and the second position after it was re-centered on the screen.  Well this looked awful.  Not exactly professional looking.  So I tried a hundered different things.  I tried setting a bool variable in the control to tell the paint function not to draw.  No good.  The drawing was done with asynchronous messages.  Then I tried  BeginInvoke.  That didn’t work also.  I tried SuspendLayout and ResumeLayout functions of the Control class:  No good.  Finally I just used the Visible property which kind of worked, well I didn’t get the double picture, but my background was light color and the foreground dark, so there was still a bad looking flicker.  After a couple of hours I finally found the solution at: http://weblogs.asp.net/jdanforth/archive/2004/03/12/88458.aspx. I worked on the example a little and boiled it down to two functions: StopDrawing and StartDrawing.

The techinque basically turns of drawing and events to the object on the win32 level underneath .Net.  This is very handy and it worked very very well.  Here is the code.

        using System.Runtime.InteropServices;
        private const int WM_SETREDRAW      = 0x000B;
        private const int WM_USER           = 0x400;
        private const int EM_GETEVENTMASK   = (WM_USER + 59);
        private const int EM_SETEVENTMASK   = (WM_USER + 69);

        [DllImport("user32", CharSet = CharSet.Auto)]
        private extern static IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam);

        IntPtr eventMask = IntPtr.Zero;

        public void StopDrawing()
        {
            if (drawStopCount == 0)
            {
                // Stop redrawing:
                SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero);
                // Stop sending of events:
                eventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);
            }
            drawStopCount++;
        }

        public void StartDrawing()
        {
            drawStopCount--;
            if (drawStopCount == 0)
            {
                // turn on events
                SendMessage(this.Handle, EM_SETEVENTMASK, 0, eventMask);

                // turn on redrawing
                SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero);

                Invalidate();
                Refresh();
            }
        }
Leave a Comment :, , , , more...

c# open an URL programatically

by brian on Apr.15, 2008, under .NET, c#, coding

Here is the easy way to open the browser from a c# .Net application.

string url="http://blog.bee-eee.com";
System.Diagnostics.Process.Start(url);

There you go. Pretty easy uh.

2 Comments :, , more...

c# joining an array of strings.

by brian on Apr.14, 2008, under .NET, c#, coding

Here the easy way to get comma’s between each of the items in an array in a string.

string[] string_array=new string[]{"1","2","3","4"};
String.Join(",",string_array)

The output is:

1,2,3,4
Leave a Comment :, , more...

c# Command Line Arguments

by brian on Apr.14, 2008, under .NET, Uncategorized, c#, coding

Here’s how you access the command line arguments:

string[] argv = Environment.GetCommandLineArgs();
Leave a Comment : more...

c# drawing outlined text.

by brian on Mar.20, 2008, under .NET, GUI, c#, c# coding GUI, graphics

Here is a little nice bit of code to get text to jump out at you no matter what the background.  Outlined text is especially useful when putting text on an image and don’t have control of the background contrast. Basically it draws a black boarder with a while fill.

// prepare to draw text

StringFormat sf = new StringFormat();

sf.Alignment = StringAlignment.Center;

sf.LineAlignment = StringAlignment.Center;// draw the text to a path

System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();

path.AddString(text, Font.FontFamily, 0, 14.0f, fillRect, sf);

// fill in the outline

g.FillPath(Brushes.White, path);

// draw the outline

g.DrawPath(new Pen(Color.Black,2.0f) , path);
1 Comment : more...

c# reading Tiff using libtiff

by brian on Mar.20, 2008, under c#, c# coding GUI, graphics

Here is the promised code for reading Tiffs.  I make no claim that this code will read all TIFF files that would be quite the accomplishment indeed.  Because of time constraints,  I’m just going to cut this right out of the application I’m writing.  As way of explanation the class ImageArray is basically an array of pixels wrapped around a class.  A pixel here is a class that consists of r,g,b colors and a few other things.  In my last post I had some of the libtiff header defined.  I’m going to skip that here
and just post the code.
public static ImageArray LoadTiff(String Image_Path)
{
    ImageArray arr = null;
    unsafe
    {
        UInt32 w = 0;
        UInt32 h = 0;
        uint samples = 3;
        uint bits = 8;
        int i, j, ptr, lptr;

        int tif = TIFFOpen(Image_Path, "r");

        if (0 != tif)
        {
            TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, ref w);
            TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ref h);
            TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, ref bits);
            TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, ref samples);
            arr = new ImageArray((int)w, (int)h);

            // make sure we get all of the data.
            if (bits == 16)
            {
                UInt32 size = w;
                ushort* raster = (ushort *)_TIFFmalloc((uint)(size * sizeof(ushort) * samples));
                // read in all of the lines
                for (j = 0; j < h; j++)
                {
                    TIFFReadScanline(tif, (byte *)raster, j, 0);
                    // copy line into data
                    for (i = 0, ptr=0; i < w; i++, ptr+=(int)samples)
                    {
                        if (samples == 3)
                        {
                            arr.Data[i + j * w].SetPixel(raster[i], raster[i + 1], raster[i + 2]);
                        }
                        else
                        {
                            ushort val = raster[i + samples - 1];
                            arr.Data[i + j * w].SetPixel(val,val,val);
                        }
                    }
                }

                _TIFFfree((byte *)raster);
            }
            else
            {
                // anything beside 16 bit
                UInt32 size = h * w;
                byte *raster = _TIFFmalloc( size );
                int val = TIFFReadRGBAImage(tif, w, h, raster, 0);
                // copy image data into a bitmap
                if (val != 0)
                {
                    for (j = 0, ptr = 0, lptr=0; j < h; j++)
                    {
                        for (i = 0; i < w; i++, ptr+=4, ptr++)
                        {
                            arr.Data[ptr].SetPixel((ushort)raster[lptr], (ushort)raster[lptr + 1], (ushort)raster[lptr + 2]);
                        } // for i
                    } // for j
                } // if val

                _TIFFfree(raster);
            }
            TIFFClose(tif);
        } // if tif
    } // unsafe

    return arr;
}
4 Comments : more...

c# writing out a Tiff File using libtiff

by brian on Mar.12, 2008, under GUI, c#, c# coding GUI, coding, graphics

Tiff files are interesting.  They are like the all inclusive file format.  It is an extremely flexible file format that allows for many types of pixel formats that other image formats couldn’t possibly handle.  For instance 16 bits per channel or sample in the Tiff lingo.  Event the possibility of 4 or 5 samples per pixel.  If you wanted you could have a Red, Green, Blue, IR, Alpha channel.  Although software would have a difficult time displaying the image.  Anyway I digress — tiff being somewhat flexible is also some what difficult to manage, this is where libtiff comes in handy.  It handles most of this for us.


The first step is to add using System.Runtime.InteropServices; to you module. Then add the stubs for the libtiff functions as follows:

    static class TiffHandler
    {
        [DllImport("libtiff3.dll")]
        private static extern int TIFFOpen(String image_path, String opts);
        [DllImport("libtiff3.dll")]
        private static extern void TIFFClose(int handle);
        [DllImport("libtiff3.dll")]
        private static extern void TIFFGetField(int handle, uint property, ref UInt32 value );
        [DllImport("libtiff3.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        private static extern int TIFFSetField(int handle, uint property, uint value);
        [DllImport("libtiff3.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        private static extern int TIFFSetField(int handle, uint property, string value);
        [DllImport("libtiff3.dll")]
        private unsafe static extern int TIFFReadRGBAImage(int handle, UInt32 width, UInt32 height, byte *raster, int Unkown);
        [DllImport("libtiff3.dll")]
        private unsafe static extern int TIFFReadEncodedStrip(int handle, int strip, byte* buf, int size);
        [DllImport("libtiff3.dll")]
        private unsafe static extern byte* _TIFFmalloc(UInt32 size);
        [DllImport("libtiff3.dll")]
        private unsafe static extern void _TIFFfree(byte* pointer);
        [DllImport("libtiff3.dll")]
        private unsafe static extern void TIFFWriteEncodedStrip(int handle, int offset, byte* buffer, int size);
        [DllImport("libtiff3.dll")]
        private static extern uint TIFFScanlineSize(int handle);
        [DllImport("libtiff3.dll")]
        private static extern int TIFFDefaultStripSize(int handle, int size);
        [DllImport("libtiff3.dll")]
        private unsafe static extern int TIFFWriteScanline(int handle, byte* buffer, int row, int sample);
        [DllImport("libtiff3.dll")]
        private unsafe static extern int TIFFReadScanline(int handle, byte* data, int row, int sample);

Next we add the constants. I’m not going to add them all there are thousands of them but here is an example of the ones that are used in writting a tiff. If you want more look in the libtiff header files. It seems like it’s in tiff.h

        const uint TIFFTAG_IMAGEWIDTH = 256;	/* image width in pixels */
        const uint TIFFTAG_IMAGELENGTH	= 257;	/* image height in pixels */
        const uint TIFFTAG_BITSPERSAMPLE = 258;	/* bits per channel (sample) */
        const uint TIFFTAG_SAMPLESPERPIXEL = 277;	/* samples per pixel */
        const uint TIFFTAG_COMPRESSION	= 259;	/* data compression technique */
        const uint COMPRESSION_DEFLATE	= 32946;	/* Deflate compression */
        const uint PHOTOMETRIC_RGB = 2;	/* RGB color model */
        const uint TIFFTAG_PLANARCONFIG = 284;	/* storage organization */
        const uint PLANARCONFIG_CONTIG	= 1;	/* single image plane */

And then the code to write out the image to a file:

        public static unsafe void SaveTiff(string fileName, ImageArray array)
        {
            int tif = TIFFOpen(fileName, "w");
            int Samples = 3;

            TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (uint)array.Width);
            TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (uint)array.Height);
            TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
            TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
            TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
            TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16);
            TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, (uint)Samples);
            TIFFSetField(tif, TIFFTAG_ARTIST, "Bee Eee Inventions, LLC");

            int cnt = array.Width * array.Height;
            int size = (cnt * Samples * sizeof(ushort));
            ushort* buffer;

            buffer = (ushort*)_TIFFmalloc((uint)size);

            // We set the strip size of the file to be size of one row of pixels
            //int RowSize = TIFFDefaultStripSize(tif, array.Width*3);

            // copy data into buffer
            int i,pos,ptr=0;
            for (i = 0, pos = 0; i < cnt; i++, pos += Samples, ptr++)
            {
                buffer[pos] =  (ushort)(array.Data[ptr].r);
                buffer[pos + 1] = (ushort)(array.Data[ptr].g);
                buffer[pos + 2] = (ushort)(array.Data[ptr].b);
            }

            // Write the information to the file
            TIFFWriteEncodedStrip(tif, 0, (byte *)buffer, size);

            TIFFClose(tif);

            _TIFFfree((byte *)buffer);
        }

Enjoy. Next article I’ll show you how to read some tiff files. Opening all tiff files could be difficult. :)

10 Comments : more...

O how beautiful!

by brian on Mar.10, 2008, under Uncategorized

“…Oh how beautiful upon the mountains are the feet of him that bringeth good tiding, that is the founder of peace, yea, even the Lord, who has redeemed his people; yea, him who has granted salvation unto his people…” Mosiah 15:18

“…being filled with compassion towards the children of men; standing betwixt [me] and justice; having broken the bands of death, taken upon himself [my] iniquity and [my] transgressions, having redeemed [me], and satisfied the demands of justice.” – Mosiah 15:9

He lives.  I testify of it.  I’ve felt His heavenward pull, His encouragement all my days!  I stand as a witness of Jesus Christ and of his love.  Follow where He leads for He only leads to happiness.  Beginning steps may be painful, but  always, always, his ways lead to happiness.

Leave a Comment more...

c# Measuring a String.

by brian on Feb.21, 2008, under .NET, GUI, c#, c# coding GUI

Often times it is desirable to draw a string with a System.Drawing.Graphics. My problem came when drawing text over an image. The image itself is dark but had light spots in it. This can make seeing the text very difficult. To fix the problem I fill a box behind the text. To do that I need to know how tall and wide the text will be.

The magic function is Graphics.MeasureString. This functions returns the calculated size of the string that is being drawn.

// measure the string
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Near;
sf.LineAlignment = StringAlignment.Near;
SizeF boundry = g.MeasureString(ToString(), font);

// draw the string
Rectangle textRect = new Rectangle(10, 10, (int)(boundry.Width + 2), (int)(boundry.Height + 2));
g.FillRectangle(Brushes.Black, textRect);
g.DrawRectangle(Pens.White, textRect);
g.DrawString(ToString(), font, Brushes.Yellow, textRect.X, textRect.Y, sf);
2 Comments : more...

C# Determining if a column exists in an SQL database using ADO.Net

by brian on Feb.15, 2008, under c#, coding

This information was very difficult to come by. There isn’t any useful documentation or tutorials that I found. I have to admit that what follows may only be valid for the System.Data.SQLite.SQLiteConnection sql connection. Just as a warning it may or may not work with a different database connection.


The idea is that you’ve changed your database layout and you want test the opened database to make sure the changes are valid. If they aren’t then you want to alter the table. Anyway here is the code

DataTable columns = connection.GetSchema("columns");
System.Data.DataRow[] selColumns = columns.Select("COLUMN_NAME='PREVIEW' AND TABLE_NAME='IMAGES'");
if (selColumns.Length == 0)
{
        ExecuteNonQuerySql("ALTER TABLE IMAGES ADD COLUMN PREVIEW BLOB");
}

The following line gets the schema table that holds all of the columns from every table.

DataTable columns = connection.GetSchema("columns");

The following line filters through all of the columns and get’s just the column with name ‘PREVIEW’ and belongs to the table ‘IMAGES’.

System.Data.DataRow[] selColumns = columns.Select("COLUMN_NAME='PREVIEW' AND TABLE_NAME='IMAGES'");

If there are any columns that fit the filter than the length of selColumns will be greater than zero. If it doesn’t exist than selColumns.Length will be 0 and you know that the column doesn’t exist.

1 Comment : more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...