显示来自字节数组的网格视图中的图像

本文关键字:网格 视图 图像 数组 字节 字节数 显示 | 更新日期: 2023-09-27 18:20:21

我遇到以下问题:我使用的是c#和.aspx页面。在.aspx页面上,我有一个GridView。我将GridView数据源设置为:

GridView1.DataSource = PictureInfo.PictureInfoList;

我的"图片信息"类如下:

public class PictureInfo
{
    public static List<PictureInfo> PictureInfoList = new List<PictureInfo>();
    public string PictureDescription { get; set; }
    public byte[] Picture { get; set; }
}

是否可能以及如何在GridView中显示"byte[]图片"中的图片?或者哪种方式是可能的?在将数据发送到数据库之前,我会以这种方式保存数据。在将它发送到数据库之前,我想在GridView中显示它。正如你所看到的,我是一个初学者,但如果我能做到这一点,我会非常高兴。我的头脑已经从网上读到了一些解决方案,直到现在都无济于事。

非常感谢

显示来自字节数组的网格视图中的图像

我建议您一个解决方案:将byte[]转换为Bitmap(可能对您有用):

public BitmapSource ByteArrayToBitmap(byte[] byteArray) {
    BitmapSource res;
    try {
        using (var stream = new MemoryStream(byteArray)) {
            using (var bmp = new Bitmap(stream)) {
                res = ToBitmap(bmp);
            }
        }
    } catch {
        res = null;
    }
    return res;
}
public BitmapSource ToBitmap(Bitmap bitmap) {
    using (var stream = new MemoryStream()) {
        bitmap.Save(stream, ImageFormat.Bmp);
        stream.Position = 0;
        var result = new BitmapImage();
        result.BeginInit();     
        result.CacheOption = BitmapCacheOption.OnLoad;
        result.StreamSource = stream;
        result.EndInit();
        result.Freeze();
        return result;
    }
}

接下来,您应该进行调整,并将Bitmap包含在GridView中。

在处理程序上。ashx

public void ProcessRequest(HttpContext context)

 context.Response.ContentType = "image/jpeg";
 string ImageID=request["ID"];
 //byte[] ImageByte=pictureInfo.Picture;//local imageByte
 byte[] ImageByte=getImage(ImageId);//image byte from any other sour,e.g database
 Stream strm = new MemoryStream(ImageByte));
 long length = strm.Length;
 byte[] buffer = new byte[length];
 int byteSeq = strm.Read(buffer, 0, 2048);
 while (byteSeq > 0)
 {
       context.Response.OutputStream.Write(buffer, 0, byteSeq);
       byteSeq = strm.Read(buffer, 0, 2048);
  }

}

现在在网格视图中为您的asp:image设置图像url,如下所示

Image1.ImageUrl = "somthing.ashx?ID="+userImageID;

我希望你有唯一的身份证,你的形象是可见的。我希望你们现在都准备好了。评论和质疑很受欢迎。

从数据库中检索图像字节

public  byte[] GetImage(string ImageId)
{ byte[] img = null;
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SlikaHendler";
cmd.Parameters.AddWithValue("@Id", ImageId);
cmd.Connection = yourConnection();
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read())
{
    img = (byte[])dr[0];
}
dr.Close();
return img;//returns array of byte
}

我知道图片是作为二进制文件记录到数据库中的。在这方面,您的问题转向"将二进制转换为字节"。

如果你可以将图片信息作为二进制数据,你可以将其转换为1字节的3位数字,并转换&显示为字节。

http://en.wikipedia.org/wiki/ASCII