Tuesday, November 9, 2010

Image to Base64

I recently wanted to add small icon images to a project and i wonderd if there wasnt a beter solotion to storing small icon images inside a data base for quick retrieval.

So i found a solution to convert a image to base64 on www.dailycoding.com I took the code from www.dailycoding.com and add a few of my code just make more sense of whats going on.

There are two methods ImageToBase64 and Base64ToImage i will only be using ImageToBase64 and I think the description comes with the name.

In the Page_Load event I made use of two properties (Base64Image and Base64Start) to build the image for display there has to be "data:image/gif;base64," in front of the base64 string to display it as an image and this is stored in the Base64Start. lastly I displayed the image and text

The only downside to base64 is that it makes the files increasingly larger than binary format but it is easier/safer to Send file data. For example if you want to send file to another server using a web service or ftp base64 will be beater because it is less likely that data will be lost




public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //create image from full path
            System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath("list.gif"));

            //Create base64 and store in property
            Base64Image = ImageToBase64(image, System.Drawing.Imaging.ImageFormat.Gif);

            //Display image and string
            imgMyImage1.ImageUrl = String.Format("{0}{1}", Base64Start, Base64Image);
            lblBase64Text.Text = Base64Image;
        }

        public string ImageToBase64(System.Drawing.Image image,
            System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }

        public System.Drawing.Image Base64ToImage(string base64String)
        {
            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0,
              imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
            return image;
        }

        private String base64Image;
        public String Base64Image
        {
            get 
            {
                return base64Image;
            }
            set 
            {
                base64Image = value;
            }
        }

        public String Base64Start
        {
            get 
            { 
                return "data:image/gif;base64,";
            }
        }
    }


    

The output will be displayed as following

Base64 displayed as Image :



Base64 displayed as full text :

R0lGODlhDgAOAPAAAFRWVPz+/CwAAAAADgAOAAACFoyPqcttAF2AQFJ5rtONJ7+AioiVRwEAOw==


Source Code

Monday, November 8, 2010

Hierarchical Data Population

Populating Herarchial data from a table can sometimes get really tricky its not the hardest thing to do but it is something to remember.

The perfict example will be to populate data from a table that has a PK ID a ParentId that shows the which Parent Id the row belongs to and the Name.

In this example I wont be using a SQL Table but a Object List.





Cosider the following




private List<String> menu = new List<String>();
        private List<MenuItem> menuList = new List<MenuItem>();
        private Boolean flag = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadMenu();

            BuildMenu(0);

            foreach (String item in menu)
            {
                litMenu.Text += item;
            }
        }

        private void LoadMenu()
        {
            //List of MenuItem        ID |ParentId  |Name
            //------------------------------------------------------
            menuList.Add(new MenuItem(1,  0,        "Home"));
            menuList.Add(new MenuItem(2,  0,        "Contact Us"));
            menuList.Add(new MenuItem(3,  0,        "About Us"));
            menuList.Add(new MenuItem(4,  1,        "Profile"));
            menuList.Add(new MenuItem(5,  1,        "Goal"));
            menuList.Add(new MenuItem(6,  2,        "Send Mail"));
            menuList.Add(new MenuItem(7,  3,        "What we do"));
            menuList.Add(new MenuItem(8,  7,        "Skinning"));
            menuList.Add(new MenuItem(9,  7,        "Milking"));
            menuList.Add(new MenuItem(10, 3,        "What we wont do"));
        }

        private void BuildMenu(int ParentId)
        {
            List<MenuItem> newList = (from p in menuList
                                      where p.ParentId == ParentId
                                      select p).ToList<MenuItem>();

            if (newList.Count > 0)
            {
                for (int i = 0; i < newList.Count; i++)
                {
                    if (i == 0)
                    {
                            menu.Add("<ul>");
                    }

                    menu.Add("<li>");
                    menu.Add(newList[i].MenuName);
                    BuildMenu(newList[i].ID);
                    menu.Add("</li>");

                    if (i == newList.Count - 1)
                    {
                        menu.Add("</ul>");
                    }

                }
            }
        }
    
The ouput from the object list will be displayed as following
  • Home
    • Profile
    • Goal
  • Contact Us
    • Send Mail
  • About Us
    • What we do
      • Skinning
      • Milking
    • What we wont do
Source Code