Search code examples
c#jpegmemorystreamaspose

Can't Save and reCreate Aspose jpeg image to/from stream


Hopefully this is just some detail I'm missing...

I'm creating a unit test for a converter which sticks a JPG into a new PDF doc. Both the new document and Jpeg are saved to memory streams, and then both streams are passed in. PDF doc works fine, but the Jpeg will save to the stream, and then I can't create a new JpegImage from it. The code is simple enough...

        converter = new Converters.JpegToPdfConverter();

        jpegConverterSourceStream = new MemoryStream();
        sourceStream = new MemoryStream();
        destinationStream = new MemoryStream();

        var document = new Document();
        var page = document.Pages.Add();
        page.PageInfo = testPageInfo;

        document.Save(destinationStream);

        var img = new Aspose.Imaging.FileFormats.Jpeg.JpegImage(imageWidth, imageHeight);

        img.Save(jpegConverterSourceStream, ImageOptions);

        jpegConverterSourceStream.CopyTo(sourceStream);

        JpegImage img2 = new JpegImage(sourceStream);

//and the last line fails with

ImageLoadException: Cannot open an image. The image file format may be not supported at the moment.

It doesn't make any sense... I just saved the exact same class. Is there something funny going on in the conversion to/from a memory stream?


Solution

  • Minor issue - you need to reset the position of the stream before copying from it -

    jpegConverterSourceStream.Position = 0;
    jpegConverterSourceStream.CopyTo(sourceStream);