Reputation: 85
I have this code that saves an image to disk
public static void SaveImage(Bitmap picture, string path)
{
// Comprimir
ImageCodecInfo encoder = GetJPGEncoder();
// Create an Encoder object based on the GUID
// for the Quality parameter category.
System.Drawing.Imaging.Encoder myEncoder =
System.Drawing.Imaging.Encoder.Quality;
// Create an EncoderParameters object.
// An EncoderParameters object has an array of EncoderParameter
// objects. In this case, there is only one
// EncoderParameter object in the array.
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
myEncoderParameters.Param[0] = myEncoderParameter;
//picture.
picture.Save(path, encoder, myEncoderParameters);
}
but now I need to get the result as a byte[]. I can't find a way to get the result in memory so that I can convert it to byte[]. I thought about loading the file after saving it in the harddrive, but that would be completely unnecessary. Does anyone know if I can achieve this?
Upvotes: 1
Views: 2748
Reputation: 46909
Use this:
using(var stream = new MemoryStream())
{
picture.Save(stream, encoder, myEncoderParameters);
return stream.ToArray();
}
Upvotes: 3
Reputation: 3813
Use a MemoryStream
. One of the overloads of the Save()
method takes a Stream
.
Upvotes: 1