Image Hash inserting in C#

半腔热情 提交于 2020-01-07 01:49:45

问题


When i upload an image hash is also generated with that image i store image in db but problem is how can i store hash in database.Below is my code.

private void FirstpictureBox_Click(object sender, EventArgs e)
        {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Title = "Select First Image";
        ofd.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
        if (ofd.ShowDialog() == DialogResult.OK)
            {
            FirstpictureBox.Image = new Bitmap(ofd.FileName);
            byte[] imgBytes = new byte[0];

            //convert image to byte array
            imgBytes = (byte[])converter.ConvertTo(FirstpictureBox.Image, imgBytes.GetType());

            //compute SHA hash string from image bytes
            string hash = ComputeHashCode(imgBytes);
            }
        }
private string ComputeHashCode(byte[] imgBytes)
    {
        //Compute hash bytes
        byte[] hash = shaEncryptor.ComputeHash(imgBytes);

        //Convert hash bytes to string representation
        return Convert.ToBase64String(hash);

    }

    public void ImageHash(string hash)
    {

    }
private void SaveRecord()
        {
            ImageHash(hash);
        string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
        string cmdString = "INSERT INTO users (img1,hash) VALUES (@firstimage,@hash)";
        using (OleDbConnection con = new OleDbConnection(connString))
            {
            using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
                {
                con.Open();
                cmd.Parameters.AddWithValue("@firstimage", savePhoto());
                cmd.Parameters.AddWithValue("@hash", hash);
                cmd.ExecuteNonQuery();
                }
            }

        }

When i call ImageHash(hash) function in SaveRecord() function it give me an error.hash doesn't exist in current context.how can i fix this problem.


回答1:


Declare your hash variable at class level instead (that is, outside any function or method).

As it is now, you have declared the string at function/method level, which means only FirstpictureBox_Click() will have access to it. Just move the declaration out of the method and you are good to go.

string hash;

private void FirstpictureBox_Click(object sender, EventArgs e)
{
    ...your code...
    hash = ComputeHashCode(imgBytes);
}


来源:https://stackoverflow.com/questions/36578134/image-hash-inserting-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!