I'm starting with a stream that represents an image, and drawing it onto a larger image. To do this, I wrote an extension method for
MemoryStream
s. When I try to save the image into a new stream, the code is throwing "Parameter is not valid" exception.
Facts:
- The stream on which I'm calling the method is NOT null, and contains data.
- When I get to the statement in question, the new image is not null, and the encoder appears to be correct.
- The recieving
MemoryStream
object is NOT null (indeed, that would have caused a completely different exception).
I have no clue as to why I'm getting this exception.
As you can see, I'm making use of
using
statements, but nothing is out of scope when I get to the statement that is throwing the exception, and the exception does not indicate WHICH parameter is invalid.
Note - the
GetEncoder
method was written to black-box and cleanup the methods that needed to use that code. As stated above, the encoder appears to be valid.
public static MemoryStream AddMatting(this MemoryStream stream, Size size, Color color)
{
MemoryStream newStream = new MemoryStream();
using (Image image = Bitmap.FromStream(stream))
{
using (Bitmap matting = new Bitmap(size.Width, size.Height, image.PixelFormat))
{
using (Graphics g = Graphics.FromImage(matting))
{
int x = (int)((matting.Width-image.Width)*0.5);
int y = (int)((matting.Height-image.Height)*0.5);
g.Clear(color);
g.DrawImage(image, x, y);
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
using (EncoderParameters encParams = new EncoderParameters(1))
{
encParams.Param[0] = new EncoderParameter(Encoder.Quality, 100);
try
{
matting.Save(newStream, jpgEncoder, encParams);
}
catch (Exception ex)
{
if (ex != null) {}
}
}
}
}
}
return newStream;
}
What I have tried:
0) I added
true,true
to the method call to
FromStream
, thinking maybe some how the stream was invalid, but that did not trigger an
ArgumentInvalid
exception, so the stream itself is valid).
1) I tried reducing the method to its simplest form (which takes the incoming stream, makes it an image, and then saves it right back to a new stream), and still get the exception:
public static MemoryStream AddMatting(this MemoryStream stream, Size size, Color color)
{
MemoryStream newStream = new MemoryStream();
using (var image = Bitmap.FromStream(stream))
{
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
using (EncoderParameters encoderParameters = new EncoderParameters(1))
{
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100);
try
{
image.Save(newStream, jpgEncoder, encoderParameters);
}
catch (Exception ex)
{
if (ex != null) {}
}
}
}
return newStream;
}