300百分求向数据库插入图片和显示的问题

程序猿3000 2005-05-11 04:52:19
300百分求向数据库插入图片和显示的问题
数据库为sql server,
表:student(code char(4),photo image)两个字段
求源代码
解决立刻给分
...全文
291 25 打赏 收藏 转发到动态 举报
写回复
用AI写文章
25 条回复
切换为时间正序
请发表友善的回复…
发表回复
renyu732 2005-07-01
  • 打赏
  • 举报
回复
呵呵.托孟老大的福呢...
http://dotnet.aspx.cc/ShowDetail.aspx?id=2A5DD7C6-A45A-48AB-A2E8-342A29F17506

http://dotnet.aspx.cc/ShowDetail.aspx?id=ECD9AE16-8FF0-4A1C-9B9F-5E8B641CB1B1

mba9001 2005-07-01
  • 打赏
  • 举报
回复
up
gzw1003 2005-07-01
  • 打赏
  • 举报
回复
可以给你一例子邮箱给我
think8848 2005-07-01
  • 打赏
  • 举报
回复
mark!
zhgroup 2005-07-01
  • 打赏
  • 举报
回复
插入数据库就是先把图片转换成byte[],然后用Command对象写入数据库,取出也是如此,
itoltgvi 2005-07-01
  • 打赏
  • 举报
回复
学习中....
掐死温柔 2005-07-01
  • 打赏
  • 举报
回复
主要难点在于把它转换成二进制流

相关的例子楼上有好几个。
lyb_abiandbel 2005-07-01
  • 打赏
  • 举报
回复
添加:
http://dotnet.aspx.cc/ShowDetail.aspx?id=2A5DD7C6-A45A-48AB-A2E8-342A29F17506
显示:
http://dotnet.aspx.cc/ShowDetail.aspx?id=ECD9AE16-8FF0-4A1C-9B9F-5E8B641CB1B1
JeasonZF 2005-05-20
  • 打赏
  • 举报
回复


源码参考:
http://www.pcsky.cn/article/list.asp?id=774

看不懂再问
jetxia 2005-05-11
  • 打赏
  • 举报
回复
mycnn=new SqlConnection(@"server=zhurongj;database=my1;Trusted_connection=yes");
mycnn.Open();
MessageBox.Show("ok.mycnn.open");
SqlCommand mycmd=new SqlCommand("select * from picture",mycnn);
SqlDataReader myrd=mycmd.ExecuteReader();


if(myrd.Read())
{
//读取图片
if(!myrd.IsDBNull(1))
{
byte []box=(byte [])myrd[1];

//构造流

Stream stream1=new MemoryStream(box);
this.pictureBox2.Image=System.Drawing.Image.FromStream(stream1);

stream1.Close();
}
else
{

MessageBox.Show("该字段是NULL");
}

}


mycnn.Close();
}
catch(Exception my)
{
MessageBox.Show(my.Message.ToString());

}
freehul 2005-05-11
  • 打赏
  • 举报
回复
把我刚才发的两个方法Copy过到同一文件去.然后把这句话改了,试一下

cmd.Parameters.Add(new SqlParameter("@photo",SqlDbType.Image));
cmd.Parameters["@photo"].Value = ConvertImage(System.Drawing.Image.FromFile("c:\\w.jpg"));
dazhu2 2005-05-11
  • 打赏
  • 举报
回复
显示到PICTURE控件
mycnn=new SqlConnection(@"server=zhurongj;database=my1;Trusted_connection=yes");
mycnn.Open();
MessageBox.Show("ok.mycnn.open");
SqlCommand mycmd=new SqlCommand("select * from picture",mycnn);
SqlDataReader myrd=mycmd.ExecuteReader();


if(myrd.Read())
{
//读取图片
if(!myrd.IsDBNull(1))
{
byte []box=(byte [])myrd[1];

//构造流

Stream stream1=new MemoryStream(box);
this.pictureBox2.Image=System.Drawing.Image.FromStream(stream1);

stream1.Close();
}
else
{

MessageBox.Show("该字段是NULL");
}

}


mycnn.Close();
}
catch(Exception my)
{
MessageBox.Show(my.Message.ToString());

}
dazhu2 2005-05-11
  • 打赏
  • 举报
回复
SQL数据库
mycnn=new SqlConnection(@"server=zhurongj;database=my1;Trusted_connection=yes");
mycnn.Open();
SqlCommand mycmd=new SqlCommand("update picture set picture=@a where ID=1",mycnn);

FileStream mystream=new FileStream("f:\\1.jpg",FileMode.Open,FileAccess.Read);
long len=mystream.Length;

mycmd.Parameters.Add("@a",SqlDbType.Image,(int)len,"picture");
mycmd.Parameters["@a"].Direction=System.Data.ParameterDirection.Input;

byte []box=new byte[len];
mystream.Read(box,0,(int)len);

mycmd.Parameters["@a"].Value=box;

//更新
mycmd.ExecuteNonQuery();
MessageBox.Show("ok");
mystream.Close();
mycnn.Close();
程序猿3000 2005-05-11
  • 打赏
  • 举报
回复
请大哥门帮忙
程序猿3000 2005-05-11
  • 打赏
  • 举报
回复

FileStream stream=new FileStream("c:\\w.jpg",FileMode.Open,FileAccess.Read);
byte[] blob=new byte[stream.Length];
stream.Read(blob,0,(int)stream.Length);
stream.Close();
string source="server=csl;database=StudentDB;uid=sa;pwd=''";
sqlcon=new SqlConnection(source);
try
{
sqlcon.Open();
string sql="insert into photo(code,photo) values('0001',@photo)";
SqlCommand command=new SqlCommand(sql,sqlcon);
cmd.Parameters.Add("@photo",blob);
//cmd.Parameters.Add("@photo", SqlDbType.Image, blob.Length).Value = blob;
cmd.ExecuteNonQuery();
}
catch(Exception e1)
{
Console.WriteLine("shiba");
}
finally
{
sqlcon.Close();
}
}

在插入数据库时,不包任何错误,但数据库中没有数据

我的数据库是sqlserver 表结构为photo(code char(4),photo image)
freehul 2005-05-11
  • 打赏
  • 举报
回复
我是用Winfrom开发,希望能帮到你
先建一个类,Copy可用..........
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Runtime.Serialization.Formatters.Binary; //引入供序列化Image对象使用

namespace Common
{
/// <summary>
/// 实现Image与byte[]之间的转换
/// </summary>
public class ReadWriteImage
{
private ReadWriteImage(){}
/// <summary>
/// 将byte[]转换为Image
/// </summary>
/// <param name="bytes">字节数组</param>
/// <returns>Image</returns>
public static Image ReadImage(byte[] bytes)
{
MemoryStream ms=new MemoryStream(bytes,0,bytes.Length);
BinaryFormatter bf = new BinaryFormatter();
object obj=bf.Deserialize(ms);
   ms.Close();
   return (Image)obj;
}
/// <summary>
/// 将Image转换为byte[]
/// </summary>
/// <param name="image">Image</param>
/// <returns>byte[]</returns>
public static byte[] ConvertImage(Image image)
{
MemoryStream ms=new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms,(object)image);
ms.Close();
return ms.ToArray();
}
}
}
程序猿3000 2005-05-11
  • 打赏
  • 举报
回复
我的不是web程序
lhcoolhacker 2005-05-11
  • 打赏
  • 举报
回复
保存图片到数据库后台代码
namespace Drugger.WebUI.Modules
{
using System;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Drugger.BusinessFacade;
using Drugger.Model;
using Drugger.SystemFramework;
using Drugger.WebUI.Modules;
using Drugger.WebCtrlLib;

/// <summary>
/// 图片编辑控件
/// </summary>
public class PhotoEditModule: UserControl
{
protected RequiredFieldValidator valFilePhoto;
protected RegularExpressionValidator valExpFilePhoto;
protected HtmlInputFile filePhoto;

private void Page_Load(object sender, System.EventArgs e){}

#region 事件

// 保存相片数据
protected void btnSave_Click(object sender, EventArgs e)
{
#region 获取数据

Stream imgStream = filePhoto.PostedFile.InputStream;
int imgLength = filePhoto.PostedFile.ContentLength;
byte[]imgData = new byte[imgLength];
int n = imgStream.Read(imgData, 0, imgLength);

#endregion

if (Page.IsValid)
{
#region 保存数据到数据库

int retVal = - 1;
PhotoModel photoModel = new PhotoModel();
PhotoSystem photoSystem = new PhotoSystem();
PhotoModel.PhotoRow row = photoModel.Photo.NewPhotoRow();

row.Photo = imgData;

photoModel.Photo.Rows.Add(row);
retVal = photoSystem.Insert(photoModel);

#endregion
}
}

#endregion

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器
/// 修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
}

前台代码
<TABLE cellSpacing="1" cellPadding="3" width="100%" border="0">
<TR>
<TD>
<INPUT id="filePhoto" type="file" name="filePhoto" runat="server">
<asp:RequiredFieldValidator id="valFilePhoto" runat="server" ControlToValidate="filePhoto" ErrorMessage="请选择图片"
Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator id="valExpFilePhoto" runat="server" ControlToValidate="filePhoto" ErrorMessage="图片格式错误"
Display="Dynamic" ValidationExpression="[a-zA-Z]:\\(.+\\)*.+(\.gif|\.jpeg|\.jpg)"></asp:RegularExpressionValidator>
<P>注:上传的图片必须为gif或jpeg格式,图片规格默认为94×114(最佳浏览效果)</P>
</TD>
</TR>
</TABLE>
<TABLE WIDTH="100%" BORDER="0" CELLSPACING="1" CELLPADDING="3">
<TR>
<TD width="40"> </TD>
<TD height="40">
<asp:Button id="btnSave" runat="server" Text="保存" Width="60" OnClick="btnSave_Click" />
      
<asp:HyperLink id="hlkReturn" runat="server" Text="返回" Absoluted="True" CssClass="Button" Width="60" />
</TD>
</TR>
</TABLE>

显示图片前台代码
<%@ Page language="c#" Codebehind="Picture.aspx.cs" AutoEventWireup="false" Inherits="Drugger.WebUI.Modules.Picture" EnableSessionState="False" enableViewState="False" %>

后台代码
namespace Drugger.WebUI.Modules
{
using System;
using System.Text;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Drugger.BusinessFacade;
using Drugger.SystemFramework;

/// <summary>
/// 图片显示Web页
/// </summary>
public class Picture: Page
{
private void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
int photoId = 0;
string photoIdText = Request.QueryString.Get("photoId");
photoId = (int)photoIdText;
byte[]photo = (new PhotoSystem()).GetPhotoByPhotoID(photoId);

if (photo != null)
{
Response.ContentType = "image/*";
Response.BinaryWrite(photo);
}
}
}

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new EventHandler(this.Page_Load);
}
#endregion
}
}

数据库提取代码:
/// <summary>
/// 获取图片
/// </summary>
/// <param name="photoId">图片ID</param>
/// <returns>图片</returns>
public byte[]GetPhotoByPhotoID(int photoId)
{
byte[]photo = null;
string spString = "GetPhotoByPhotoID";

SqlParameter[]parms = SqlHelperParameterCache.GetSpParameterSet
(AccessCommon.ConnectionString, spString);
parms[0].Value = photoId;

using(SqlDataReader rdr = SqlHelper.ExecuteReader
(AccessCommon.ConnectionString, CommandType.StoredProcedure, spString,
parms))
{
if (rdr.Read())
{
if (!rdr.IsDBNull(0))
photo = (byte[])rdr[0];
}
}

return photo;
}
dazhu2 2005-05-11
  • 打赏
  • 举报
回复
个人认为如果图片比较多的话存路径比较好点
程序猿3000 2005-05-11
  • 打赏
  • 举报
回复
我的是winform程序,要求用pictureBox控件来显示
加载更多回复(5)

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧