This project has moved and is read-only. For the latest updates, please go here.

Writing to an already open stream?

Apr 2, 2014 at 2:02 PM
I have a possible issue when writing to an open stream. My code works like this:
  1. Open a file stream called destinationStream:
  2. create MagickImage object
  3. call object.Write(destinationStream) which works fine
  4. create MagickImage object2
  5. call object2.Merge() to add a watermark
  6. call object2.Write(destinationStream) which seems to work fine
  7. dispose of destinationStream
The resulting file is an image that is twice the size(2MB) that it should be and the image does not have the watermark. If I dispose of the destinationStream between the two write calls, and then reopen the stream everything works fine. Also, the file size is 1MB, not 2MB.

Is it possible that Magick requires my file stream to be closed/reopened between writes to produce the desired effect? And if you think this is simply a C# file stream thing, then disregard.

Apr 2, 2014 at 2:29 PM
Aren't you missing a step in the example above? Step 5 calls Merge of object2 but MagickImage does not contain a Merge method. You probably created a MagickImageCollection at some point.

The reason you are not seeing the watermark is because you are writing two images to the stream instead of only one. An image looks something like this:
| Header of image  |
| +--------------+ |
| | Size of data | |
| +--------------+ |
| Image data       |
If your image contains more data then specified in the header it is considered to be garbage. Some image readers will raise an error but most readers will just ignore the rest after the 'Image data' block.

You should only write the result of the Merge method to the destinationStream.
using (MagickImageCollection images = new MagickImageCollection())
  using (MagickImage result = images.Merge())
Apr 2, 2014 at 2:46 PM
I apologize for my pseudo code not being 100% accurate. I am in fact creating an MagickImageCollection and calling Merge on that guy, so we're good there. The second thing is that my code looks almost identical to yours in terms of writing the result of the Merge to the stream. Since the file size is being doubled, my guess is that the second write is successful but possibly on another layer perhaps, instead of overwriting the result of the first Write call.
Apr 2, 2014 at 5:04 PM
Edited Apr 2, 2014 at 5:04 PM
I think you should read my reply again. Each write action creates one image. When you write two MagickImages to the same stream they don't automatically get merged. And it also does not mean that layers are being created.