XImage fromStream returns 'Parameter Not Valid'

92 Views Asked by At

I cannot seem to work out why my image byte array when retrieved from my SQL database is not able to be read as a valid stream using XImage.FromSource().

I have used the same method of saving and retrieving the image in other areas of the application and images are shown correctly when retrieved, and I have tested the same images which are erroring using fromsource() in these other areas mentioned and images do show up correctly so I would not say this is an issue with how I have saved the varbinary to database.

dr["Image"] shows in debug that is has the bytes and is not null

This is my code:

connectionString();

con.Open();
com.Connection = con;
com.CommandText = "SELECT TOP(1) [Image] FROM dbo.recovery_job_images WHERE [JobNo] = '21802' AND [ImageName] = 'DAMAGE IMAGE'";

dr = com.ExecuteReader();

while (dr.Read())
{
    byte[] byteArray = (byte[])dr["Image"];

    XImage image2;

    using (var stream = new MemoryStream(byteArray))
    {
        image2 = XImage.FromStream(stream); //always returns parameter not valid
    }
    XImage image = XImage.FromFile("_Logo.png");
    gfx.DrawImage(image, 400, 20, 140, 74);

    //pdfDoc.Save("C:\\" + filename);
    pdfDoc.Save(filename);
}
1

There are 1 best solutions below

0
TryingAgain On

Solved the issue, let me know if my understanding of the problem is correct but it seemed to be an issue with the fact that when I insert these images into the database I first convert them to a base64 string and get the bytes:

public async Task<string> SendPODAsync()
    {
        try
        {
            var base64DamageImage = System.Convert.ToBase64String(damageImageBytes);
            var base64SignatureImage = System.Convert.ToBase64String(signatureImageBytes);

            base64DamageImage = "data:image/png;base64," + base64DamageImage;
            base64SignatureImage = "data:image/png;base64," + base64SignatureImage;

To solve this I found I had to remove the data type headers and do some base64 conversions to get a byte stream that is happy

dr = com.ExecuteReader();

        while (dr.Read())
        {
            var base64 = System.Text.Encoding.UTF8.GetString(((byte[])dr["Image"]));
            base64 = base64.Substring(base64.IndexOf(",") + 1); //remove data type header data:image/png;base64,

            Byte[] bitmapData = Convert.FromBase64String(base64);

            XImage image2;
            using (var stream = new MemoryStream(bitmapData))
            {
                image2 = XImage.FromStream(stream);
            }
            XImage image = XImage.FromFile("SVL_Logo.png");
            gfx.DrawImage(image, 400, 20, 140, 74);
            gfx.DrawImage(image2, 200, 100, 140, 74);

            //pdfDoc.Save("C:\\" + filename);
            pdfDoc.Save(filename);
        }

        con.Dispose();
        con.Close();

And thanks to all who commented as you where correct with the issue being in dr["Image"]