黑马程序员技术交流社区
标题:
往数据库中传图片,在数据库中保存的是图片还是地址?
[打印本页]
作者:
赵刘滨
时间:
2012-8-17 11:31
标题:
往数据库中传图片,在数据库中保存的是图片还是地址?
请详细说明下(谢谢)
作者:
许庭洲
时间:
2012-8-17 11:42
1,将图片转换成byte存储;
2,存进数据库可以直接用Image对象;
3,SqlCommand.Parameters.Add("@image",SqlDbType.Image).Value=myImage; //myImage 为Image对象
4,从数据库取出来,是byte数组。
作者:
冯华亮
时间:
2012-8-17 12:46
我这有代码,读写都有,你自己看吧:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace 图片存取
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection conn;
SqlDataReader myreader;
byte[] photo = null;
#region //定义一个静态变量区
#endregion
private void button1_Click(object sender, EventArgs e)
{
SqlCommand cmd1 = new SqlCommand("insert image values(@image_id,@image_tupian)", conn);
cmd1.Parameters.Add("@image_id", SqlDbType.Int, 4).Value = textBox1.Text;
cmd1.Parameters.Add("@image_tupian", SqlDbType.Image, photo.Length).Value = photo;
conn.Open();
cmd1.ExecuteNonQuery();
conn.Close();
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.AddExtension = true;
ofd.Title = "图片选择过滤器";
ofd.Filter = "file(*.jpg)|*.jpg|file(*.bmp)|*.bmp";
if(ofd.ShowDialog()==DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(ofd.FileName);
FileStream fs = new FileStream(ofd.FileName,FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
pictureBox1.Image = null;
SqlCommand cmd2 = new SqlCommand("select image_tupian from image where image_id='" + textBox1.Text + "'",conn);
//conn.Open();
//myreader = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
//if (myreader.Read())
//{
// photo =(byte[])myreader.GetValue(0);
//}
//MemoryStream ms = new MemoryStream(photo);
//pictureBox1.Image = Image.FromStream(ms);
//ms.Close();
//myreader.Close();
conn.Open();
photo = (byte[])cmd2.ExecuteScalar();
MemoryStream ms = new MemoryStream(photo);
if (ms.Length > 0)
{
pictureBox1.Image = Image.FromStream(ms);
}
else
pictureBox1.Image = null;
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection(global.conString);
SqlDataAdapter sda = new SqlDataAdapter("Select * from image",conn);
DataSet ds = new DataSet();
sda.Fill(ds,"image");
dataGridView1.DataSource=ds.Tables["image"].DefaultView;
}
private void button4_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2