Click to See Complete Forum and Search --> : byte[] from filestream or from image have different lengths


dannystommen
April 9th, 2009, 02:33 AM
I want to get the byte[] from an image file.

byte[] fromFile;
using (FileStream fs = new FileStream("myImage.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read)) {
fromFile= new byte[fs.Length];
fs.Read(fromFile, 0, Convert.ToInt32(fs.Length));
}
// fromFile has a length of 5308

using (MemoryStream ms = new MemoryStream()) {
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo _codecInfo = null;
foreach (ImageCodecInfo codec in codecs) {
if (codec.MimeType == "image/jpeg")
_codecInfo = codec;
}

byte[] fromImage;
using (Image img = Image.FromFile("myImage.jpg")) {
img.Save(ms, ImageFormat.Jpeg);
fromImage = ms.ToArray();
}
}
//fromImage has a length of 5835


why does the 2 byte arrays have a different length? it is the same file.

I also tried

using (MemoryStream ms = new MemoryStream()) {
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo _codecInfo = null;
foreach (ImageCodecInfo codec in codecs) {
if (codec.MimeType == "image/jpeg")
_codecInfo = codec;
}

using (EncoderParameters _encoderParameters = new EncoderParameters()) {
_encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.RenderMethod, (long)100);

img.Save(ms, _codecInfo, _encoderParameters);
fromImage = ms.ToArray();
}

and some other encoderParameters, but they all give a different length

boudino
April 9th, 2009, 05:25 AM
Maybe each image is stored in different format? E.g. bmp vs. jpg.

dannystommen
April 9th, 2009, 05:27 AM
No, the image is not stored in an different format. The image is saved via Photoshop as an jpg file.

boudino
April 9th, 2009, 06:37 AM
I thought in memory as .NET object. The first is read as raw bytes from file, the second is an instance of Image object asked for its bytes representation. There can be some metadata in the second case, or some transformation could come into play while the image was instantinated. Try to save the image to file and read raw data from the file again, or compare the files.