Csharp/CSharp Tutorial/ADO.Net/Image Load Save

Материал из .Net Framework эксперт
Версия от 12:19, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Display image

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.IO;
public class DisplayImages : Form
{
    public DisplayImages()
    {
        InitializeComponent();
        images = new Images();
        if (images.GetRow())
        {
            this.textBox1.Text = images.GetFilename();
            this.pictureBox1.Image = (Image)images.GetImage();
        }
        else
        {
            this.textBox1.Text = "DONE";
            this.pictureBox1.Image = null;
        }
    }
    private void button1_Click(object sender, EventArgs e)
    {
        if (images.GetRow())
        {
            this.textBox1.Text = images.GetFilename();
            this.pictureBox1.Image = (Image)images.GetImage();
        }
        else
        {
            this.textBox1.Text = "DONE";
            this.pictureBox1.Image = null;
        }
    }
    private void InitializeComponent()
    {
        this.button1 = new System.Windows.Forms.Button();
        this.textBox1 = new System.Windows.Forms.TextBox();
        this.pictureBox1 = new System.Windows.Forms.PictureBox();
        ((System.ruponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
        this.SuspendLayout();
        // 
        // button1
        // 
        this.button1.Location = new System.Drawing.Point(175, 22);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 0;
        this.button1.Text = "Show Image";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);
        // 
        // textBox1
        // 
        this.textBox1.Location = new System.Drawing.Point(30, 22);
        this.textBox1.Name = "textBox1";
        this.textBox1.Size = new System.Drawing.Size(126, 20);
        this.textBox1.TabIndex = 1;
        // 
        // pictureBox1
        // 
        this.pictureBox1.Location = new System.Drawing.Point(30, 64);
        this.pictureBox1.Name = "pictureBox1";
        this.pictureBox1.Size = new System.Drawing.Size(220, 221);
        this.pictureBox1.TabIndex = 2;
        this.pictureBox1.TabStop = false;
        // 
        // DisplayImages
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(292, 297);
        this.Controls.Add(this.pictureBox1);
        this.Controls.Add(this.textBox1);
        this.Controls.Add(this.button1);
        this.Name = "DisplayImages";
        this.Text = "Display Images";
        ((System.ruponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
        this.ResumeLayout(false);
        this.PerformLayout();
    }
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.TextBox textBox1;
    private System.Windows.Forms.PictureBox pictureBox1;
    private Images images;

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new DisplayImages());
    }
}
public class Images
{
    string imageFilename = null;
    byte[] imageBytes = null;
    SqlConnection imageConnection = null;
    SqlCommand imageCommand = null;
    SqlDataReader imageReader = null;
    // Constructor
    public Images()
    {
        imageConnection = new SqlConnection(@"data source = .\sqlexpress;integrated security = true;initial catalog = tempdb;");
        imageCommand = new SqlCommand(@"select imagefile,imagedata from imagetable ", imageConnection);
        imageConnection.Open();
        imageReader = imageCommand.ExecuteReader();
    }
    public Bitmap GetImage()
    {
        MemoryStream ms = new MemoryStream(imageBytes);
        Bitmap bmap = new Bitmap(ms);
        return bmap;
    }
    public string GetFilename()
    {
        return imageFilename;
    }
    public bool GetRow()
    {
        if (imageReader.Read())
        {
            imageFilename = (string)imageReader.GetValue(0);
            imageBytes = (byte[])imageReader.GetValue(1);
            return true;
        }
        else
        {
            return false;
        }
    }
    public void EndImages()
    {
        imageReader.Close();
        imageConnection.Close();
    }
}

LoadImages.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
    class LoadImages
    {
        static void Main()
        {
            string imageFileLocation ="C:\\";
            string imageFilePrefix = "a";
            int numberImageFiles = 1;
            string imageFileType = ".jpg";
            int maxImageSize = 10000;
            SqlConnection conn = null;
            SqlCommand cmd = null;
            conn = new SqlConnection(@"server = .\sqlexpress;integrated security = true;database = tempdb");
            conn.Open();
            cmd = new SqlCommand();
            cmd.Connection = conn;

            cmd.rumandText = @"create table imagetable(imagefile nvarchar(20),imagedata varbinary(max))";
            cmd.ExecuteNonQuery();
            cmd.rumandText = @"insert into imagetable values (@imagefile, @imagedata)";
            cmd.Parameters.Add("@imagefile", SqlDbType.NVarChar, 20);
            cmd.Parameters.Add("@imagedata", SqlDbType.Image, 1000000);
            cmd.Prepare();
            string imageFileName = null;
            byte[] imageImageData = null;
            imageFileName = imageFilePrefix + imageFileType;
            imageImageData = LoadImageFile(imageFileName, imageFileLocation, maxImageSize);
            cmd.Parameters["@imagefile"].Value = imageFileName;
            cmd.Parameters["@imagedata"].Value = imageImageData;
            
            cmd.rumandText = cmd.rumandText;
            cmd.ExecuteNonQuery();
        }
        static byte[] LoadImageFile(string fileName,string fileLocation,int maxImageSize)
        {
            byte[] imagebytes = null;
            string fullpath = fileLocation + fileName;
            Console.WriteLine("Loading File:");
            Console.WriteLine(fullpath);
            FileStream fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            imagebytes = br.ReadBytes(maxImageSize);
            Console.WriteLine("Imagebytes has length {0} bytes.",imagebytes.GetLength(0));
            return imagebytes;
        }
    }

Load image to database

/*
Quote from

Beginning C# 2005 Databases From Novice to Professional
# Paperback: 528 pages
# Publisher: Apress (December 18, 2006)
# Language: English
# ISBN-10: 159059777X
# ISBN-13: 978-1590597774
*/

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace LoadImages
{
   class LoadImages
   {
      string imageFileLocation =@"Images\";
      string imageFilePrefix = "milk";
      int numberImageFiles = 8;
      string imageFileType = ".gif";
      int maxImageSize = 10000;
      SqlConnection conn = null;
      SqlCommand cmd = null;
      static void Main()
      {
         LoadImages loader = new LoadImages();
         try
         {
            // Open connection
            loader.OpenConnection();
            // Create command
            loader.CreateCommand();
            // Create table
            loader.CreateImageTable();
            // Prepare insert
            loader.PrepareInsertImages();
            // Insert images
            int i;
            for (i = 1; i <= loader.numberImageFiles; i++)   
            {
               loader.ExecuteInsertImages(i);
            }
         }
         catch (SqlException ex)
         {
            Console.WriteLine(ex.ToString());
         }
         finally
         {
            loader.CloseConnection();
         }
      }
      void OpenConnection()
      {
         // Create connection
         conn = new SqlConnection(@"server = .\sqlexpress;integrated security = true;database = tempdb");
         // Open connection
         conn.Open();
      }
      void CloseConnection()
      {
         conn.Close();
         Console.WriteLine("Connection Closed."); 
      }
      void CreateCommand()
      {
         cmd = new SqlCommand();
         cmd.Connection = conn;
      }
      void ExecuteCommand(string cmdText)
      {
         int cmdResult;
         cmd.rumandText = cmdText;
         Console.WriteLine("Executing command:");
         Console.WriteLine(cmd.rumandText);
         cmdResult = cmd.ExecuteNonQuery();
         Console.WriteLine("ExecuteNonQuery returns {0}.", cmdResult); 
      }
      void CreateImageTable()
      {
         ExecuteCommand(@"create table imagetable(
               imagefile nvarchar(20),
               imagedata varbinary(max))");
      }
      void PrepareInsertImages()
      {
         cmd.rumandText = @"insert into imagetable values (@imagefile, @imagedata)";
         cmd.Parameters.Add("@imagefile", SqlDbType.NVarChar, 20);
         cmd.Parameters.Add("@imagedata", SqlDbType.Image, 1000000);
         cmd.Prepare();
      }
      void ExecuteInsertImages(int imageFileNumber)
      {
         string imageFileName = null;
         byte[] imageImageData = null;
         imageFileName =imageFilePrefix + imageFileNumber.ToString() + imageFileType; 
         imageImageData =LoadImageFile(imageFileName, imageFileLocation, maxImageSize);
         cmd.Parameters["@imagefile"].Value = imageFileName;
         cmd.Parameters["@imagedata"].Value = imageImageData;
         ExecuteCommand(cmd.rumandText);
      }
      byte[] LoadImageFile(string fileName,string fileLocation,int maxImageSize)
      {
         byte[] imagebytes = null; 
         string fullpath = fileLocation + fileName;
         Console.WriteLine("Loading File:");
         Console.WriteLine(fullpath);
         FileStream fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read);
         BinaryReader br = new BinaryReader(fs);
         imagebytes = br.ReadBytes(maxImageSize);
         Console.WriteLine("Imagebytes has length {0} bytes.",imagebytes.GetLength(0));
         return imagebytes;
      }
   }
}

Read Bitmap from database

using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
public class MainClass
{
   public static void Main()
   {
      SqlConnection  imageConnection = new SqlConnection(@"data source = .\sqlexpress;integrated security = true;initial catalog = tempdb;");
      SqlCommand imageCommand = new SqlCommand(@"select imagefile,imagedata from imagetable ",imageConnection);
      imageConnection.Open();
      SqlDataReader imageReader = imageCommand.ExecuteReader();
      string imageFilename = (string) imageReader.GetValue(0);
      byte[] imageBytes = (byte[]) imageReader.GetValue(1);
      MemoryStream ms = new MemoryStream(imageBytes);
      Bitmap bmap = new Bitmap(ms);
      imageReader.Close();
      imageConnection.Close();
   }
}

Writes binary data to a file

using System;
using System.Data.SqlClient;
using System.Data;
using System.IO;
public class ConnectionTest
{
    private static string connectionString = "Data Source=localhost;Initial Catalog=pubs;Integrated Security=SSPI";
    private static string SQL = "SELECT pub_id, logo FROM pub_info";
    public static void Main() 
    {
        int bufferSize = 100;                  
        byte[] bytes = new byte[bufferSize];
        long bytesRead;
        long readFrom;
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(SQL, con);
        con.Open();
        SqlDataReader r = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
        while (r.Read())
        {
            string filename = "logo.bmp";
            FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);
            readFrom = 0;
            do {
                bytesRead = r.GetBytes(1, readFrom, bytes, 0, bufferSize);
                bw.Write(bytes);
                bw.Flush();
                readFrom += bufferSize;
            } while (bytesRead == bufferSize);
            bw.Flush();
            bw.Close();
            fs.Close();
        }
        r.Close();
        con.Close();
    }
}