Reputation: 3650
I want to convert a gif file to byte[].
I tried two method, but the result is different.Which one is right?
Method 1:
Using the
bytes =File.ReadAllBytes(filepath)
; This return a byte array.
Methond 2:
private byte[] ImageToBytes(Image image, ImageFormat format) { using (MemoryStream ms = new MemoryStream()) { image.Save(ms, format); return ms.ToArray(); } } Bitmap image = new Bitmap(@"c:\\1.gif");
Then call
bytes = ImageToBytes(image, ImageFormat.Gif);
The two bytes have a little bit of difference. Which one I should trust?
Upvotes: 0
Views: 2315
Reputation: 10781
Both are "right", in that they're the result of what you told the computer to do. One is the byte array directly from the file, and the other is the result of decoding the file and re-encoding it, which could end up being the exact same array, or wildly different. Likely the one you want is the first one, since it's significantly faster since it doesn't go through the decode/encode process and keeps the original data. The only reason I can think of to use the second one is if you really need to analyze the output of the .NET gif encoding process for some reason.
The second option is the same as the below, except without needing the temp file because it does everything in memory. So all you're doing is loading it then saving it then loading it again.
Bitmap image = new Bitmap(@"c:\1.gif");
image.Save("c:\1_temp.gif", ImageFormat.Gif);
bytes = File.ReadAllBytes(@"c:\1_temp.gif");
Upvotes: 0
Reputation: 120480
Your "methond 2" is reencoding/recompressing the file. It's likely to be significantly different, and (in all likelihood) degraded in quality.
Upvotes: 1