【问题标题】:Compare two images from DB and file比较来自数据库和文件的两个图像
【发布时间】:2019-05-29 04:47:51
【问题描述】:

我想将上传的图片与数据库中的所有图像进行比较,如果匹配则应显示数据与图像,比较很简单,只需将每个图像转换为二进制see this

我正在使用此代码,但它不起作用:

protected void CompareImages(object sender, EventArgs e)
{
    if (this.FileUpload1.HasFile)
    {
        Stream fs = FileUpload1.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(constr))
        {
            string sqlQuery = "SELECT * from [MostWanted] WHERE Photo = @FileName";

            using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
            {
                cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(this.FileUpload1.PostedFile.FileName));
                conn.Open();
                Byte[] bytes2 = (Byte[])cmd.ExecuteScalar();
                conn.Close();
                if (bytes2 != null)
                {
                    if (bytes.Length == bytes2.Length)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Equal Images')", true);
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Images are not equal')", true);
                    }
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('File Not found in the table')", true);
                }
            }
        }
    }
}

【问题讨论】:

  • 那么,您尝试过哪些操作,哪些操作不适合您?

标签: c# asp.net


【解决方案1】:

除非这些图像实际上是同一文件的副本,否则简单的二进制比较将不起作用。即使是一点点差异或不同的文件格式也会彻底破坏它。并且将它们视为相同的这一点进入了人工智能研究。

如果这些文件直到最后一个字节都相同,您可以通过为每个图像存储一个哈希值来相应地加快检查速度。将您尝试添加的图像的哈希值与所有现有的图像哈希值进行比较,以预过滤它们不能相同。您仍然应该进行二进制比较,因为即使使用哈希值,您也可能出现错误的肯定/冲突(两个不同的输入具有相同的输出)。

由于您还计划存储大量图像,我认为文件流属性可能会有所帮助:https://www.simple-talk.com/sql/learn-sql-server/an-introduction-to-sql-server-filestream/

【讨论】:

    【解决方案2】:
    • 有一个名为data varbinary(max) 的列来存储图像文件
    • 查询语句不需要where条件
    • 删除添加参数行。然后,通过单独比较二进制数据,它可以完美运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多