/// <summary> /// Reads and consumes the next data row which contains a surface line, parsing the data to create an instance /// of <see cref="SurfaceLine"/>. /// </summary> /// <returns>Returns the parsed surface line, or null when at the end of the file.</returns> /// <exception cref="CriticalFileReadException">Thrown when a critical error has occurred, which may be caused by: /// <list type="bullet"> /// <item>The file cannot be found at specified path.</item> /// <item>The specified path is invalid, such as being on an unmapped drive.</item> /// <item>Some other I/O related issue occurred, such as: path includes an incorrect /// or invalid syntax for file name, directory name, or volume label.</item> /// <item>There is insufficient memory to allocate a buffer for the returned string.</item> /// <item>The file is incompatible for importing surface lines.</item> /// </list> /// </exception> /// <exception cref="LineParseException">Thrown when a parse error has occurred for the current row, which may be caused by: /// <list type="bullet"> /// <item>The row doesn't use ';' as separator character.</item> /// <item>The row contains a coordinate value that cannot be parsed as a double.</item> /// <item>The row contains a number that is too big or too small to be represented with a double.</item> /// <item>The row is missing an identifier value.</item> /// <item>The row is missing values to form a surface line point.</item> /// </list> /// </exception> public SurfaceLine ReadSurfaceLine() { if (fileReader == null) { fileReader = StreamReaderHelper.InitializeStreamReader(filePath); ValidateHeader(fileReader, 1); lineNumber = 2; } string readText = ReadNextNonEmptyLine(); if (readText != null) { try { return(CreateSurfaceLine(readText)); } finally { lineNumber++; } } return(null); }
private bool TestColorFormatHeader(StreamReaderHelper stream, ImportedImage ii) { // The SOS header (start of scan). if (stream.GetWord(0, true) == 0xffda) { int components = stream.GetByte(4); if (components < 1 || components > 4 || components == 2) { return(false); } // 1 for grayscale, 3 for RGB, 4 for CMYK. int blockLength = stream.GetWord(2, true); // Integrity check: correct size? if (blockLength != 6 + 2 * components) { return(false); } // Eventually do more tests here. // Magic: we assume that all JPEG files with 4 components are RGBW (inverted CMYK) and not CMYK. // We add a test to tell CMYK from RGBW when we encounter a test file in CMYK format. ii.Information.ImageFormat = components == 3 ? ImageInformation.ImageFormats.JPEG : (components == 1 ? ImageInformation.ImageFormats.JPEGGRAY : ImageInformation.ImageFormats.JPEGRGBW); return(true); } return(false); }
private bool MoveToNextHeader(StreamReaderHelper stream) { int blockLength = stream.GetWord(2, true); int headerMagic = stream.GetByte(0); int headerType = stream.GetByte(1); if (headerMagic == 0xff) { // EOI: last header. if (headerType == 0xd9) { return(false); } // Check for standalone markers. if (headerType == 0x01 || headerType >= 0xd0 && headerType <= 0xd7) { stream.CurrentOffset += 2; return(true); } // Now assume header with block size. stream.CurrentOffset += 2 + blockLength; return(true); } return(false); }
public ImportedImage ImportImage(StreamReaderHelper stream, PdfDocument document) { try { stream.CurrentOffset = 0; int offsetImageData; if (TestBitmapFileHeader(stream, out offsetImageData)) { // Magic: TestBitmapFileHeader updates stream.CurrentOffset on success. ImagePrivateDataBitmap ipd = new ImagePrivateDataBitmap(stream.Data, stream.Length); ImportedImage ii = new ImportedImageBitmap(this, ipd, document); if (TestBitmapInfoHeader(stream, ii, offsetImageData)) { //stream.CurrentOffset = offsetImageData; return ii; } } } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } return null; }
/// <summary> /// Reads and parses the next data row to create a new instance of <see cref="CharacteristicPoints"/>, /// which will contain all the declared characteristic points for some surface line. /// </summary> /// <returns>Returns the parsed characteristic points location, or <c>null</c> when at the end of the file.</returns> /// <exception cref="CriticalFileReadException">Thrown when a critical error has occurred, which may be caused by: /// <list type="bullet"> /// <item>The file cannot be found at specified path.</item> /// <item>The specified path is invalid, such as being on an unmapped drive.</item> /// <item>Some other I/O related issue occurred, such as: path includes an incorrect /// or invalid syntax for file name, directory name, or volume label.</item> /// <item>There is insufficient memory to allocate a buffer for the returned string.</item> /// <item>The file is incompatible for importing characteristic points.</item> /// </list> /// </exception> /// <exception cref="LineParseException">Thrown when a parse error has occurred for the current row, which may be caused by: /// <list type="bullet"> /// <item>The row doesn't use ';' as separator character.</item> /// <item>The row contains a coordinate value that cannot be parsed as a double.</item> /// <item>The row contains a number that is too big or too small to be represented with a double.</item> /// <item>The row is missing an identifier value.</item> /// <item>The row is missing values to form a characteristic point.</item> /// </list> /// </exception> public CharacteristicPoints ReadCharacteristicPointsLocation() { if (fileReader == null) { fileReader = StreamReaderHelper.InitializeStreamReader(filePath); ValidateHeader(fileReader); lineNumber = 2; } string readText = ReadNextNonEmptyLine(); if (readText != null) { try { return(CreateCharacteristicPointsLocation(readText)); } finally { lineNumber++; } } return(null); }
/// <summary> /// Reads the next structure parameter from file. /// </summary> /// <returns>The next <see cref="StructuresParameterRow"/> based on the read file, /// or <c>null</c> when at the end of the file.</returns> /// <exception cref="CriticalFileReadException"> /// Thrown when either: /// <list type="bullet"> /// <item>The file or directory cannot be found.</item> /// <item>The file is empty.</item> /// <item>Some I/O related problem occurred.</item> /// <item>The header is not in the required format.</item> /// </list></exception> /// <exception cref="LineParseException">Thrown when either: /// <list type="bullet"> /// <item>The line does not contain the separator character.</item> /// <item>Location id field is empty or consists only of white-space characters.</item> /// <item>Parameter id field is empty or consists only of white-space characters.</item> /// <item>Numeric value field is not a number or too large/small to be represented as <see cref="double"/>.</item> /// <item>Variance value field is not a number or too large/small to be represented as <see cref="double"/>.</item> /// <item>Boolean field is not a valid value.</item> /// </list></exception> public StructuresParameterRow ReadLine() { if (fileReader == null) { fileReader = StreamReaderHelper.InitializeStreamReader(filePath); lineNumber = 1; IndexFile(fileReader); lineNumber++; } string readText = ReadNextNonEmptyLine(fileReader); if (readText != null) { try { return(CreateStructuresParameterRow(readText)); } finally { lineNumber++; } } return(null); }
public ImportedImage ImportImage(StreamReaderHelper stream, PdfDocument document) { try { stream.CurrentOffset = 0; int offsetImageData; if (TestBitmapFileHeader(stream, out offsetImageData)) { // Magic: TestBitmapFileHeader updates stream.CurrentOffset on success. ImagePrivateDataBitmap ipd = new ImagePrivateDataBitmap(stream.Data, stream.Length); ImportedImage ii = new ImportedImageBitmap(this, ipd, document); if (TestBitmapInfoHeader(stream, ii, offsetImageData)) { //stream.CurrentOffset = offsetImageData; return(ii); } } } // ReSharper disable once EmptyGeneralCatchClause catch { } return(null); }
public static T Deserialize <T>(Stream stream, ITextSerializer <T> textSerializer) { using (var textReader = StreamReaderHelper.NewLeaveOpen(stream)) { var value = textSerializer.Deserialize(textReader); return(value); } }
public T Deserialize(Stream stream) { using (var textReader = StreamReaderHelper.NewLeaveOpen(stream)) { var value = this.TextSerializer.Deserialize(textReader); return(value); } }
/// <summary> /// Performs the parsing of the cache entry data /// </summary> public void Update(byte[] data) { using (MemoryStream memoryStream = new MemoryStream(data)) { memoryStream.Seek(0, SeekOrigin.Begin); // No size size values are included in these entries, so search for utf-16 terminator. int[] ret = data.Slice(0, 0 + (Global.MAX_PATH + 8)).Locate(new byte[] { 00, 00 }); if (ret.Length == 0) { return; } string path = Encoding.Unicode.GetString(data.Slice(0, (UInt32)(0 + ret[0] + 1))); path = path.Replace("\\??\\", string.Empty); if (path.Trim().Length == 0) { return; } Path = path; UInt32 entryOffset = 0 + Global.MAX_PATH + 8; memoryStream.Seek(entryOffset, SeekOrigin.Begin); try { UInt32 lowDateTime = StreamReaderHelper.ReadUInt32(memoryStream); UInt32 highDateTime = StreamReaderHelper.ReadUInt32(memoryStream); long hFT2 = (((long)highDateTime) << 32) + lowDateTime; ModDateTime = DateTime.FromFileTimeUtc(hFT2); } catch (Exception) { ModDateTime = DateTime.MinValue; } FileSize = StreamReaderHelper.ReadUInt64(memoryStream); if (FileSize == 0) { return; } try { UInt32 lowDateTime = StreamReaderHelper.ReadUInt32(memoryStream); UInt32 highDateTime = StreamReaderHelper.ReadUInt32(memoryStream); long hFT2 = (((long)highDateTime) << 32) + lowDateTime; ExecDateTime = DateTime.FromFileTimeUtc(hFT2); } catch (Exception) { ExecDateTime = DateTime.MinValue; } } }
/// <summary> /// Reads the file to determine the number of available <see cref="CharacteristicPoints"/> /// data rows. /// </summary> /// <returns>A value greater than or equal to 0.</returns> /// <exception cref="CriticalFileReadException">Thrown when a critical error has occurred, which may be caused by: /// <list type="bullet"> /// <item>The file cannot be found at specified path.</item> /// <item>The specified path is invalid, such as being on an unmapped drive.</item> /// <item>Some other I/O related issue occurred, such as: path includes an incorrect /// or invalid syntax for file name, directory name, or volume label.</item> /// <item>There is insufficient memory to allocate a buffer for the returned string.</item> /// <item>The file is incompatible for importing characteristic points locations.</item> /// </list> /// </exception> public int GetLocationsCount() { using (StreamReader reader = StreamReaderHelper.InitializeStreamReader(filePath)) { ValidateHeader(reader); return(CountNonEmptyLines(reader, 2)); } }
public static T Deserialize <T>(Stream stream) { using (var reader = StreamReaderHelper.NewLeaveOpen(stream)) { var xmlSerializer = new XmlSerializer(typeof(T)); var output = (T)xmlSerializer.Deserialize(reader); return(output); } }
public static T Deserialize <T>(Stream stream) { using (var textReader = StreamReaderHelper.NewLeaveOpen(stream)) using (var jsonReader = new JsonTextReader(textReader)) { var jsonSerializer = new JsonSerializer(); var output = jsonSerializer.Deserialize <T>(jsonReader); return(output); } }
public static SolutionFile Deserialize(string solutionFilePath) { using (var fileStream = FileStreamHelper.NewRead(solutionFilePath)) using (var textReader = StreamReaderHelper.NewLeaveOpen(fileStream)) { var solutionFileTextSerialializer = new SolutionFileTextSerializer(); var solutionFile = solutionFileTextSerialializer.Deserialize(textReader); return(solutionFile); } }
public static T DeserializeWithoutNamespaces <T>(Stream stream) { using (var reader = StreamReaderHelper.NewLeaveOpen(stream)) using (var xmlReader = XmlReader.Create(reader)) using (var namespaceIgnorantReader = new NamespaceIgnorantXmlReader(xmlReader)) { var xmlSerializer = new XmlSerializer(typeof(T)); var output = (T)xmlSerializer.Deserialize(xmlReader); return(output); } }
public async Task <IEnumerable <ServiceDescriptorDescription> > Deserialize(string filePath) { var jsonSerializer = new JsonSerializer(); using (var streamReader = StreamReaderHelper.New(filePath)) { var json = await streamReader.ReadToEndAsync(); var serviceDescriptorDescriptions = JsonConvert.DeserializeObject <ServiceDescriptorDescription[]>(json); return(serviceDescriptorDescriptions); } }
public void InitializeStreamReader_ValidFile_ReturnsStreamReader() { // Setup string filePath = Path.Combine(testDataPath, "empty.csv"); // Call using (StreamReader streamReader = StreamReaderHelper.InitializeStreamReader(filePath)) { // Assert Assert.IsInstanceOf <StreamReader>(streamReader); } }
/// <summary> /// Imports the image. /// </summary> public ImportedImage ImportImage(Stream stream, PdfDocument document) { StreamReaderHelper helper = new StreamReaderHelper(stream); // Try all registered importers to see if any of them can handle the image. foreach (IImageImporter importer in _importers) { helper.Reset(); ImportedImage image = importer.ImportImage(helper, document); if (image != null) return image; } return null; }
public void InitializeStreamReader_NotExistingFolder_ThrowsCriticalFileReadExceptionWithInnerDirectoryNotFoundException() { // Setup string filePath = Path.Combine(notExistingTestDataPath, "empty.csv"); string expectedMessage = $"Fout bij het lezen van bestand '{filePath}': het bestandspad verwijst naar een map die niet bestaat."; // Call TestDelegate call = () => StreamReaderHelper.InitializeStreamReader(filePath); // Assert var exception = Assert.Throws <CriticalFileReadException>(call); Assert.AreEqual(expectedMessage, exception.Message); Assert.IsInstanceOf <DirectoryNotFoundException>(exception.InnerException); }
public void InitializeStreamReader_NotExistingFile_ThrowsCriticalFileReadExceptionWithInnerFileNotFoundException() { // Setup const string filePath = "nothing"; string expectedMessage = $"Fout bij het lezen van bestand '{filePath}': het bestand bestaat niet."; // Call TestDelegate call = () => StreamReaderHelper.InitializeStreamReader(filePath); // Assert var exception = Assert.Throws <CriticalFileReadException>(call); Assert.AreEqual(expectedMessage, exception.Message); Assert.IsInstanceOf <FileNotFoundException>(exception.InnerException); }
/// <summary> /// Imports the image. /// </summary> public ImportedImage ImportImage(Stream stream, PdfDocument document) { StreamReaderHelper helper = new StreamReaderHelper(stream); // Try all registered importers to see if any of them can handle the image. foreach (IImageImporter importer in _importers) { helper.Reset(); ImportedImage image = importer.ImportImage(helper, document); if (image != null) { return(image); } } return(null); }
private bool TestBitmapFileHeader(StreamReaderHelper stream, out int offset) { offset = 0; // File must start with "BM". if (stream.GetWord(0, true) == 0x424d) { int filesize = (int)stream.GetDWord(2, false); // Integrity check: filesize set in BM header should match size of the stream. // We test "<" instead of "!=" to allow extra bytes at the end of the stream. if (filesize < stream.Length) return false; offset = (int)stream.GetDWord(10, false); stream.CurrentOffset += 14; return true; } return false; }
private bool TestBitmapFileHeader(StreamReaderHelper stream, out int offset) { offset = 0; // File must start with "BM". if (stream.GetWord(0, true) == 0x424d) { int filesize = (int)stream.GetDWord(2, false); // Integrity check: filesize set in BM header should match size of the stream. // We test "<" instead of "!=" to allow extra bytes at the end of the stream. if (filesize < stream.Length) { return(false); } offset = (int)stream.GetDWord(10, false); stream.CurrentOffset += 14; return(true); } return(false); }
private bool TestJfifHeader(StreamReaderHelper stream, ImportedImage ii) { // The App0 header should be the first header in every JFIF file. if (stream.GetWord(0, true) == 0xffe0) { // Now check for text "JFIF". if (stream.GetDWord(4, true) == 0x4a464946) { int blockLength = stream.GetWord(2, true); if (blockLength >= 16) { int version = stream.GetWord(9, true); int units = stream.GetByte(11); int densityX = stream.GetWord(12, true); int densityY = stream.GetWord(14, true); switch (units) { case 0: // Aspect ratio only. ii.Information.HorizontalAspectRatio = densityX; ii.Information.VerticalAspectRatio = densityY; break; case 1: // DPI. ii.Information.HorizontalDPI = densityX; ii.Information.VerticalDPI = densityY; break; case 2: // DPCM. ii.Information.HorizontalDPM = densityX * 100; ii.Information.VerticalDPM = densityY * 100; break; } // More information here? More tests? return(true); } } } return(false); }
private List <DestListEntry> ParseDestList(byte[] data) { List <DestListEntry> entries = new List <DestListEntry>(); try { using (MemoryStream memoryStream = new MemoryStream(data)) { memoryStream.Seek(32, SeekOrigin.Begin); do { DestListEntry destListEntry = new DestListEntry(); memoryStream.Seek(8, SeekOrigin.Current); destListEntry.Droid = new Guid[] { new Guid(StreamReaderHelper.ReadByteArray(memoryStream, 16)), new Guid(StreamReaderHelper.ReadByteArray(memoryStream, 16)) }; destListEntry.Uuid = new Uuid(destListEntry.Droid[1].ToString()); destListEntry.DroidBirth = new Guid[] { new Guid(StreamReaderHelper.ReadByteArray(memoryStream, 16)), new Guid(StreamReaderHelper.ReadByteArray(memoryStream, 16)) }; destListEntry.UuidBirth = new Uuid(destListEntry.DroidBirth[1].ToString()); destListEntry.NetBiosName = woanware.Text.ReplaceNulls(StreamReaderHelper.ReadString(memoryStream, 16)); destListEntry.StreamNo = StreamReaderHelper.ReadInt64(memoryStream).ToString("X"); memoryStream.Seek(4, SeekOrigin.Current); destListEntry.FileTime = StreamReaderHelper.ReadDateTime(memoryStream); memoryStream.Seek(4, SeekOrigin.Current); int stringLength = StreamReaderHelper.ReadInt16(memoryStream); if (stringLength != -1) { destListEntry.Data = StreamReaderHelper.ReadStringUnicode(memoryStream, stringLength * 2); } else { memoryStream.Seek(4, SeekOrigin.Current); } destListEntry.Data = woanware.Text.ReplaceNulls(destListEntry.Data); entries.Add(destListEntry); }while (memoryStream.Position < memoryStream.Length); } } catch (Exception ex) { } return(entries); }
// TODO Find information about JPEG2000. // Notes: JFIF is big-endian. public ImportedImage ImportImage(StreamReaderHelper stream, PdfDocument document) { try { stream.CurrentOffset = 0; // Test 2 magic bytes. if (TestFileHeader(stream)) { // Skip over 2 magic bytes. stream.CurrentOffset += 2; ImagePrivateDataDct ipd = new ImagePrivateDataDct(stream.Data, stream.Length); ImportedImage ii = new ImportedImageJpeg(this, ipd, document); if (TestJfifHeader(stream, ii)) { bool colorHeader = false, infoHeader = false; while (MoveToNextHeader(stream)) { if (TestColorFormatHeader(stream, ii)) { colorHeader = true; } else if (TestInfoHeader(stream, ii)) { infoHeader = true; } } if (colorHeader && infoHeader) { return(ii); } } } } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } return(null); }
private bool TestInfoHeader(StreamReaderHelper stream, ImportedImage ii) { // The SOF header (start of frame). int header = stream.GetWord(0, true); if (header >= 0xffc0 && header <= 0xffc3 || header >= 0xffc9 && header <= 0xffcb) { // Lines in image. int sizeY = stream.GetWord(5, true); // Samples per line. int sizeX = stream.GetWord(7, true); // $THHO TODO: Check if we always get useful information here. ii.Information.Width = (uint)sizeX; ii.Information.Height = (uint)sizeY; return(true); } return(false); }
// TODO Find information about JPEG2000. // Notes: JFIF is big-endian. public ImportedImage ImportImage(StreamReaderHelper stream, PdfDocument document) { try { stream.CurrentOffset = 0; // Test 2 magic bytes. if (TestFileHeader(stream)) { // Skip over 2 magic bytes. stream.CurrentOffset += 2; ImagePrivateDataDct ipd = new ImagePrivateDataDct(stream.Data, stream.Length); ImportedImage ii = new ImportedImageJpeg(this, ipd, document); if (TestJfifHeader(stream, ii)) { bool colorHeader = false, infoHeader = false; while (MoveToNextHeader(stream)) { if (TestColorFormatHeader(stream, ii)) { colorHeader = true; } else if (TestInfoHeader(stream, ii)) { infoHeader = true; } } if (colorHeader && infoHeader) return ii; } } } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } return null; }
/// <summary> /// Deserialize XML with unqualified elements (elements not specifying their namespace) to an XML serialization object type that specifies a namespace for its XmlTypeAttribute. /// </summary> /// <remarks> /// Magic incantations adapted from here: https://stackoverflow.com/a/29776266 /// </remarks> public static T Deserialize <T>(Stream stream, string defaultXmlNamespace) { var nameTable = new NameTable(); var xmlNamespaceManager = new XmlNamespaceManager(nameTable); xmlNamespaceManager.AddNamespace(String.Empty, defaultXmlNamespace); var xmlParserContext = new XmlParserContext(nameTable, xmlNamespaceManager, null, XmlSpace.Default); var xmlReaderSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Auto, }; using (var reader = StreamReaderHelper.NewLeaveOpen(stream)) using (var xmlReader = XmlReader.Create(reader, xmlReaderSettings, xmlParserContext)) { var xmlSerializer = new XmlSerializer(typeof(T)); var output = (T)xmlSerializer.Deserialize(xmlReader); return(output); } }
private bool TestFileHeader(StreamReaderHelper stream) { // File must start with 0xffd8. return(stream.GetWord(0, true) == 0xffd8); }
private bool TestFileHeader(StreamReaderHelper stream) => // File must start with 0xffd8. stream.GetWord(0, true) == 0xffd8;
private bool TestBitmapInfoHeader(StreamReaderHelper stream, ImportedImage ii, int offset) { int size = (int)stream.GetDWord(0, false); if (size == 40 || size == 108 || size == 124) // sizeof BITMAPINFOHEADER == 40, sizeof BITMAPV4HEADER == 108, sizeof BITMAPV5HEADER == 124 { uint width = stream.GetDWord(4, false); int height = (int)stream.GetDWord(8, false); int planes = stream.GetWord(12, false); int bitcount = stream.GetWord(14, false); int compression = (int)stream.GetDWord(16, false); int sizeImage = (int)stream.GetDWord(20, false); int xPelsPerMeter = (int)stream.GetDWord(24, false); int yPelsPerMeter = (int)stream.GetDWord(28, false); uint colorsUsed = stream.GetDWord(32, false); uint colorsImportant = stream.GetDWord(36, false); // TODO Integrity and plausibility checks. if (sizeImage != 0 && sizeImage + offset > stream.Length) { return(false); } ImagePrivateDataBitmap privateData = (ImagePrivateDataBitmap)ii.Data; // Return true only for supported formats. if (compression == 0 || compression == 3) // BI_RGB == 0, BI_BITFIELDS == 3 { ((ImagePrivateDataBitmap)ii.Data).Offset = offset; ((ImagePrivateDataBitmap)ii.Data).ColorPaletteOffset = stream.CurrentOffset + size; ii.Information.Width = width; ii.Information.Height = (uint)Math.Abs(height); ii.Information.HorizontalDPM = xPelsPerMeter; ii.Information.VerticalDPM = yPelsPerMeter; privateData.FlippedImage = height < 0; if (planes == 1 && bitcount == 24) { // RGB24 ii.Information.ImageFormat = ImageInformation.ImageFormats.RGB24; // TODO: Verify Mask if size >= 108 && compression == 3. return(true); } if (planes == 1 && bitcount == 32) { // ARGB32 //ii.Information.ImageFormat = ImageInformation.ImageFormats.ARGB32; ii.Information.ImageFormat = compression == 0 ? ImageInformation.ImageFormats.RGB24 : ImageInformation.ImageFormats.ARGB32; // TODO: tell RGB from ARGB. Idea: assume RGB if alpha is always 0. // TODO: Verify Mask if size >= 108 && compression == 3. return(true); } if (planes == 1 && bitcount == 8) { // Palette8 ii.Information.ImageFormat = ImageInformation.ImageFormats.Palette8; ii.Information.ColorsUsed = colorsUsed; return(true); } if (planes == 1 && bitcount == 4) { // Palette8 ii.Information.ImageFormat = ImageInformation.ImageFormats.Palette4; ii.Information.ColorsUsed = colorsUsed; return(true); } if (planes == 1 && bitcount == 1) { // Palette8 ii.Information.ImageFormat = ImageInformation.ImageFormats.Palette1; ii.Information.ColorsUsed = colorsUsed; return(true); } // TODO Implement more formats! } } return(false); }
private bool TestBitmapInfoHeader(StreamReaderHelper stream, ImportedImage ii, int offset) { int size = (int)stream.GetDWord(0, false); if (size == 40 || size == 108 || size == 124) // sizeof BITMAPINFOHEADER == 40, sizeof BITMAPV4HEADER == 108, sizeof BITMAPV5HEADER == 124 { uint width = stream.GetDWord(4, false); int height = (int)stream.GetDWord(8, false); int planes = stream.GetWord(12, false); int bitcount = stream.GetWord(14, false); int compression = (int)stream.GetDWord(16, false); int sizeImage = (int)stream.GetDWord(20, false); int xPelsPerMeter = (int)stream.GetDWord(24, false); int yPelsPerMeter = (int)stream.GetDWord(28, false); uint colorsUsed = stream.GetDWord(32, false); uint colorsImportant = stream.GetDWord(36, false); // TODO Integrity and plausibility checks. if (sizeImage != 0 && sizeImage + offset > stream.Length) return false; ImagePrivateDataBitmap privateData = (ImagePrivateDataBitmap)ii.Data; // Return true only for supported formats. if (compression == 0 || compression == 3) // BI_RGB == 0, BI_BITFIELDS == 3 { ((ImagePrivateDataBitmap)ii.Data).Offset = offset; ((ImagePrivateDataBitmap)ii.Data).ColorPaletteOffset = stream.CurrentOffset + size; ii.Information.Width = width; ii.Information.Height = (uint)Math.Abs(height); ii.Information.HorizontalDPM = xPelsPerMeter; ii.Information.VerticalDPM = yPelsPerMeter; privateData.FlippedImage = height < 0; if (planes == 1 && bitcount == 24) { // RGB24 ii.Information.ImageFormat = ImageInformation.ImageFormats.RGB24; // TODO: Verify Mask if size >= 108 && compression == 3. return true; } if (planes == 1 && bitcount == 32) { // ARGB32 //ii.Information.ImageFormat = ImageInformation.ImageFormats.ARGB32; ii.Information.ImageFormat = compression == 0 ? ImageInformation.ImageFormats.RGB24 : ImageInformation.ImageFormats.ARGB32; // TODO: tell RGB from ARGB. Idea: assume RGB if alpha is always 0. // TODO: Verify Mask if size >= 108 && compression == 3. return true; } if (planes == 1 && bitcount == 8) { // Palette8 ii.Information.ImageFormat = ImageInformation.ImageFormats.Palette8; ii.Information.ColorsUsed = colorsUsed; return true; } if (planes == 1 && bitcount == 4) { // Palette8 ii.Information.ImageFormat = ImageInformation.ImageFormats.Palette4; ii.Information.ColorsUsed = colorsUsed; return true; } if (planes == 1 && bitcount == 1) { // Palette8 ii.Information.ImageFormat = ImageInformation.ImageFormats.Palette1; ii.Information.ColorsUsed = colorsUsed; return true; } // TODO Implement more formats! } } return false; }
/// <summary> /// Performs the parsing of the cache entry data /// </summary> public void Update(byte[] data) { using (MemoryStream memoryStream = new MemoryStream(data)) { memoryStream.Seek(0, SeekOrigin.Begin); Length = StreamReaderHelper.ReadUInt16(memoryStream); MaxLength = StreamReaderHelper.ReadUInt16(memoryStream); if (Is32Bit == true) { Offset = StreamReaderHelper.ReadUInt32(memoryStream); try { UInt32 lowDateTime = StreamReaderHelper.ReadUInt32(memoryStream); UInt32 highDateTime = StreamReaderHelper.ReadUInt32(memoryStream); long hFT2 = (((long)highDateTime) << 32) + lowDateTime; DateTime = DateTime.FromFileTimeUtc(hFT2); } catch (Exception) { DateTime = DateTime.MinValue; } FileSizeLow = StreamReaderHelper.ReadUInt32(memoryStream); FileSizeHigh = StreamReaderHelper.ReadUInt32(memoryStream); } else { memoryStream.Seek(4, SeekOrigin.Current); Offset = StreamReaderHelper.ReadUInt64(memoryStream); try { UInt32 lowDateTime = StreamReaderHelper.ReadUInt32(memoryStream); UInt32 highDateTime = StreamReaderHelper.ReadUInt32(memoryStream); long hFT2 = (((long)highDateTime) << 32) + lowDateTime; DateTime = DateTime.FromFileTimeUtc(hFT2); } catch (Exception) { DateTime = DateTime.MinValue; } FileSizeLow = StreamReaderHelper.ReadUInt32(memoryStream); FileSizeHigh = StreamReaderHelper.ReadUInt32(memoryStream); } } // It contains file data. if (_containsFileSize == false) { // Check the CSRSS flag. if ((FileSizeLow & Global.CSRSS_FLAG) == Global.CSRSS_FLAG) { ProcessExec = true; } else { ProcessExec = false; } } }
private bool TestJfifHeader(StreamReaderHelper stream, ImportedImage ii) { // The App0 header should be the first header in every JFIF file. if (stream.GetWord(0, true) == 0xffe0) { // Now check for text "JFIF". if (stream.GetDWord(4, true) == 0x4a464946) { int blockLength = stream.GetWord(2, true); if (blockLength >= 16) { int version = stream.GetWord(9, true); int units = stream.GetByte(11); int densityX = stream.GetWord(12, true); int densityY = stream.GetWord(14, true); switch (units) { case 0: // Aspect ratio only. ii.Information.HorizontalAspectRatio = densityX; ii.Information.VerticalAspectRatio = densityY; break; case 1: // DPI. ii.Information.HorizontalDPI = densityX; ii.Information.VerticalDPI = densityY; break; case 2: // DPCM. ii.Information.HorizontalDPM = densityX * 100; ii.Information.VerticalDPM = densityY * 100; break; } // More information here? More tests? return true; } } } return false; }
private bool TestFileHeader(StreamReaderHelper stream) { // File must start with 0xffd8. return stream.GetWord(0, true) == 0xffd8; }
private bool MoveToNextHeader(StreamReaderHelper stream) { int blockLength = stream.GetWord(2, true); int headerMagic = stream.GetByte(0); int headerType = stream.GetByte(1); if (headerMagic == 0xff) { // EOI: last header. if (headerType == 0xd9) return false; // Check for standalone markers. if (headerType == 0x01 || headerType >= 0xd0 && headerType <= 0xd7) { stream.CurrentOffset += 2; return true; } // Now assume header with block size. stream.CurrentOffset += 2 + blockLength; return true; } return false; }
private bool TestInfoHeader(StreamReaderHelper stream, ImportedImage ii) { // The SOF header (start of frame). int header = stream.GetWord(0, true); if (header >= 0xffc0 && header <= 0xffc3 || header >= 0xffc9 && header <= 0xffcb) { // Lines in image. int sizeY = stream.GetWord(5, true); // Samples per line. int sizeX = stream.GetWord(7, true); // $THHO TODO: Check if we always get useful information here. ii.Information.Width = (uint)sizeX; ii.Information.Height = (uint)sizeY; return true; } return false; }
private bool TestColorFormatHeader(StreamReaderHelper stream, ImportedImage ii) { // The SOS header (start of scan). if (stream.GetWord(0, true) == 0xffda) { int components = stream.GetByte(4); if (components < 1 || components > 4 || components == 2) return false; // 1 for grayscale, 3 for RGB, 4 for CMYK. int blockLength = stream.GetWord(2, true); // Integrity check: correct size? if (blockLength != 6 + 2 * components) return false; // Eventually do more tests here. // Magic: we assume that all JPEG files with 4 components are RGBW (inverted CMYK) and not CMYK. // We add a test to tell CMYK from RGBW when we encounter a test file in CMYK format. ii.Information.ImageFormat = components == 3 ? ImageInformation.ImageFormats.JPEG : (components == 1 ? ImageInformation.ImageFormats.JPEGGRAY : ImageInformation.ImageFormats.JPEGRGBW); return true; } return false; }
/// <summary> /// Performs the parsing of the cache entry data /// </summary> public void Update(byte[] data) { using (MemoryStream memoryStream = new MemoryStream(data)) { memoryStream.Seek(0, SeekOrigin.Begin); if (Is32Bit == true) { Length = StreamReaderHelper.ReadUInt16(memoryStream); MaxLength = StreamReaderHelper.ReadUInt16(memoryStream); Offset = StreamReaderHelper.ReadUInt32(memoryStream); try { UInt32 lowDateTime = StreamReaderHelper.ReadUInt32(memoryStream); UInt32 highDateTime = StreamReaderHelper.ReadUInt32(memoryStream); long hFT2 = (((long)highDateTime) << 32) + lowDateTime; DateTime = DateTime.FromFileTimeUtc(hFT2); } catch (Exception) { DateTime = DateTime.MinValue; } FileFlags = StreamReaderHelper.ReadUInt32(memoryStream); Flags = StreamReaderHelper.ReadUInt32(memoryStream); BlobSize = StreamReaderHelper.ReadUInt32(memoryStream); BlobOffset = StreamReaderHelper.ReadUInt32(memoryStream); } else { Length = StreamReaderHelper.ReadUInt16(memoryStream); MaxLength = StreamReaderHelper.ReadUInt16(memoryStream); memoryStream.Seek(4, SeekOrigin.Current); Offset = StreamReaderHelper.ReadUInt64(memoryStream); try { UInt32 lowDateTime = StreamReaderHelper.ReadUInt32(memoryStream); UInt32 highDateTime = StreamReaderHelper.ReadUInt32(memoryStream); long hFT2 = (((long)highDateTime) << 32) + lowDateTime; DateTime = DateTime.FromFileTimeUtc(hFT2); } catch (Exception) { DateTime = DateTime.MinValue; } FileFlags = StreamReaderHelper.ReadUInt32(memoryStream); Flags = StreamReaderHelper.ReadUInt32(memoryStream); BlobSize = StreamReaderHelper.ReadUInt64(memoryStream); BlobOffset = StreamReaderHelper.ReadUInt64(memoryStream); } } // Test to see if the file may have been executed. if ((FileFlags & Global.CSRSS_FLAG) == Global.CSRSS_FLAG) { ProcessExec = true; } else { ProcessExec = false; } }