0

I'm trying to show my uploaded pictures in a GridView, but everytime I want to get the data from the database and decode the byte array into a base64 string again, I get an System.InvalidCastException. It says that the object System.String can't be converted to System.Byte[].

Here are my methods that I have written so far:

Image-Table in Database:

CREATE TABLE [dbo].[epadoc_mod_wound_image] (
    [image_id]     INT            IDENTITY (1, 1) NOT NULL,
    [image_file]   NVARCHAR (MAX) NULL,
    [file_size]    VARCHAR (50)   NULL,
    [image_format] VARCHAR (100)  NULL,
    [image_time]   DATETIME       NULL,
    [wound_id]     INT            NULL,
    PRIMARY KEY CLUSTERED ([image_id] ASC),
    FOREIGN KEY ([wound_id]) REFERENCES [dbo].[epadoc_mod_wound_details] ([wound_id])

Uploading-Method:

 protected void btn_Upload_Click(object sender, EventArgs e)
        {

            try
            {
                // checks, if the uploaded picture either is a jpeg- or a png-file
                if (uploadWoundPic.PostedFile.ContentType == "image/jpeg" | uploadWoundPic.PostedFile.ContentType == "image/png")
                {
                    // read the image properties                        
                    string imageFormat = uploadWoundPic.PostedFile.ContentType;
                    int fileSize = uploadWoundPic.PostedFile.ContentLength;
                    string imageSize = fileSize.ToString();
                    DateTime imageTime = DateTime.Now;

                    // convert the image to Byte Array
                    byte[] bytes = new byte[fileSize];
                    HttpPostedFile img = uploadWoundPic.PostedFile;
                    img.InputStream.Read(bytes, 0, fileSize);
                    // saves the filename in a variable
                    string filename = Path.GetFileName(uploadWoundPic.PostedFile.FileName);


                    // convert the Byte Array to Base64 Encoded string
                    string imageFile = Convert.ToBase64String(bytes, 0, bytes.Length);


                    // save picture on server in given folder
                    _db.SaveWoundImage(imageFile, imageSize, imageFormat, imageTime);
                }
            }
            catch (Exception)
            {

            }
        }

That works without problems.

The GridView-Control with the Image:

<asp:GridView ID="woundImageGridview" runat="server" AutoGenerateColumns="false">
                            <Columns>
                                <asp:BoundField DataField="wound_id" HeaderText="ID_Wunde" SortExpression="File"></asp:BoundField>
                                <asp:BoundField DataField="image_file" HeaderText="Imagefile" SortExpression="File"></asp:BoundField>
                                <asp:TemplateField HeaderText="Image">
                                    <ItemTemplate>
                                        <asp:Image ID="woundimage" runat="server" ImageUrl='<%# "data:image/png;base64," + Convert.ToBase64String((byte[])Eval("image_file"))%>' Height="150px" Width="150px"></asp:Image>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                        </asp:GridView>

And my method to get the data from the database:

private void BindData()
        {
            ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["pflegedokumentationConnectionString"];
            SqlConnection conn = new SqlConnection(connectionString.ConnectionString);
            SqlCommand query = new SqlCommand("SELECT * FROM epadoc_mod_wound_image", conn);
            conn.Open();
            woundImageGridview.DataSource = query.ExecuteReader();
            woundImageGridview.DataBind();
            conn.Close();
        }

But everytime I call that method e.g. on PageLoad or on a button click I get this exception.

6
  • [image_file] NVARCHAR (MAX)? Why not VARBINARY(MAX)? Commented Jan 18, 2019 at 11:34
  • strangely the upload doesn't work with varbinary(MAX), i can click upload and i dont get an exception, but the image isn`t stored in the database Commented Jan 18, 2019 at 11:38
  • What you mean "doesn't work with varbinary(MAX)", you mean saving byte[] to DB? If you don't want or can't store as varbinary then save your base64 string inside varbinary instead of byte[]. Commented Jan 18, 2019 at 11:39
  • 1
    in this point -> Convert.ToBase64String((byte[]) they are all ready String, not byte. Commented Jan 18, 2019 at 11:39
  • One cannot simply cast string into bytes. you would need to byte[] bytes = Encoding.ASCII.GetBytes(someString); in order to get byte[] since the input is in string form from database and after that pass the byte array to convert Commented Jan 18, 2019 at 11:41

1 Answer 1

2

The message is clear

System.String can't be converted to System.Byte[]

at that point

<asp:Image ID="woundimage" runat="server" ImageUrl='<%# "data:image/png;base64," 
 + Convert.ToBase64String((byte[])Eval("image_file"))%>' Height="150px" Width="150px"></asp:Image>

the

Eval("image_file")

is a string, not a byte[], the declaration is string, the save to the database is string - so this is the main error.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah you are right i just didnt notice that i pass the String to the database function and not the byte-array - so varbinary can't work with String. Thanks for the hint :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.