Samir Ríos Samir Ríos - 3 months ago 87
C# Question

Cannot access a closed stream Exception

I'm trying to "copy" an image from another image, reduce it's height and width, and return it as stream to retrieve in another class and show as an Image. But when I get the stream in the other class, and exception is thrown; "cannot access to closed stream".

This method gets the image path, reduces its size and returns as a stream.

public Stream getImagenCopia (string dataImagen)
{
Bitmap ImageOrig = BitmapFactory.DecodeFile (dataImagen);
var ImagenCopia = Bitmap.CreateScaledBitmap (ImageOrig, 80, 80, false);


using (MemoryStream ms = new MemoryStream ())
{
ImagenCopia.Compress (Bitmap.CompressFormat.Jpeg, 40, ms);

return ms;
}
}


This method receives the stream and sets it in Image source

var cim = auxFotos.getImagenCopia(path);
setImagen(img, cim);

void setImagen (Image img, Stream strm)
{
img.Source = ImageSource.FromStream (() =>
{
return strm;
});
}

Answer

You're disposing of the MemoryStream because you're using a using block. By the time you try to use the return value later in your code, it's unavailable.

using (MemoryStream ms = new MemoryStream ())
{
    ImagenCopia.Compress (Bitmap.CompressFormat.Jpeg, 40, ms);

    return ms;
}

Remove the using statement:

Bitmap ImageOrig = BitmapFactory.DecodeFile(dataImagen);
var ImagenCopia = Bitmap.CreateScaledBitmap(ImageOrig, 80, 80, false);

var ms = new MemoryStream());
ImagenCopia.Compress(Bitmap.CompressFormat.Jpeg, 40, ms);
return ms;

If you see memory consumption spike because resources aren't being garbage collected, you may have to clean it up manually after you're done using it, perhaps by calling .Dispose() on it.

Comments