图片保存到数据库的小程序

应一位网友要求,做了一个将图片保存到数据库和从数据库读取图片的小程序。

源码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;

namespace ImageToDB
{
    
public partial class UserEdit : Form
    {
        
public UserEdit()
        {
            InitializeComponent();
        }
        
private void UserEdit_Load(object sender, EventArgs e)
        {
            LoadNextUser();
        }
        
string strConn = "Data Source=wangyang\\SQLEXPRESS;Initial Catalog=test;Persist Security Info=True;User ID=uap;Password=uap";
        
string strGetTopOne = "select top 1 * from users ";

        
/// <summary>
        
/// 保存按钮事件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            
if (txtUserID.Text == "" || txtUserID.Text == string.Empty)
            {
                
//新增
                if (txtUserName.Text == "" || txtImagePath.Text == "")
                {
                    MessageBox.Show(
"用户名和图片不能为空!");
                    
return;
                }
                
//这里看如何将图片保存到数据库的。
                FileStream fs = File.OpenRead(txtImagePath.Text);
                
byte[] imageb = new byte[fs.Length];
                fs.Read(imageb, 
0, imageb.Length);
                fs.Close();
                
string strSQL = "insert into Users(UserName,UserImage)values(@UserName,@UserImage)";
                SqlConnection con 
= new SqlConnection(strConn);
                SqlCommand com3 
= new SqlCommand(strSQL, con);
                com3.Parameters.Add(
"@UserName", SqlDbType.VarChar).Value = txtUserName.Text;
                com3.Parameters.Add(
"@UserImage", SqlDbType.Image).Value = imageb;
                
if (com3.Connection.State == ConnectionState.Closed)
                    com3.Connection.Open();
                
try
                {
                    com3.ExecuteNonQuery();
                    MessageBox.Show(
"新增用户成功!");
                }
                
catch
                {
                    MessageBox.Show(
"新增用户失败!");
                }
                
finally
                { com3.Connection.Close(); }

            }
            
else
            {
                
//修改
                
//这里看如何将图片保存到数据库的。
                string strSQL = "update users set username=@UserName";
                
if (txtImagePath.Text != "")
                    strSQL 
+= ",userimage=@UserImage";
                SqlConnection con 
= new SqlConnection(strConn);
                SqlCommand com3 
= new SqlCommand(strSQL, con);
                com3.Parameters.Add(
"@UserName", SqlDbType.VarChar).Value = txtUserName.Text;
                
if (txtImagePath.Text != "")
                {
                    FileStream fs 
= File.OpenRead(txtImagePath.Text);
                    
byte[] imageb = new byte[fs.Length];
                    fs.Read(imageb, 
0, imageb.Length);
                    fs.Close();
                    com3.Parameters.Add(
"@UserImage", SqlDbType.Image).Value = imageb;
                }
                
if (com3.Connection.State == ConnectionState.Closed)
                    com3.Connection.Open();
                
try
                {
                    com3.ExecuteNonQuery();
                    MessageBox.Show(
"修改用户成功!");
                }
                
catch
                {
                    MessageBox.Show(
"修改用户失败!"); 
                }
                
finally
                { com3.Connection.Close(); }
            }

        }

        
/// <summary>
        
/// 下一位。
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            
string preUserID = txtUserID.Text;
            LoadNextUser();
            
if (txtUserID.Text == preUserID)
                MessageBox.Show(
"已经是最后一位用户!");
        }

        
/// <summary>
        
/// 清空。
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            txtUserID.Text 
= "";
            txtUserName.Text 
= "";
            txtImagePath.Text 
= "";
            pictureBox1.Image 
= null;
        }
        
/// <summary>
        
/// 选择图片。
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void btOpenImage_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter 
= "JPEG|*.jpg|GIF|*.gif";
            
if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtImagePath.Text 
= openFileDialog1.FileName;
                FileStream fs 
= File.OpenRead(txtImagePath.Text);
                
byte[] imageb = new byte[fs.Length];
                fs.Read(imageb, 
0, imageb.Length);
                fs.Close();
                MemoryStream memStream 
= new MemoryStream(imageb);
                
try
                {
                    Bitmap myimge 
= new Bitmap(memStream);
                    
this.pictureBox1.Image = myimge;
                }
                
catch
                {
                }
            }
        }

        
/// <summary>
        
/// 从数据库中读取下一位用户的信息。如果参数为空则读取第一条信息。
        
/// </summary>
        
/// <param name="PreUserID"></param>
        
/// <returns></returns>
        public DataTable GetTopOneUser(string filter)
        {
            strGetTopOne 
= "select top 1 * from users ";
            
if (filter != "" && filter != string.Empty)
                strGetTopOne 
+= filter;
            SqlConnection con 
= new SqlConnection(strConn);
            SqlCommand com 
= new SqlCommand(strGetTopOne, con);
            
if (con.State == ConnectionState.Closed)
                con.Open();
            SqlDataAdapter da 
= new SqlDataAdapter(com);
            DataSet ds 
= new DataSet();
            da.Fill(ds, 
"UserTable");
            
if (ds != null && ds.Tables.Count > 0)
                
return ds.Tables[0];
            
else
                
return null;
        }
        
/// <summary>
        
/// 加载下一位用户信息
        
/// </summary>
        public void LoadNextUser()
        {
            
//这里看如何将数据库图片读出来
            string filter ="";
            
if (txtUserID.Text != "")
                filter 
= " where userid>" + txtUserID.Text;
            DataTable dt 
= GetTopOneUser(filter);
            
if (dt.Rows.Count == 0)
                
return;
            DataRow dr 
= dt.Rows[0];
            txtUserID.Text 
= dr["UserID"].ToString();
            txtUserName.Text 
= dr["UserName"].ToString();
            
byte[] imageb = (byte[])dr["UserImage"];
            MemoryStream memStream 
= new MemoryStream(imageb);
            
try
            {
                Bitmap myimge 
= new Bitmap(memStream);
                
this.pictureBox1.Image = myimge;
            }
            
catch
            {
            }
        }
        
/// <summary>
        
/// 加载上一位用户信息
        
/// </summary>
        public void LoadPreUser()
        {
            
string filter = "";
            
if (txtUserID.Text != "")
                filter 
= " where userid<" + txtUserID.Text+" order by Userid desc";
            DataTable dt 
= GetTopOneUser(filter);
            
if (dt.Rows.Count == 0)
                
return;
            DataRow dr 
= dt.Rows[0];
            txtUserID.Text 
= dr["UserID"].ToString();
            txtUserName.Text 
= dr["UserName"].ToString();
            
byte[] imageb = (byte[])dr["UserImage"];
            MemoryStream memStream 
= new MemoryStream(imageb);
            
try
            {
                Bitmap myimge 
= new Bitmap(memStream);
                
this.pictureBox1.Image = myimge;
            }
            
catch
            {
            }
        }
        
/// <summary>
        
/// 关闭。
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            
this.Close();
        }
        
/// <summary>
        
/// 上一位
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            
string preUserID = txtUserID.Text;
            LoadPreUser();
            
if (txtUserID.Text == preUserID)
                MessageBox.Show(
"已经是最前一位用户!");
            
        }
        
/// <summary>
        
/// 帮助。
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            help helper 
= new help();
            helper.Show();
        }
        
    }
}


界面如下:


说明:
不用担心数据库能不能存放下你保存的图片,数据库可以存放2GB大的图片,可以远远满足你的要求。

源码下载: CODE   演示版:DEMO
posted @ 2008-01-14 11:08  小y  阅读(4678)  评论(7编辑  收藏  举报