0

我有一个包含 3 列的 SQL Server 数据库,其中 2 列是字符串,1 列是 jpeg。图像存储为VARBINARY(MAX).

sql图片

我已将此数据保存到 ASP.NET 中的 DataTable 中。我想将图像作为字节数组,但显然它是类型对象......或者是吗?

在此处输入图像描述

什么是dt.rows[0 ][2 ],对象或字节数组?如果它不是字节数组,为什么.ToString()返回System.Byte[]

我的索引控制器

public IActionResult Index()
{
    SqlConnection con = new SqlConnection("Data Source=DESKTOP-896D683;Initial Catalog=aspdb1;Integrated Security=True");

    SqlDataAdapter sda = new SqlDataAdapter(" select * from stuff_for_carrousel ", con);

    List<front_page> mi_list = new List<front_page>();

    DataTable dt = new DataTable();
    sda.Fill(dt);

    Image newImage = mi_converter.convert_to_image(dt.Rows[0][2]);

    ViewData["dd"] = dt.Rows[0][0].ToString();
    ViewData["ccc"] = dt.Rows[0][1].ToString();
    ViewData["ts"] = dt.Rows[0][2].GetType().ToString();

    return View();
}

我的转换器

    public class mi_converter
    {
        public Image convert_to_image(byte[] b)
        {
            using (var ms = new MemoryStream(b))
            {
                return Image.FromStream(ms);
            }
        }
    }
}

我想我只需要转换dt.rows[0][2]为字节数组。

4

1 回答 1

1

dt.Rows[0][0] means: Get me the value of the first column of the first row.
Since that value could basically be anything, the .Net framework can only represent it as System.Object.

Your method, however, expects a byte[] - so you need to cast that object to a byte array, or better yet, use the Field<T> extension method instead of the indexer:

Image newImage = mi_converter.convert_to_image(dt.Rows[0].Field<Byte[]>(2));

And some notes as well:

  1. Using select * is a bad idea - it makes your code vulnerable to changes in the table.

  2. using the ordinal indexer (0, 1, 2) is even worst, since now your code is even more vulnerable to changes in the table.

  3. using identifiers such as "dd", "ccc" or any other meaningless combinations of letters in your code is a terrible idea - always use meaningful names. Your future self will thank you.

于 2019-11-14T12:00:45.737 回答