1

I have a web api service that accepts an image (byte[]) as part of the data for the post/create method. I save the image data in a sql server blob column. When I use the corresponding get method I see the data as

"ffd8ffe000104a46494600010100000100010000ffdb004300100b0c0e0c0a100e0d0e..." (shortened)

When I look at the bytes of the original image they look just like that (snip from my binary editor):

![Manual Method[(http://sdrv.ms/1bjgsnX)

I need a way to convert my data into the correct jpg file. I’ve tried several things but finally had to manually do it. I didn't include here my attempts at using Image but they were also many and unsuccessful. There must be a more standard way of doing what I need to do. For all of these methods I use the same File writing code:

string base64String = Convert.ToBase64String(photoFromDB, Base64FormattingOptions.None);
//various methods to convert that to a byte[] tempBytes
string DestFilePath = "testManual.jpg";
System.IO.FileStream fs = new System.IO.FileStream(DestFilePath,
System.IO.FileMode.Create, System.IO.FileAccess.Write);
fs.Write(tempBytes, 0, tempBytes.Length);
fs.Close();

Here are my attempts and the outcomes:

![All Methods[(http://sdrv.ms/1bjgegH)

//Manual method that works but I don’t like.
byte[] tempBytes = new byte[base64String.Length/2];
string tempString;
byte tempByte;
int count = 0;

for (int i = 0; i < base64String.Length; i = i+2)
{
    tempString = base64String.Substring(i, 2);
    tempByte = Convert.ToByte(tempString, 16);
    tempBytes[count++] = tempByte;
}

//Unicode convert
//I can see my data here but it has extra nulls included.

tempBytes = System.Text.Encoding.Unicode.GetBytes(base64String);



//UTF32 convert
//again can see my data but even more nulls included

tempBytes = System.Text.Encoding.UTF32.GetBytes(base64String);


//UTF7, UTF8, and Default, ASCII, BigEndianUnicodegive me the same output
//I can see my data but it isn’t correct yet

tempBytes = System.Text.Encoding.UTF7.GetBytes(base64String);
tempBytes = System.Text.Encoding.UTF8.GetBytes(base64String);
tempBytes = System.Text.Encoding.Default.GetBytes(base64String);
tempBytes = System.Text.Encoding.ASCII.GetBytes(base64String);
tempBytes = System.Text.Encoding.BigEndianUnicodegive.GetBytes(base64String);

What’s the secret sauce I’m missing?

  • What datatype does your blob field have? if your using sql server i would recommend varbinary(maxsize) this way you would not have to deal with the base64 encoding and could just cast the result to byte[], also your images don't seem to work! – Peter Feb 10 '14 at 15:19
  • May I ask - are you just trying to save the file? If so - you don't need to worry about the content so much as just saving to the file or database. – drew_w Feb 10 '14 at 15:20
  • `ffd8ff` looks like the start of an JPEG magic number, and that looks like a string with hexadecimal notation. See the linked possible duplicate on how to get a byte array out of that. From your question it is not clear what exactly you are having trouble with, can you explain some more what you are trying to do and where it goes wrong? – CodeCaster Feb 10 '14 at 15:22
  • See [Download and Upload images from SQL Server via ASP.Net MVC](http://rusanu.com/2010/12/28/download-and-upload-images-from-sql-server-with-asp-net-mvc/) and [FILESTREAM MVC: Download and Upload images from SQL Server](http://rusanu.com/2011/02/06/filestream-mvc-download-and-upload-images-from-sql-server/). – Remus Rusanu Feb 10 '14 at 15:22
  • What is the type of `photoFromDB` is that not already a `byte[]`? – Chris Feb 10 '14 at 15:26
  • Images fixed. datatype is varbinary(maxsize). byte[] tempBytes = (byte[])photoFromDB; gives the following output which doesn't work. 7D F7 7C 7D F7 B4 D3 4D 74 E1 AE 3A E3 DE 3A D3 Yes, just trying to save the file in the correct format. I had expected to just do some standard either casting or converting with existing dotnet methods and then saving the file. I didn't expect to have to manipulate the data like I did. My byte array just isn't doing it. – Wendell Gruber Feb 10 '14 at 15:42

3 Answers3

3

I'm not quite sure why you're trying to base64-encode/decode anything here... If you already have a byte array, why not use File.WriteAllBytes(...); to put them into the JPEG file?

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
1

For my use, I wrote two small functions for realise this conversion

 #region public byte[] BitmapToBytes(Image bmp, ImageFormat p_Format)
        public byte[] BitmapToBytes(Image bmp, ImageFormat p_Format)
        {
            MemoryStream stream = new MemoryStream();
            try
            {
                bmp.Save(stream, p_Format);
            }
            catch (Exception ex)
            {
            }
            return stream.ToArray();
        }
        #endregion

        #region public Image BytesToBitmap(byte[] bytes)
        public Image BytesToBitmap(byte[] bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(bytes);
            }
            catch (Exception ex)
            {
            }

            return new Bitmap(stream);
        }
        #endregion
tdelepine
  • 1,986
  • 1
  • 13
  • 19
  • Just tried this method as well. My byte[] apparently just isn't in the format that all these ideas expect it to be in. This gives my an invalid argument when it tries to create the Bitmap. – Wendell Gruber Feb 10 '14 at 16:07
  • If you really receive a encoding Base64 string for image you can converted by statement Convert.FromBase64String() – tdelepine Feb 10 '14 at 16:36
0

Thorsten Dittmar is right.

  1. You have data in byte[]
  2. Then you make conversion TO Base64 string

    string base64String = Convert.ToBase64String(photoFromDB, Base64FormattingOptions.None); //various methods to convert that to a byte[] tempBytes ....

  3. Then you do some conversion from string (Base64String) back to array[]!

    ... tempByte = Convert.ToByte(tempString, 16); ...

    Why? Just try File.WriteAllBytes(...) as Thorsten Dittmar suggested.

Jaroslav Kubacek
  • 1,387
  • 18
  • 26
  • That was my first (many hours ago attempt). When that didn't work I started looking at the data manually to figure out what needed to be done. My manual manipulation was the only thing that worked. These images are being uploaded by an android device going through Sybase Unwired Platform to our REST services. I can't control what it looks like when it initially comes in. – Wendell Gruber Feb 10 '14 at 16:00
  • Ok. Please, can you put somether some testing data? Link to small testing image + text file with content of base64String after operation Convert.ToBase64String(photoFromDB, Base64FormattingOptions.None); Text file encoded in UTF32. Thanks – Jaroslav Kubacek Feb 10 '14 at 20:05