开发者

convert uploaded file to bitmap image in asp.net

I have a Fi开发者_开发百科leUpload box and button. In my scenario the files that are going to be uploaded are image files. I want to convert these image files into bitmaps and store them temporarily in a buffer.

I have a function which takes two bitmap inputs and tells us whether the two files match or not.

One of the file will come from the FileUpload control on ButtonClick event and the other bitmap will be read from Database.

Can anyone tell me as to how do I convert these files to bitmaps and pass both the bitmap objects to the function.


You can get a bitmap of your uploaded image as follows:

System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(userFileUpload.PostedFile.InputStream);

You then get the stored copy (which hopefully is stored as a byte array and you have an ID to get it), and then convert it to bitmap as follows

byte[] byteArrayStoredImage = ImageService.GetImageData(imageID);
MemoryStream imgStream = new MemoryStream(byteArrayStoredImage);
System.Drawing.Bitmap bmpStoredImage = new Bitmap(imgStream);

With the two bitmaps in hand (bmpPostedImage and bmpStoredImage), you can then call the function to do the comparison. For a start you can try this function from http://www.dreamincode.net/code/snippet2859.htm and see how it it goes. there may be more efficient functions out there to do the comparison, trying out a google search for that will be a goo thing to try.

EDIT

Find below the code to retrieve image from the database with the assumptions I put in the comment below:

    public byte[] GetImageData(string imageID)
    {
                string connectionString = ConfigurationManager.ConnectionStrings["connectionstringname"];
        SqlConnection connection = SqlConnection(connectionString);
        connection.Open();
        SqlCommand command1 = new SqlCommand("select imgfile from myimages where imgname=@imageId", connection);
        SqlParameter myparam = command1.Parameters.Add("@imageId", SqlDbType.NVarChar, 30);
        myparam.Value = imageID;
        byte[] img = (byte[])command1.ExecuteScalar();
        connection.Close();
        return img;
    }

and then change ImageService.GetImageData(imageID) to GetImageData(imageID);

Note also, that error handling is not addressed here, so might have to factor that into your final code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜