public Result findCreate() { var user = HttpContext.Session.Get("User"); User creator = null; if (user == null || user.Length == 0) { return(Result.failResult("登录过期", null)); } else { try { User res = (User)ByteConvert.BytesToObject(user); creator = res; } catch (Exception e) { return(Result.failResult("Error", null)); } } var resm = _service.findCreateParty(creator.uid); return(Result.successResult("OK", resm)); }
public void OnLoad(string tag, LoadPath loadPath, DataSet data, Callback <Sprite> callback) { CDebug.Log("load texture success " + loadPath.path); Texture2D texture2d = null; if (TextureCache.Instance.Contains(loadPath.path)) { texture2d = TextureCache.Instance.Get(loadPath.path).texture2d; } else { texture2d = ByteConvert.BytesToTexture2D(data.bytes); } texture2d.wrapMode = TextureWrapMode.Clamp; Sprite sprite = ByteConvert.CreateImage(texture2d); TextureCache.Instance.AddCache(loadPath.path, texture2d); SpriteCache.Instance.AddCache(loadPath.path, sprite); Callback unload = () => { TextureCache.Instance.UnloadCache(loadPath.path); SpriteCache.Instance.UnloadCache(loadPath.path); }; AddToUnloadTask(tag, unload); if (callback != null) { callback(sprite); callback = null; } }
private void LoadFromBinary(StreamReader streamReader) { BinaryReader binaryReader = new BinaryReader(streamReader.BaseStream); while (streamReader.BaseStream.Position < streamReader.BaseStream.Length) { try { int length = binaryReader.ReadInt32(); byte[] buffer = new byte[length]; binaryReader.Read(buffer, 0, length); string stringUid = ByteConvert.ToString(buffer, CharacterRepertoire.Ascii); Uid uid = new Uid(stringUid); length = binaryReader.ReadInt32(); buffer = new byte[length]; binaryReader.Read(buffer, 0, length); string name = ByteConvert.ToString(buffer, CharacterRepertoire.Ascii); int intType = binaryReader.ReadInt32(); UidType type = (UidType)UidType.ToObject(typeof(UidType), intType); bool retired = binaryReader.ReadBoolean(); UidDictionaryEntry entry = new UidDictionaryEntry(uid, name, type, retired); Add(entry); } catch (Exception e) { throw new DicomException("Wrong entry before index " + streamReader.BaseStream.Position + ": " + e.Message); } } }
public void OnLoad(string tag, LoadPath loadPath, DataSet data, Callback <string> callback) { CDebug.Log("load texture success " + loadPath.path); string str = ""; if (StringCache.Instance.Contains(loadPath.path)) { str = StringCache.Instance.Get(loadPath.path); } else { str = ByteConvert.BytesToString(data.bytes); StringCache.Instance.Add(loadPath.path, str); } Callback unload = () => { str = ""; }; AddToUnloadTask(tag, unload); if (callback != null) { callback(str); callback = null; } }
/// <summary> /// 加载并解析表 /// </summary> public void Parse(bool useLocal = false) { string url; if (useLocal || !AppSetting.isRemote) { url = System.IO.Path.Combine(AppSetting.SourceDataPath, "setting/" + fileName); CDebug.Log("load tsv fileName " + url); //string content = LoadSettingNoLock(url); string content = ByteConvert.BytesToString(LoadSetting(url)); //CDebug.Log(content); ParseString(content); } else { //CDebug.Log("--------------- setting/" + "setting/" + fileName); if (TaskManager.instance.localResPaths.ContainsKey("setting/" + fileName)) { var localPath = TaskManager.instance.localResPaths["setting/" + fileName]; TaskManager.instance.AddTask(localPath, "", (data) => { string content = ByteConvert.BytesToString(data.bytes); ParseString(content); }); } } }
/// <summary> /// Creates a new VR instance from a DICOM output stream. /// </summary> /// <param name="stream"> /// Any kind of DICOM output stream. /// </param> /// <returns> /// Output stream position of this instance. /// </returns> public static ValueRepresentation LoadFrom(Stream stream, Tag tag) { DicomContext.Set(stream, tag); if (IsImplicitBy(tag)) { if (tag.IsUserDefined) { // implicit but unknown value representation return(GetBy("UN", tag)); } else { // implicit but known value representation; // return new instance, dictionary entry do not have a // transfer syntax return(GetBy(tag.GetDictionaryEntry().VR.Name, tag)); } } else { // explicit value representation byte[] buffer = new byte[2]; stream.Read(buffer, 0, 2); string name = ByteConvert.ToString(buffer, CharacterRepertoire.Default); return(GetBy(name, tag)); } DicomContext.Reset(); }
/// <summary> /// Re-creates this instance from a DICOM output stream. /// </summary> public void LoadFrom(Stream stream) { streamPosition = stream.Position; DicomContext.Set(stream, tag); if (IsImplicit) { if (Tag.IsUserDefined) { // implicit but unknown value representation vrName = "UN"; } else { // implicit but known value representation; // return new instance, dictionary entry do not have a // transfer syntax vrName = Tag.GetDictionaryEntry().VR.Name; } } else { // explicit value representation byte[] buffer = new byte[2]; stream.Read(buffer, 0, 2); vrName = ByteConvert.ToString(buffer, CharacterRepertoire.Default); } DicomContext.Reset(); }
public static string ReadStringEx(int tSize = 32) { string readString = ByteConvert.MsgBytesToStringEx(rbytes, curReadIndex, tSize); curReadIndex += tSize; return(readString); }
/// <summary> /// The command method to encrypt the given data /// </summary> private void Encrypt() { byte[] encrypted; byte[] plainBytes; //Encryption sequence differs according to the selected data format switch (DataInput.DataFormatSelected) { //Encrypt file case Format.File: //Get plain file bytes plainBytes = DataInput.GetBytesFromFile(); //Encrypt encrypted = KeyPairSetup.Encrypt(plainBytes); //Verify that the encryption is successfull if (encrypted != null) { //Create encrypted file path EncryptedFilePath = DataInput.GetEncryptedFilePath(); //Write the encrypted bytes to the new file path File.WriteAllBytes(EncryptedFilePath, encrypted); } break; //Encrypt text case Format.Text: //Encrypt encrypted = KeyPairSetup.Encrypt(DataInput.Data); //Verify that the encryption is successfull if (encrypted != null) { //Comvert the encrypted bytes to hex string EncryptedText = ByteConvert.BytesToHexString(encrypted); } break; //Encrypt hex string case Format.Hex: //Convert hex string to plain bytes plainBytes = ByteConvert.HexStringToBytes(DataInput.Data); //Encrypt encrypted = KeyPairSetup.Encrypt(plainBytes); //Verify that the encryption is successfull if (encrypted != null) { //Convert encrypted bytes to hex string EncryptedText = ByteConvert.BytesToHexString(encrypted); } break; } }
/// <summary> /// The command method to encrypt the given data /// </summary> private void Encrypt() { //Convert the string key and iv to bytes var secretKey = ByteConvert.HexStringToBytes(SecretKey); var iv = ByteConvert.HexStringToBytes(IV); //fields for saving the plain and encrypted byte arrays byte[] encrypted; byte[] plainBytes; //Get the data and encrypt it acording to the selected format switch (DataInput.DataFormatSelected) { //Encrypt a text string case Format.Text: //Encrypt with the selected cipher and return the encrypted byte array encrypted = SelectedCipherApi.EncryptText(SelectedAlgorithim, SelectedKeySize, secretKey, iv, DataInput.Data); //Converts the byte array to a hex string EncryptedText = ByteConvert.BytesToHexString(encrypted); break; //Encrypt a hex string case Format.Hex: //Convert the plain hex string to byte array plainBytes = ByteConvert.HexStringToBytes(DataInput.Data); //Encrypt with the selected cipher and return the encrypted byte array encrypted = SelectedCipherApi.EncryptBytes(SelectedAlgorithim, SelectedKeySize, secretKey, iv, plainBytes); //Converts the byte array to a hex string EncryptedText = ByteConvert.BytesToHexString(encrypted); break; //Encrypt a file case Format.File: //Gets the file as a byte array plainBytes = File.ReadAllBytes(DataInput.Data); //Encrypt with the selected cipher and return the encrypted byte array encrypted = SelectedCipherApi.EncryptBytes(SelectedAlgorithim, SelectedKeySize, secretKey, iv, plainBytes); //Gets the file extension of the plain original file var extension = Path.GetExtension(DataInput.Data); //Adds the "Encrypted" text to the encrypted file name EncryptedFilePath = Path.Combine(Directory.GetParent(DataInput.Data).ToString(), Path.GetFileNameWithoutExtension(DataInput.Data) + ".Encrypted" + extension); //Writes all the bytes to the encrypted file File.WriteAllBytes(EncryptedFilePath, encrypted); break; } }
/// <summary> /// 发送字节流 /// </summary> /// <param name="remoteEndPoint">udp远程地址,如果为null表示tcp发送</param> /// <param name="buffer">字节流</param> /// <returns>发送结果</returns> private SocketResult SendCore(IPEndPoint remoteEndPoint, List <byte> buffer) { if (Socket == null) { return(SocketResult.Disconnection); } if (buffer == null || buffer.Count == 0) { return(SocketResult.SendFailed); } byte[] temp = buffer.ToArray(); TransmitSize += Convert.ToUInt32(temp.Length); try { if (remoteEndPoint == null || remoteEndPoint.Address.Equals(IPAddress.Any) && remoteEndPoint.Port == 0) { Log($"{Socket.Handle} - {temp.Length} {ByteConvert.ToHex(temp)}"); int written = 0; while (written != temp.Length) { int n; if ((n = Socket.Send(temp, written, temp.Length - written, SocketFlags.None)) <= 0) { return(SocketResult.SendFailed); } written += n; } } else { Log($"{Socket.Handle} {remoteEndPoint} - {temp.Length} {ByteConvert.ToHex(temp)}"); int written = 0; while (written != temp.Length) { int n; if ((n = Socket.SendTo(temp, written, temp.Length - written, SocketFlags.None, remoteEndPoint)) <= 0) { return(SocketResult.SendFailed); } written += n; } } return(SocketResult.Success); } catch (SocketException) { return(SocketResult.SendFailed); } catch (ObjectDisposedException) { return(SocketResult.SendFailed); } }
/// <summary> /// Default constructor /// </summary> public KeyPairSetupDesignModel() { SelectedOperation = AsymmetricOperation.Encryption; Algorithims = BaseMsdnAsymmetric.GetAlgorthims(SelectedOperation); //Algorithims = IAsymmetricCipher.GetBouncyAlgorthims(SelectedOperation); SelectedAlgorithimIndex = 0; BaseMsdnAsymmetric.GetCipher(Algorithims[SelectedAlgorithimIndex]); PrivateKey = ByteConvert.HexStringToBytes("FFFFFFFFF111000"); PublicKey = ByteConvert.HexStringToBytes("00000000FFFFFFF"); }
/// <summary> /// The command method to decrypt the given data /// </summary> private void Decrypt() { byte[] encrypted; byte[] decrypted; //Decryption sequence differs according to the selected data format switch (DataInput.DataFormatSelected) { //Decrypt file case Format.File: //Get the encrypted file bytes encrypted = ByteConvert.FileToBytes(EncryptedFilePath); //Decrypt decrypted = KeyPairSetup.Decrypt(encrypted); //true if decrypted not null if (decrypted != null) { //Create an encrypted file path DecryptedFilePath = DataInput.GetDecryptedFilePath(EncryptedFilePath); //Write decrypted bytes to file File.WriteAllBytes(DecryptedFilePath, decrypted); } break; //Decrypt a text case Format.Text: //Convert the encrypted hex string to bytes encrypted = ByteConvert.HexStringToBytes(EncryptedText); //Decrypt as text DecryptedText = KeyPairSetup.DecryptToText(encrypted); break; //Decrypt a hex value case Format.Hex: //Convert the encrypted hex string to bytes encrypted = ByteConvert.HexStringToBytes(EncryptedText); //Decrypt decrypted = KeyPairSetup.Decrypt(encrypted); //true if decrypted not null if (decrypted != null) { //Convert decrypted bytes to hex string DecryptedText = ByteConvert.BytesToHexString(decrypted); } break; } }
public static void WriteString(string wString) { if (writeStringAmount == 0) { writeStringIndex = curWriteIndex; curWriteIndex += sizeof(byte); } writeStringAmount += 1; wbytes[writeStringIndex] = (byte)writeStringAmount; byte[] strBuffs = ByteConvert.StringToMsgBytes(wString); strBuffs.CopyTo(wbytes, curWriteIndex); curWriteIndex += strBuffs.Length; }
/// <summary> /// The command methods to generate a random key /// </summary> private void GenerateKey() { //Gets a list of byte arrays containing the secret key and if available the iv var keyAndIv = SelectedCipherApi.GenerateKey(SelectedAlgorithim, SelectedKeySize); //Convert the byte array to a string SecretKey = ByteConvert.BytesToHexString(keyAndIv[0]); //true if an iv byte array exists if (keyAndIv.Count > 1) { //Convert the byte array to a string IV = ByteConvert.BytesToHexString(keyAndIv[1]); } }
public static string ReadString() { if (readStringAmount == 0) { readStringAmount = rbytes[curReadIndex++]; } if (curReadIndex >= rbytes.Length) { return(""); } string readString = ByteConvert.MsgBytesToString(rbytes, curReadIndex); curReadIndex += readString.Length + sizeof(byte); return(readString); }
/* Attempt to send data */ private void SendData() { if (serialPort == null || !serialPort.IsOpen) { PutLog("请先连接串口后再发送数据!"); return; } try { byte[] buffer; if (SendDataType == 0) { buffer = Encoding.GetEncoding(setting.sendDataEncoding).GetBytes(SendDataText); PutSendDataLog(SendDataType, SendDataText); } else if (SendDataType == 1) { buffer = ByteConvert.HexStringToBytes(SendDataText); PutSendDataLog(SendDataType, ByteConvert.BytesToHexString(buffer)); } else { buffer = ByteConvert.BinStringToBytes(SendDataText); PutSendDataLog(SendDataType, ByteConvert.BytesToBinString(buffer)); } if (buffer.Length == 0) { PutLog("发送数据为空!"); return; } serialPort.Write(buffer, 0, buffer.Length); numberBytesSendInt += buffer.Length; NumberBytesSend = numberBytesSendInt.ToString(); } catch (Exception e) { PutLog(e.ToString()); } }
/// <summary> /// The command method to verify a signature /// </summary> private void Verify() { var pubKey = File.ReadAllBytes(KeyPairSetup.PublicKeyFilePath); var signature = ByteConvert.HexStringToBytes(OriginalSignature); byte[] data = null; switch (DataInput.DataFormatSelected) { case Format.File: data = File.ReadAllBytes(DataInput.Data); break; case Format.Text: data = ByteConvert.StringToUTF8Bytes(DataInput.Data); break; } SignatureVerified = KeyPairSetup.Verify(signature, pubKey, data); }
public string GetPowerUpTimeDescription() { // this is generally a byte[] of length 8 directly representing a date and time. // the format is : first 2 bytes together are the year, and then each byte after // is month, day, hour, minute, second with the eighth byte unused // e.g., 2011:04:25 01:54:58 var o = Directory.GetByteArray(NikonType2MakernoteDirectory.TagPowerUpTime); if (o == null) { return(null); } ushort year = ByteConvert.FromBigEndianToNative(BitConverter.ToUInt16(o, 0)); return(string.Format($"{year}:{o[2]:D2}:{o[3]:D2} {o[4]:D2}:{o[5]:D2}:{o[6]:D2}")); }
/// <summary> /// The command method to sign some data /// </summary> private void Sign() { var privKey = File.ReadAllBytes(KeyPairSetup.PrivateKeyFilePath); byte[] data = null; switch (DataInput.DataFormatSelected) { case Format.File: data = File.ReadAllBytes(DataInput.Data); break; case Format.Text: data = ByteConvert.StringToUTF8Bytes(DataInput.Data); break; } var signature = KeyPairSetup.Sign(privKey, data); OriginalSignature = ByteConvert.BytesToHexString(signature); }
public Result showUser() { var user = HttpContext.Session.Get("User"); if (user == null || user.Length == 0) { return(Result.failResult("登录过期", null)); } else { try { User res = (User)ByteConvert.BytesToObject(user); return(Result.successResult("OK", res.username)); }catch (Exception e) { return(Result.failResult("Error", null)); } } }
private void LoadFromBinary(StreamReader streamReader) { BinaryReader binaryReader = new BinaryReader(streamReader.BaseStream); while (streamReader.BaseStream.Position < streamReader.BaseStream.Length) { try { int group = binaryReader.ReadInt32(); int element = binaryReader.ReadInt32(); Tag tag = new Tag(group, element); int length = binaryReader.ReadInt32(); byte[] buffer = new byte[length]; binaryReader.Read(buffer, 0, length); string description = ByteConvert.ToString(buffer, CharacterRepertoire.Ascii); buffer = new byte[2]; binaryReader.Read(buffer, 0, 2); string vr = ByteConvert.ToString(buffer, CharacterRepertoire.Ascii); vr = vr.Trim(); length = binaryReader.ReadInt32(); buffer = new byte[length]; binaryReader.Read(buffer, 0, length); string vm = ByteConvert.ToString(buffer, CharacterRepertoire.Ascii); bool retiredBool = binaryReader.ReadBoolean(); string retired = retiredBool ? "RET" : null; DataElementDictionaryEntry entry = new DataElementDictionaryEntry(tag.ToString(), description, vr, vm, retired); Add(entry); } catch (Exception e) { throw new DicomException("Wrong entry before index " + streamReader.BaseStream.Position + ": " + e.Message); } } }
public Result Post([FromBody] UserReq req) { if (!req.validate()) { return(Result.failResult("格式有误", null)); } var res = _userService.CheckUser(req.username, req.password); if (res != null && res.username == req.username) { var ret = Result.successResult("登陆成功", res); HttpContext.Session.Set("User", ByteConvert.ObjectToBytes(res)); Console.WriteLine(ret.message); return(ret); } else { var ret = Result.failResult("未有匹配的账号密码", null); Console.WriteLine(ret.message); return(ret); } }
public Result closeParty(int id) { var user = HttpContext.Session.Get("User"); User creator = null; if (user == null || user.Length == 0) { return(Result.failResult("登录过期", null)); } else { try { User res = (User)ByteConvert.BytesToObject(user); creator = res; } catch (Exception e) { return(Result.failResult("Error", null)); } } var auth = _service.checkMem(creator.uid, id); if (auth != 2) { return(Result.failResult("没有权限", null)); } var resm = _service.setPartyStatus(id, 1); if (resm) { return(Result.successResult("OK", null)); } else { return(Result.failResult("队伍处于关闭状态", null)); } }
/// <summary> /// transforms the data to bytes according to the selected format option /// </summary> /// <param name="format">The format option to use for byte extraction</param> /// <param name="data">The data to extract the bytes from</param> /// <returns>the extracted bytes</returns> private byte[] GetBytesAccordingToFormatSelected(Format format, string data) { byte[] bytes = null; switch (format) { case Format.File: bytes = ByteConvert.FileToBytes(data); break; case Format.Text: bytes = ByteConvert.StringToAsciiBytes(data); break; case Format.Hex: bytes = ByteConvert.HexStringToBytes(data); break; default: Debugger.Break(); break; } return(bytes); }
public Result publish([FromBody] PublishReq req) { var user = HttpContext.Session.Get("User"); if (!req.validate()) { return(Result.failResult("格式有误", null)); } User creator = null; if (user == null || user.Length == 0) { return(Result.failResult("登录过期", null)); } else { try { User res = (User)ByteConvert.BytesToObject(user); creator = res; } catch (Exception e) { return(Result.failResult("Error", null)); } } int id = _service.createParty(creator.uid, req); if (id == -1) { return(Result.failResult("Error", null)); } else { return(Result.successResult("队伍发布成功", id)); } }
/// <summary> /// Returns the entire DICOM pixel data as array of byte arrays. /// </summary> /// <remarks> /// All non-byte arrays are transcoded into byte arrays. If a DICOM /// pixel data element is not a DICOM sequence of items, an array /// with a single byte array entry will be returned. /// </remarks> public byte[][] ToBytesArray() { byte[][] bytesArray; if (Data.Value.IsSequence) { Sequence sq = (Sequence)Data.Value[0]; bytesArray = new byte[sq.Count][]; for (int i = 0; i < sq.Count; i++) { if (sq[i].Value[0] is ushort[]) { bytesArray[i] = ByteConvert.ToBytes( (ushort[])sq[i].Value[0]); } else { bytesArray[i] = (byte[])sq[i].Value[0]; } } } else { bytesArray = new byte[1][]; if (Data.Value[0] is ushort[]) { bytesArray[0] = ByteConvert.ToBytes( (ushort[])Data.Value[0]); } else { bytesArray[0] = (byte[])Data.Value[0]; } } return(bytesArray); }
private void AddValueToXml(XmlTextWriter xml, object value, bool isDate) { if (value is ushort[]) { byte[] bytes = ByteConvert.ToBytes((ushort[])value); xml.WriteAttributeString("encoding", "Base64"); AddBase64ValueToXml(xml, bytes); } else if (value is byte[]) { xml.WriteAttributeString("encoding", "Base64"); AddBase64ValueToXml(xml, (byte[])value); } else if (isDate) { // hide zero valued time xml.WriteString(((DateTime)value).ToShortDateString()); } else { xml.WriteString(value.ToString()); } }
public Result removeMem([FromBody] RemoveReq req) { var user = HttpContext.Session.Get("User"); User creator = null; if (user == null || user.Length == 0) { return(Result.failResult("登录过期", null)); } else { try { User res = (User)ByteConvert.BytesToObject(user); creator = res; } catch (Exception e) { return(Result.failResult("Error", null)); } } var auth = _service.checkMem(creator.uid, req.pid); if (auth != 2) { return(Result.failResult("没有权限", null)); } if (_service.removeMem(req.username, req.pid)) { return(Result.successResult("OK", null)); } else { return(Result.failResult("目标不在队伍中", null)); } }
/// <exception cref="PngProcessingException"/> /// <exception cref="System.IO.IOException"/> private static IEnumerable <Directory> ProcessChunk([NotNull] PngChunk chunk) { var chunkType = chunk.ChunkType; var bytes = chunk.Bytes; if (chunkType == PngChunkType.IHDR) { var header = new PngHeader(bytes); var directory = new PngDirectory(PngChunkType.IHDR); directory.Set(PngDirectory.TagImageWidth, header.ImageWidth); directory.Set(PngDirectory.TagImageHeight, header.ImageHeight); directory.Set(PngDirectory.TagBitsPerSample, header.BitsPerSample); directory.Set(PngDirectory.TagColorType, header.ColorType.NumericValue); directory.Set(PngDirectory.TagCompressionType, header.CompressionType); directory.Set(PngDirectory.TagFilterMethod, header.FilterMethod); directory.Set(PngDirectory.TagInterlaceMethod, header.InterlaceMethod); yield return(directory); } else if (chunkType == PngChunkType.PLTE) { var directory = new PngDirectory(PngChunkType.PLTE); directory.Set(PngDirectory.TagPaletteSize, bytes.Length / 3); yield return(directory); } else if (chunkType == PngChunkType.tRNS) { var directory = new PngDirectory(PngChunkType.tRNS); directory.Set(PngDirectory.TagPaletteHasTransparency, 1); yield return(directory); } else if (chunkType == PngChunkType.sRGB) { int srgbRenderingIntent = unchecked ((sbyte)bytes[0]); var directory = new PngDirectory(PngChunkType.sRGB); directory.Set(PngDirectory.TagSrgbRenderingIntent, srgbRenderingIntent); yield return(directory); } else if (chunkType == PngChunkType.cHRM) { var chromaticities = new PngChromaticities(bytes); var directory = new PngChromaticitiesDirectory(); directory.Set(PngChromaticitiesDirectory.TagWhitePointX, chromaticities.WhitePointX); directory.Set(PngChromaticitiesDirectory.TagWhitePointY, chromaticities.WhitePointY); directory.Set(PngChromaticitiesDirectory.TagRedX, chromaticities.RedX); directory.Set(PngChromaticitiesDirectory.TagRedY, chromaticities.RedY); directory.Set(PngChromaticitiesDirectory.TagGreenX, chromaticities.GreenX); directory.Set(PngChromaticitiesDirectory.TagGreenY, chromaticities.GreenY); directory.Set(PngChromaticitiesDirectory.TagBlueX, chromaticities.BlueX); directory.Set(PngChromaticitiesDirectory.TagBlueY, chromaticities.BlueY); yield return(directory); } else if (chunkType == PngChunkType.gAMA) { var gammaInt = ByteConvert.ToInt32BigEndian(bytes); var directory = new PngDirectory(PngChunkType.gAMA); directory.Set(PngDirectory.TagGamma, gammaInt / 100000.0); yield return(directory); } else if (chunkType == PngChunkType.iCCP) { var reader = new SequentialByteArrayReader(bytes); var profileName = reader.GetNullTerminatedStringValue(maxLengthBytes: 79); var directory = new PngDirectory(PngChunkType.iCCP); directory.Set(PngDirectory.TagIccProfileName, profileName); var compressionMethod = reader.GetSByte(); if (compressionMethod == 0) { // Only compression method allowed by the spec is zero: deflate // This assumes 1-byte-per-char, which it is by spec. var bytesLeft = bytes.Length - profileName.Bytes.Length - 2; // http://george.chiramattel.com/blog/2007/09/deflatestream-block-length-does-not-match.html // First two bytes are part of the zlib specification (RFC 1950), not the deflate specification (RFC 1951). reader.GetByte(); reader.GetByte(); bytesLeft -= 2; var compressedProfile = reader.GetBytes(bytesLeft); IccDirectory iccDirectory = null; Exception ex = null; try { using (var inflaterStream = new DeflateStream(new MemoryStream(compressedProfile), CompressionMode.Decompress)) { iccDirectory = new IccReader().Extract(new IndexedCapturingReader(inflaterStream)); iccDirectory.Parent = directory; } } catch (Exception e) { ex = e; } if (ex == null) { yield return(iccDirectory); } else { directory.AddError($"Exception decompressing {nameof(PngChunkType.iCCP)} chunk: {ex.Message}"); } } else { directory.AddError("Invalid compression method value"); } yield return(directory); } else if (chunkType == PngChunkType.bKGD) { var directory = new PngDirectory(PngChunkType.bKGD); directory.Set(PngDirectory.TagBackgroundColor, bytes); yield return(directory); } else if (chunkType == PngChunkType.tEXt) { var reader = new SequentialByteArrayReader(bytes); var keyword = reader.GetNullTerminatedStringValue(maxLengthBytes: 79).ToString(_latin1Encoding); var bytesLeft = bytes.Length - keyword.Length - 1; var value = reader.GetNullTerminatedStringValue(bytesLeft, _latin1Encoding); var textPairs = new List <KeyValuePair> { new KeyValuePair(keyword, value) }; var directory = new PngDirectory(PngChunkType.tEXt); directory.Set(PngDirectory.TagTextualData, textPairs); yield return(directory); } else if (chunkType == PngChunkType.zTXt) { var reader = new SequentialByteArrayReader(bytes); var keyword = reader.GetNullTerminatedStringValue(maxLengthBytes: 79).ToString(_latin1Encoding); var compressionMethod = reader.GetSByte(); var bytesLeft = bytes.Length - keyword.Length - 1 - 1 - 1 - 1; byte[] textBytes = null; if (compressionMethod == 0) { using (var inflaterStream = new DeflateStream(new MemoryStream(bytes, bytes.Length - bytesLeft, bytesLeft), CompressionMode.Decompress)) { Exception ex = null; try { textBytes = ReadStreamToBytes(inflaterStream); } catch (Exception e) { ex = e; } // Work-around no yield-return from catch blocks if (ex != null) { var directory = new PngDirectory(PngChunkType.zTXt); directory.AddError($"Exception decompressing {nameof(PngChunkType.zTXt)} chunk with keyword \"{keyword}\": {ex.Message}"); yield return(directory); } } } else { var directory = new PngDirectory(PngChunkType.zTXt); directory.AddError("Invalid compression method value"); yield return(directory); } if (textBytes != null) { if (keyword == "XML:com.adobe.xmp") { // NOTE in testing images, the XMP has parsed successfully, but we are not extracting tags from it as necessary yield return(new XmpReader().Extract(textBytes)); } else { var textPairs = new List <KeyValuePair> { new KeyValuePair(keyword, new StringValue(textBytes, _latin1Encoding)) }; var directory = new PngDirectory(PngChunkType.zTXt); directory.Set(PngDirectory.TagTextualData, textPairs); yield return(directory); } } } else if (chunkType == PngChunkType.iTXt) { var reader = new SequentialByteArrayReader(bytes); var keyword = reader.GetNullTerminatedStringValue(maxLengthBytes: 79).ToString(_latin1Encoding); var compressionFlag = reader.GetSByte(); var compressionMethod = reader.GetSByte(); // TODO we currently ignore languageTagBytes and translatedKeywordBytes var languageTagBytes = reader.GetNullTerminatedBytes(bytes.Length); var translatedKeywordBytes = reader.GetNullTerminatedBytes(bytes.Length); var bytesLeft = bytes.Length - keyword.Length - 1 - 1 - 1 - languageTagBytes.Length - 1 - translatedKeywordBytes.Length - 1; byte[] textBytes = null; if (compressionFlag == 0) { textBytes = reader.GetNullTerminatedBytes(bytesLeft); } else if (compressionFlag == 1) { if (compressionMethod == 0) { using (var inflaterStream = new DeflateStream(new MemoryStream(bytes, bytes.Length - bytesLeft, bytesLeft), CompressionMode.Decompress)) { Exception ex = null; try { textBytes = ReadStreamToBytes(inflaterStream); } catch (Exception e) { ex = e; } // Work-around no yield-return from catch blocks if (ex != null) { var directory = new PngDirectory(PngChunkType.iTXt); directory.AddError($"Exception decompressing {nameof(PngChunkType.iTXt)} chunk with keyword \"{keyword}\": {ex.Message}"); yield return(directory); } } } else { var directory = new PngDirectory(PngChunkType.iTXt); directory.AddError("Invalid compression method value"); yield return(directory); } } else { var directory = new PngDirectory(PngChunkType.iTXt); directory.AddError("Invalid compression flag value"); yield return(directory); } if (textBytes != null) { if (keyword == "XML:com.adobe.xmp") { // NOTE in testing images, the XMP has parsed successfully, but we are not extracting tags from it as necessary yield return(new XmpReader().Extract(textBytes)); } else { var textPairs = new List <KeyValuePair> { new KeyValuePair(keyword, new StringValue(textBytes, _latin1Encoding)) }; var directory = new PngDirectory(PngChunkType.iTXt); directory.Set(PngDirectory.TagTextualData, textPairs); yield return(directory); } } } else if (chunkType == PngChunkType.tIME) { var reader = new SequentialByteArrayReader(bytes); var year = reader.GetUInt16(); var month = reader.GetByte(); int day = reader.GetByte(); int hour = reader.GetByte(); int minute = reader.GetByte(); int second = reader.GetByte(); var directory = new PngDirectory(PngChunkType.tIME); if (DateUtil.IsValidDate(year, month, day) && DateUtil.IsValidTime(hour, minute, second)) { var time = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Unspecified); directory.Set(PngDirectory.TagLastModificationTime, time); } else { directory.AddError($"PNG tIME data describes an invalid date/time: year={year} month={month} day={day} hour={hour} minute={minute} second={second}"); } yield return(directory); } else if (chunkType == PngChunkType.pHYs) { var reader = new SequentialByteArrayReader(bytes); var pixelsPerUnitX = reader.GetInt32(); var pixelsPerUnitY = reader.GetInt32(); var unitSpecifier = reader.GetSByte(); var directory = new PngDirectory(PngChunkType.pHYs); directory.Set(PngDirectory.TagPixelsPerUnitX, pixelsPerUnitX); directory.Set(PngDirectory.TagPixelsPerUnitY, pixelsPerUnitY); directory.Set(PngDirectory.TagUnitSpecifier, unitSpecifier); yield return(directory); } else if (chunkType.Equals(PngChunkType.sBIT)) { var directory = new PngDirectory(PngChunkType.sBIT); directory.Set(PngDirectory.TagSignificantBits, bytes); yield return(directory); } }