在ASP.NET中怎么图片转换二进制
1个回答
展开全部
首先数据库里面有一字段类型为image,我这里是一个窗体应用程序,也是将图片以二进制的形式保存至数据库的,思路是一样的
byte[] photo;
public byte[] Photo
{
get { return photo; }
set { photo = value; }
}
FileStream fs;
string fileName = string.Empty;
private void btnChooose_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "*.jpg|*.jpg|*.gif|*.gif|*.bmp|*.bmp";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
fileName = fileDialog.FileName;
fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
pictureBox.Image = Image.FromStream(fs);
fs.Close();
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(fileName))
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
byte[] imageByte = new byte[fs.Length];
fs.Read(imageByte, 0, (int)fs.Length);
Photo = imageByte;
fs.Close();
AddImage();
}
else
{
MessageBox.Show("请选择图片");
}
}
private void AddImage()
{
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
SqlCommand command = new SqlCommand("PROC_ADDIMAGE", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@IMAGE", SqlDbType.Image).Value = Photo;
int rows = command.ExecuteNonQuery();
if (rows > 0)
{
MessageBox.Show("添加成功");
}
else
{
MessageBox.Show("添加失败");
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
int index;
/// <summary>
/// 获取图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetImage_Click(object sender, EventArgs e)
{
/// <summary>
/// 存图片的集合
/// </summary>
IList<Form1> form1List = new List<Form1>();
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand command = new SqlCommand("PROC_GETIMAGE", conn);
command.CommandType = CommandType.StoredProcedure;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Form1 form1 = new Form1();
form1.Photo = (byte[])reader["Photo"];
form1List.Add(form1);
}
}
}
if (form1List.Count == 1)
{
MemoryStream imageStream = new MemoryStream(form1List[0].Photo);
pictureBox.Image = Image.FromStream(imageStream);
}
else if (form1List.Count > 1)
{
index++;
if (index < form1List.Count)
{
btnGetImage.Text = "下一张";
MemoryStream imageStream = new MemoryStream(form1List[index].Photo);
pictureBox.Image = Image.FromStream(imageStream);
}
else
{
index=0;
MemoryStream imageStream = new MemoryStream(form1List[index].Photo);
pictureBox.Image = Image.FromStream(imageStream);
}
}
else
{
MessageBox.Show("存中还没有图片");
}
}
/// <summary>
/// 清除图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClear_Click(object sender, EventArgs e)
{
pictureBox.Image = null;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询