简体   繁体   中英

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);

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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM