以二进制流的方式存入数据库,并读取显示

以二进制流的方式存入数据库,并读取显示

数据库的字段同样简单:
Image_ID    int    identity(1,1)     primarykey    not null
Image_Content     image null
Image_Content以二进制形式保存图片

整体看一下例子里的页面组成:
上传图片页面和第一种方法一样,同样是用到FileUpload,以及一个Button,具体代码如下:

protected void Button1_Click(object sender, EventArgs e)

{

       
string name =
FileUpload1.PostedFile.FileName;

       
string type = name.Substring(name.LastIndexOf(".") + 1
);

        FileStream fs
=
File.OpenRead(name);

       
byte[] content = new byte
[fs.Length];

        fs.Read(content,
0
, content.Length);

        fs.Close();



        SqlConnection conn
= new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Pooling=False;Password="
);

        SqlCommand cmd
=
conn.CreateCommand();

        conn.Open();

        cmd.CommandText
= "insert into Images(Image_Content) values (@content)"
;

        cmd.CommandType
=
CommandType.Text;



       
if (type == "jpg" || type == "gif" || type == "bmp" || type == "png"
)

        {

          SqlParameter para
= cmd.Parameters.Add("@content"
, SqlDbType.Image);

          para.Value
=
content;

          cmd.ExecuteNonQuery();

        }

}

显示一张图片和显示一组图片有所不同,将会分别说明之。

显示一张图片,要用到Default.aspx和Default2.aspx。Default.aspx中有一个控件Image,它的属性ImageUrl指向Default2.aspx用于显示图片。Default2.aspx用于
读取图片。
Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{



        Image1.ImageUrl
= "Default2.aspx"
;

}

Default2.aspx.cs        

string imgid = Request.QueryString["imgid"
];

        SqlConnection conn1
= new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=sa;Pooling=False;Password="
);

        SqlCommand cmd1
= new SqlCommand("select Image_Content from Images where Image_ID=3", conn1);     //固定显示Image_ID为3的图片


        conn1.Open();

        SqlDataReader sdr
= cmd1.ExecuteReader();

       
if
(sdr.Read())

        {

          Response.BinaryWrite((
byte[])sdr["Image_Content"
]);

        }

        Response.End();

显示一组图片时,用ashx Handle存放图片。同时用GridView以列显示图片。Image控件绑定Image_ID。
allimage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="allimage.aspx.cs" Inherits="allimage" %>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



<HTML xmlns="http://www.w3.org/1999/xhtml">

<HEAD runat="server">


<title>BindImg</title>


</HEAD>


<body>


<form id="Form1" method="post" runat="server">


<FONT face="宋体">


<asp:DataGrid id="MyDataGrid" runat="server" AutoGenerateColumns="False" Width="632px">


<AlternatingItemStyle BackColor="Beige"></AlternatingItemStyle>


<HeaderStyle HorizontalAlign="Center"></HeaderStyle>


<Columns>


<asp:TemplateColumn HeaderText="Photo">


<ItemTemplate> <asp:Image ID="Image1" runat="server" Height="70px" ImageUrl='<%# "Getimg.ashx?id="+Eval("Image_ID") %>'


        Width
="100px" />

</ItemTemplate>

</asp:TemplateColumn>


</Columns>


</asp:DataGrid></FONT>


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:PracticeConnectionString %>"


        SelectCommand
="SELECT * FROM [Images]"></asp:SqlDataSource>

</form>

</body>


</HTML>


allimage.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

        MyDataGrid.DataSource
=
SqlDataSource1;

        MyDataGrid.DataBind();

}
Getimg.ashx
<%@ WebHandler Language="C#" Class="Getimg" %>

using System;

using
System.Web;

using
System.Data;

using
System.Data.SqlClient;

using
System.Configuration;



public class
Getimg : IHttpHandler {



public void
ProcessRequest (HttpContext context)

{

       
int id = int.Parse(context.Request.QueryString["id"
]);

        SqlConnection conn
= new SqlConnection(@"server=;database=;uid=;pwd="
);

        SqlCommand cmd
= new SqlCommand("select Image_Content from Images where Image_ID='" + id + "'"
, conn);

        cmd.Parameters.Add(
"@id", SqlDbType.Int).Value =
id;

        conn.Open();

        SqlDataReader dr
=
cmd.ExecuteReader();

       
if
(dr.Read())

        {

          context.Response.BinaryWrite((
byte[])dr["Image_Content"
]);

        }

        dr.Close();

}



public bool
IsReusable {

       
get
{

         
return false
;

        }

}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是将图片以二进制存入Phpadmin数据库中并显示的实现代码: 1. 存入数据库 // 连接数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "dbname"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // 读取图片文件 $image_path = "image.jpg"; $image_data = file_get_contents($image_path); // 将图片数据存入数据库 $sql = "INSERT INTO images (image_data) VALUES ('$image_data')"; if ($conn->query($sql) === TRUE) { echo "Image saved to database successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); 2. 显示图片 // 连接数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "dbname"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // 从数据库读取图片数据 $sql = "SELECT image_data FROM images WHERE image_id = 1"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出图片数据 $row = $result->fetch_assoc(); header("Content-Type: image/jpeg"); echo $row["image_data"]; } else { echo "Image not found"; } $conn->close(); 注意:以上代码仅供参考,实际应用中需要根据具体情况进行修改和优化。同时,将图片存入数据库会增加数据库的负担和数据存储量,建议仅在特定情况下使用,如需要保护图片版权等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值