If you want to export images from a SQL Server database you could use the following code:

        public void ExportImagesFromDatabase()
        {
            var exportPath = @"C:\Temp";
            if (!Directory.Exists(exportPath))
            {
                Directory.CreateDirectory(exportPath);
            }
            var imagesTable = GetImagesFromDatabase("select [ImageColumn] from [ImageTable]");
            var rowCounter = 0;
            foreach (DataRow row in imagesTable.Rows)
            {
                if (row.ItemArray.Length > 0)
                {
                    if (row[0] != null)
                    {
                        var imageBytes = (byte[])row["Image"];
                        if (imageBytes.Length > 0)
                        {
                            using (var convertedImage = new Bitmap(new MemoryStream(imageBytes)))
                            {
                                var fileName = Path.Combine(exportPath, string.Format("ExportImage_{0}.bmp", rowCounter.ToString().PadLeft(5, '0')));
                                if (File.Exists(fileName))
                                {
                                    File.Delete(fileName);
                                }
                                convertedImage.Save(fileName);
                            }
                        }
                    }
                }
            }
        }
        public DataTable GetImagesFromDatabase(string query)
        {
            if (string.IsNullOrEmpty(query))
            {
                throw new NullReferenceException("Parameter query can't be null or empty");
            }
            var result = new DataTable();
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Runner"].ConnectionString))
            {
                using (var command = new SqlCommand(query, connection))
                {
                    connection.Open();
                    command.CommandTimeout = 0;
                    command.CommandType = CommandType.Text;

                    using (var adapter = new SqlDataAdapter(command))
                    {
                        var recordCount = adapter.Fill(result);
                    }
                }
            }

            return result;
        }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.