Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After fileStream.CopyTo(memoryStream), memoryStream is null

So, I have the function, which gets BitmapImage, I need to save it to iso storage and convert to Base64 (for sending to server). However, copying from fileStream to memoryStream is not successful.

public void SetImage(BitmapImage bitmap)
{
    if (isoFiles.FileExists(Settings.FILE_AVATAR_JPG))
        isoFiles.DeleteFile(Settings.FILE_AVATAR_JPG);

    var fileStream = isoFiles.CreateFile(Settings.FILE_AVATAR_JPG);
    var wb = new WriteableBitmap(bitmap);
    wb.SaveJpeg(fileStream, 120, 120, 0, 85); // file is saved 

    var memoryStream = new MemoryStream();
    fileStream.CopyTo(memoryStream);          // here, memoryStream is null
    byte[] result = memoryStream.ToArray();
    fileStream.Close();

    var base64 = Convert.ToBase64String(result);
}
like image 697
Vitalii Vasylenko Avatar asked Apr 18 '13 10:04

Vitalii Vasylenko


1 Answers

Stream.CopyTo copies from the current position of fileStream which has been changed by SaveJpeg() so you need to reset it;

var memoryStream = new MemoryStream();

fileStream.Position = 0;
fileStream.CopyTo(memoryStream);  
like image 129
Alex K. Avatar answered Sep 18 '22 17:09

Alex K.