/// <summary> /// Function to load an image from a stream. /// </summary> /// <param name="stream">The stream containing the image data to read.</param> /// <param name="size">The size of the image within the stream, in bytes.</param> /// <returns>A <see cref="IGorgonImage"/> containing the image data from the stream.</returns> /// <exception cref="GorgonException">Thrown when the image data in the stream has a pixel format that is unsupported.</exception> protected override IGorgonImage OnDecodeFromStream(Stream stream, long size) { var wic = new WicUtilities(); Stream streamAlias = stream; try { // If we have a stream position that does not begin exactly at the start of the stream, we have to wrap that stream in a // dummy stream wrapper. This is to get around a problem in the underlying COM stream object used by WIC that throws an // exception when the stream position is not exactly 0. if (streamAlias.Position != 0) { streamAlias = new GorgonStreamWrapper(stream, 0, size); } IGorgonImage result = wic.DecodeImageData(streamAlias, size, SupportedFileFormat, DecodingOptions, FrameOffsetMetadataNames); if (result == null) { throw new IOException(string.Format(Resources.GORIMG_ERR_FILE_FORMAT_NOT_CORRECT, Codec)); } if (stream.Position != streamAlias.Position) { stream.Position += streamAlias.Position; } return(result); } finally { if (streamAlias != stream) { streamAlias?.Dispose(); } wic.Dispose(); } }
public void StreamWrapperTest() { byte[] block1 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; using (MemoryStream stream = new MemoryStream()) { stream.Write(block1, 0, block1.Length); stream.Position = 0; using (GorgonStreamWrapper wrapper = new GorgonStreamWrapper(stream, 6, 5)) { byte[] actualBytes = new byte[5]; Assert.AreEqual(5, wrapper.Read(actualBytes, 0, 5)); for (int i = 0; i < actualBytes.Length; ++i) { Assert.AreEqual(block1[i + 6], actualBytes[i]); } Assert.AreEqual(wrapper.Length, wrapper.Position); } Assert.AreEqual(0, stream.Position); using (GorgonStreamWrapper wrapper = new GorgonStreamWrapper(stream, 6, 5)) { byte[] actualBytes = new byte[8]; Assert.AreEqual(5, wrapper.Read(actualBytes, 0, 8)); } using (GorgonStreamWrapper wrapper = new GorgonStreamWrapper(stream, 2)) { byte[] actualBytes = new byte[3]; wrapper.Seek(3, SeekOrigin.Begin); wrapper.Read(actualBytes, 0, 3); for (int i = 0; i < actualBytes.Length; ++i) { Assert.AreEqual(block1[i + 5], actualBytes[i]); } wrapper.Seek(-3, SeekOrigin.End); wrapper.Read(actualBytes, 0, 3); for (int i = 0; i < actualBytes.Length; ++i) { Assert.AreEqual(block1[block1.Length - 3 + i], actualBytes[i]); } } } }