Example #1
0
        /// <summary>
        /// Deserializes the given string into a ConsoleBitmap
        /// </summary>
        /// <param name="s">the serialized string</param>
        /// <returns>the deserialized image</returns>
        public static ConsoleBitmap Deserialize(string s)
        {
            if (string.IsNullOrWhiteSpace(s))
            {
                throw new ArgumentNullException("s cannot be null or whitespace");
            }
            var lines = s.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n').Where(l => string.IsNullOrEmpty(l) == false).ToArray();
            var width = lines[0].LastIndexOf("#") - 1; // minus 1 for the hashes that surround the image

            if (width < 0)
            {
                throw new FormatException("Tab hash not found at line 1");
            }
            int height = FindHeight(lines);

            var valueLines              = lines.Skip(1).Take(height).ToArray();
            var pallateLines            = lines.Skip(height + 2).ToArray();
            var pallate                 = ColorPallate.Deserialize(pallateLines);
            var defaultPallateColorCode = pallate.EnumeratePallate()[0].Key;

            var ret = new ConsoleBitmap(width, height);

            for (var lineIndex = 0; lineIndex < valueLines.Length; lineIndex++)
            {
                var line   = valueLines[lineIndex].Substring(1);                                                         // substring removes the leading hash
                var values = line.Substring(0, width);
                var colors = line.Substring(width + 1).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // width + 1 to remove trailing hash

                for (var x = 0; x < width; x++)
                {
                    var character = line[x];
                    // Conditional statement below allows text that doesn't have the color informatio to be serialized.
                    // This is really useful since you want to be able to sketch your image in a normal text editor without having to
                    // format the colors by hand. By leaving the color information out of your sketch (still surrounded with hashes) you
                    // can import that image and then serialize it out. On the way out the serializer will add default colors for you.
                    // You can then happily edit from there.
                    var colorCode = colors.Length == width?int.Parse(colors[x]) : defaultPallateColorCode;

                    var lookedUp = pallate.Lookup(colorCode);
                    ret.Pixels[x][lineIndex] = new ConsoleCharacter(character, lookedUp.ForegroundColor, lookedUp.BackgroundColor);
                }
            }
            return(ret);
        }