Search code examples
c#imageazurememorystream

Can I convert a bitmap to a jpeg when saving the bitmap to a memory stream?


I'm attempting to save a bitmap file as a jpeg into Azure without saving it locally in the process, so I am first saving the bitmap as a jpeg in a MemoryStream.

But when I execute the following code, the file uploads but it did not convert the bitmap correctly. If I view the file, the viewer displays 'Invalid Image.'

I read somewhere that bitmaps cannot be converted to jpegs in memory. Could that be what is happening here?

        // Retrieve reference to a blob
        var blobContainer = GetBlobContainer(Properties.Settings.Default.BlobContainerName);
        var blob = blobContainer.GetBlockBlobReference(blobFilePath);

        // Save bitmap to jpeg in MemoryStream, then upload to Azure blob
        //var writer = new StreamWriter(blob.OpenWrite());
        MemoryStream memStr = new MemoryStream();
        bitmap.Save(memStr, System.Drawing.Imaging.ImageFormat.Jpeg);
        blob.UploadFromStream(memStr);

Solution

  • After writing to the MemoryStream you need to "rewind" it by setting memStr.Position = 0 before any attempts to read it (in your case, uploading it to Azure)

    "Be kind, please rewind."