简体   繁体   中英

Converting Uploaded Bitmap to Byte Array and Storing in SQL Server

I am attempting to build an application that allows a user to select an image and then later, upload into an SQL server table.

The problem is that the stored data seems incomplete. I attempted to put it through an online converter (namely http://www.lokowebdesign.com/imagetobinary/ ) but receive an error stating that it is not in a recognized format.

As it is stored in the table the data looks like this:

0xFFD8FFE000104A46494600010201006000600000FFEE000E41646F626500640000000001FFE10DDE4578696600004D4D002A000000080006013200020000001400000056013B00020000000B0000006A47460003000000010005000047490003000000010058000082980002000000160000007687690004000000010000008C

Here are some relevant code snippets:

// the definition for the table, Grid

  DataTable grid = new DataTable("Grid");
        grid.Columns.Add("ID", typeof(int));
        grid.Columns.Add("Description", typeof(String));
        grid.Columns.Add("Points", typeof(int));
        grid.Columns.Add("Score", typeof(List<int>));
        grid.Columns.Add("Current", typeof(int));
        grid.Columns.Add("Comments", typeof(List<String>));
        grid.Columns.Add("SelectedComment", typeof(int));
        grid.Columns.Add("SelectedCommentText", typeof(String));
        grid.Columns.Add("Category", typeof(int));
        grid.Columns.Add("SelectedScore", typeof(int));
        grid.Columns.Add("Image", typeof(byte[]));

// report_details table

insert = new SqlCommand("INSERT into dbo.report_details (reportID, itemID, points, comments, image) " + " VALUES (@reportID, @itemID, @points, @comments, @image)", con);
            insert.Parameters.Add("@reportID", SqlDbType.Char, 5, "reportID");
            insert.Parameters.Add("@itemID", SqlDbType.Int, 5, "itemID");
            insert.Parameters.Add("@points", SqlDbType.Int, 4, "points");
            insert.Parameters.Add("@comments", SqlDbType.Text, 150, "comments");
            insert.Parameters.Add("@image", SqlDbType.Image, (int)Math.Pow(2, 20), "image");

// update report_details (in database) based on the DataGrid bound table, Grid

  foreach (DataRow row in ds.Tables["Grid"].Rows)
        {

            DataRow reportDetailsRow = ds.Tables["Details"].NewRow();

           reportDetailsRow["reportID"] = id;
            reportDetailsRow["itemID"] = row["ID"];
            reportDetailsRow["points"] = row["Current"];

            List<String> comments = (List<String>)row["Comments"];


            reportDetailsRow["comments"] = row["SelectedCommentText"];
            if (row["Image"] != null)
            {


                reportDetailsRow["image"] = row["Image"];
            }

            ds.Tables["Details"].Rows.Add(reportDetailsRow);

        }

        detailsAdapter.Update(ds, "Details");
        tran.Commit();


    }

// called when a user clicks a button to attach an image

    private async void uploadImage(Object sender, RoutedEventArgs e)
    {
        Bitmap photo = null;

        // this is for tablets

try
        {
            capturePhoto capture = new capturePhoto();
            photo = await capture.getImage();


        }
        catch (Exception ex)
        {

// this is what I am actually using for testing 

            OpenFileDialog fileDialog = new OpenFileDialog();

            if (fileDialog.ShowDialog() == true)
            {
                photo = (Bitmap)Bitmap.FromStream(fileDialog.OpenFile());
            }

        }

        DataRowView row = (DataRowView)itemGrid.CurrentItem;
        ImageConverter converter = new ImageConverter();
        byte[] photoBytes = (byte[])converter.ConvertTo(photo, typeof(byte[])); ;
        row["Image"] = photoBytes;


    }

    }

I truly hope I provided enough details, but can supply more if needed. This is a very vexing issue for me, so I would really appreciate any guidance. Thanks so much!

EDIT: I tried the following and the same issue remains:

 private async void uploadImage(Object sender, RoutedEventArgs e)
        {
            Bitmap photo = null;

            try
            {
                capturePhoto capture = new capturePhoto();
                photo = await capture.getImage();


            }
            catch (Exception ex)
            {
                OpenFileDialog fileDialog = new OpenFileDialog();

                if (fileDialog.ShowDialog() == true)
                {
                    photo = (Bitmap)Bitmap.FromStream(fileDialog.OpenFile());
                }

            }

            DataRowView row = (DataRowView)itemGrid.CurrentItem;
           //  ImageConverter converter = new ImageConverter();
            // byte[] photoBytes = (byte[])converter.ConvertTo(photo, typeof(byte[])); ;
            MemoryStream mem = new MemoryStream();
            using (mem)
            {
                photo.Save(mem, System.Drawing.Imaging.ImageFormat.Jpeg);
                row["Image"] = mem.ToArray();
            }
           //  row["Image"] = photoBytes;


        }

        }

First, according to this MSDN article :

ntext , text , and image data types will be removed in a future version of MicrosoftSQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

I'm not sure if there is some bizarre formatting with the Image column type, but the sample data you posted is almost base64, except that it's an invalid length. The code you posted in your edit to save an image looks correct to me, so to test this theory you could convert your image to base64 and compare to what you see in the DB:

var data = mem.ToArray();
var base64 = Convert.ToBase64(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM