LiamHT
LiamHT

Reputation: 1332

uploading to azure storage from memorystream returning an empty file

I'm writing a System.Drawing.Bitmap to Azure storage using a memory stream. I have the correct credentials and everything azure side wires up correctly. I have uploaded an image into a blob successfully using an input stream so I think it must be a problem with how i am using the memorystream object.

After looking about for a while, the general solution to my problem looked to be setting the memorystream position to 0, that hasn't worked for me however and an empty file is still being saved into azure.

my code is:

 using (image)
 {
 System.IO.MemoryStream ms = new MemoryStream();

 //create an encoder parameter for the image quality
 EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

 //get the jpeg codec
 ImageCodecInfo imgCodec = ImageUtilities.GetEncoderInfo(CodecInfo);

  //create a collection of all parameters that we will pass to the encoder
  EncoderParameters encoderParams = new EncoderParameters(1);

  //set the quality parameter for the codec
  encoderParams.Param[0] = qualityParam;

  //Move the pointer to the start of stream.
  ms.Position = 0;

  image.Save(ms, imgCodec, encoderParams);

  blockBlob.UploadFromStream(ms);
}

The image element that is saved at the end has data in it. at debug is holds the correct length etc. so the problem is somewhere in the uploading step

Upvotes: 7

Views: 6398

Answers (1)

Guillaume
Guillaume

Reputation: 13138

You have to rewind your memory Stream after saving the image and before uploading :

  //...

  //Move the pointer to the start of stream.
  ms.Position = 0;

  image.Save(ms, imgCodec, encoderParams);
  //HERE !!!
  ms.Position = 0;

  blockBlob.UploadFromStream(ms);
}

Upvotes: 17

Related Questions