none
Read a text file and convert the contents into a jpg to save to the database RRS feed

  • Question

  • I currently watch a folder for incoming .txt files using the watcher class, when a file arrives I use the File.ReadAllLines to a List<string>, I iterate through the list to get data from certain lines which I then upload to my database using SqlConnection.

    How can I convert the file contents to an image to store a copy of the original file in my database?


       

    CuriousCoder

    Tuesday, August 7, 2018 11:55 AM

Answers

  • Hi CuriousCoder15,

    Thank you for posting here.

    For your question, you could try the below to read data from .txt file and then convert it to image. 

            public static Bitmap Convert_Text_to_Image(string txt, string fontname, int fontsize)
            {
                //creating bitmap image
                Bitmap bmp = new Bitmap(1, 1);
    
                //FromImage method creates a new Graphics from the specified Image.
                Graphics graphics = Graphics.FromImage(bmp);
                // Create the Font object for the image text drawing.
                Font font = new Font(fontname, fontsize);
                // Instantiating object of Bitmap image again with the correct size for the text and font.
                SizeF stringSize = graphics.MeasureString(txt, font);
                bmp = new Bitmap(bmp, (int)stringSize.Width, (int)stringSize.Height);
                graphics = Graphics.FromImage(bmp);
    
                /* It can also be a way
               bmp = new Bitmap(bmp, new Size((int)graphics.MeasureString(txt, font).Width, (int)graphics.MeasureString(txt, font).Height));*/
    
                //Draw Specified text with specified format 
                graphics.DrawString(txt, font, Brushes.Red, 0, 0);
                font.Dispose();
                graphics.Flush();
                graphics.Dispose();
                return bmp;     //return Bitmap Image 
            }

    How do you want to save it to database?

    1. If you want to insert using T-SQL, please refer to the following T-SQL language.

    insert into tableName (ImageColumn) 
    SELECT BulkColumn 
    FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img

    2. If you want to store using C#, please try the code below.

     public static void Save_Image_To_Database(string ImagePath)
            {
                string strConn = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\wendyz.WICRESOFT.000\OneDrive\Projects\VS2017 Project\ConsoleApp\ConsoleApp\Database.mdf;Integrated Security=True;Connect Timeout=30";
                FileInfo fi = new FileInfo(ImagePath);
                using (FileStream fs = fi.OpenRead())
                {
                    byte[] bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                    using (SqlConnection cn = new SqlConnection(strConn))
                    {
                        cn.Open();
                        using (SqlCommand cm = new SqlCommand())
                        {
                            cm.Connection = cn;
                            cm.CommandType = CommandType.Text;
                            cm.CommandText = "insert into Image (Image) values(@file)";
                            SqlParameter spFile = new SqlParameter("@file", SqlDbType.Image);
                            spFile.Value = bytes;
                            cm.Parameters.Add(spFile);
                            cm.ExecuteNonQuery();
                        }
                    }
                }
            }

    Here is the invoke for these two methods.

     public static void Main(string[] args)
            {
                string txt = File.ReadAllText("Test.txt");
                string ImagePath = "Save.jpg";
                Bitmap bit = Convert_Text_to_Image(txt, "Bookman Old Style", 20);
                bit.Save(ImagePath);
                Save_Image_To_Database(ImagePath);
            }

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, August 8, 2018 8:20 AM
    Moderator

All replies

  • Here is an example using stored procedures, you could always use the statements in the SP's in your code rather than use SP's.

    https://code.msdn.microsoft.com/INSERT-Image-into-SQL-29dfc8ee?redir=0


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, August 7, 2018 12:33 PM
    Moderator
  • Thanks for your reply, It's the converting the text file to an image that I was looking for, the reading and uploading to the database I can do.

    Many Thanks


    CuriousCoder

    Tuesday, August 7, 2018 2:32 PM
  • Do you mean how to use Graphics.DrawString in a loop and other functions to make a black-and-white image that contains just the text?


    Tuesday, August 7, 2018 6:41 PM
  • Hi CuriousCoder15,

    Thank you for posting here.

    For your question, you could try the below to read data from .txt file and then convert it to image. 

            public static Bitmap Convert_Text_to_Image(string txt, string fontname, int fontsize)
            {
                //creating bitmap image
                Bitmap bmp = new Bitmap(1, 1);
    
                //FromImage method creates a new Graphics from the specified Image.
                Graphics graphics = Graphics.FromImage(bmp);
                // Create the Font object for the image text drawing.
                Font font = new Font(fontname, fontsize);
                // Instantiating object of Bitmap image again with the correct size for the text and font.
                SizeF stringSize = graphics.MeasureString(txt, font);
                bmp = new Bitmap(bmp, (int)stringSize.Width, (int)stringSize.Height);
                graphics = Graphics.FromImage(bmp);
    
                /* It can also be a way
               bmp = new Bitmap(bmp, new Size((int)graphics.MeasureString(txt, font).Width, (int)graphics.MeasureString(txt, font).Height));*/
    
                //Draw Specified text with specified format 
                graphics.DrawString(txt, font, Brushes.Red, 0, 0);
                font.Dispose();
                graphics.Flush();
                graphics.Dispose();
                return bmp;     //return Bitmap Image 
            }

    How do you want to save it to database?

    1. If you want to insert using T-SQL, please refer to the following T-SQL language.

    insert into tableName (ImageColumn) 
    SELECT BulkColumn 
    FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img

    2. If you want to store using C#, please try the code below.

     public static void Save_Image_To_Database(string ImagePath)
            {
                string strConn = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\wendyz.WICRESOFT.000\OneDrive\Projects\VS2017 Project\ConsoleApp\ConsoleApp\Database.mdf;Integrated Security=True;Connect Timeout=30";
                FileInfo fi = new FileInfo(ImagePath);
                using (FileStream fs = fi.OpenRead())
                {
                    byte[] bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                    using (SqlConnection cn = new SqlConnection(strConn))
                    {
                        cn.Open();
                        using (SqlCommand cm = new SqlCommand())
                        {
                            cm.Connection = cn;
                            cm.CommandType = CommandType.Text;
                            cm.CommandText = "insert into Image (Image) values(@file)";
                            SqlParameter spFile = new SqlParameter("@file", SqlDbType.Image);
                            spFile.Value = bytes;
                            cm.Parameters.Add(spFile);
                            cm.ExecuteNonQuery();
                        }
                    }
                }
            }

    Here is the invoke for these two methods.

     public static void Main(string[] args)
            {
                string txt = File.ReadAllText("Test.txt");
                string ImagePath = "Save.jpg";
                Bitmap bit = Convert_Text_to_Image(txt, "Bookman Old Style", 20);
                bit.Save(ImagePath);
                Save_Image_To_Database(ImagePath);
            }

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, August 8, 2018 8:20 AM
    Moderator
  • Hi,

    yes, that's it. Do I need to write the contents of my List<string> to a Listbox to and save the ListBox to a new text file then read the new image file into my program to upload it to my database or is there a more efficient way?


    CuriousCoder

    Wednesday, August 8, 2018 8:23 AM
  • Thank you, Wendy,

    That is a really detailed answer, a lot more efficient than the way I thought I might have to do it.

    Great.

    Thanks again. :D


    CuriousCoder

    Wednesday, August 8, 2018 8:37 AM