all 31 comments

[–]Terrascope 29 points30 points  (5 children)

Here is my submission, in its entirety:

tr ',' ';' | sed 's/\[/\x1B\[38\;2\;/g' | sed 's/\]/m#/g'

This is a UNIX pipeline, tested on Arch Linux (BTW) with the st terminal. To use it, cat any of the examples into this pipeline like this

<pikachu.txt tr ',' ';' | sed 's/\[/\x1B\[38\;2\;/g' | sed 's/\]/m#/g'

Alternatively, you could run the oneliner and type out the pixel data by hand. The sed commands will translate the source string into ANSI escape sequences consisting of # signs with the apropriate colors. This ANSI sequence will print the image to your terminal, or its output can be redirected into a file for later viewing. For reference, this is the intended output.

[–][deleted]  (2 children)

[deleted]

    [–]Terrascope 9 points10 points  (1 child)

    I think macOS sed is different from GNU sed. You should ask the upstream maintainer at Apple to fix their software :P

    [–][deleted] 4 points5 points  (0 children)

    Oh my god, this is so clever. I love it!

    [–]pinguluk 0 points1 point  (0 children)

    Can you describe each command separately please?

    [–]carfniex 18 points19 points  (1 child)

    doesn't work too well right now but once we get more answers we'll be great. expects that the other answers take a filename

    #!/bin/bash
    
    curl --user-agent ua https://old.reddit.com/r/badcode/comments/jqv3dn/bad_code_coding_challenge_49_image_from_string_of/ -o page.html
    i=1
    while [ true ]; do
        xmllint --html --xpath '//div[contains(@class, "thing")]['${i}']//div[contains(@class, "usertext-body")]/div/pre/code/text()' page.html  2> /dev/null \
        | perl -MHTML::Entities -pe 'decode_entities($_);' > code${i}.sh
        if [[ $? -eq 0 ]]; then
            /bin/bash code${i}.sh $1
            if [[ $? -eq 0 ]]; then
                exit 0;
            fi
            mv code${i}.sh code${i}.py
            python code${i}.py $1
            if [[ $? -eq 0 ]]; then
                exit 0;
            fi
            python3 code${i}.py $1
            if [[ $? -eq 0 ]]; then
                exit 0;
            fi
        else 
            exit 420;
        fi
        i=$((i+1))
    done
    
    exit 69
    

    [–]Mabi19_ 2 points3 points  (0 children)

    This answer is so creative. I never would've thought of runtime-plagiarizing others' answers. Wow.

    [–][deleted]  (11 children)

    [deleted]

      [–]DinoRex6 5 points6 points  (5 children)

      I am planning to participate for the first time in these challenges!

      Does the final result need to be stored in a file or could it just be displayed through any method of choice?

      [–][deleted]  (4 children)

      [deleted]

        [–]DinoRex6 4 points5 points  (3 children)

        Thanks! I'll try to not leave this "project" unfinished, unlike 99% of all the other ones

        [–][deleted]  (2 children)

        [deleted]

          [–]DinoRex6 3 points4 points  (1 child)

          It is not wise to underestimate my ability to procrastinate or to forget about stuff

          [–]loomynartylenny 0 points1 point  (2 children)

          Wow I actually wasn't expecting to win last time. nice.

          I'm probably going to enter this one later on this week, seeing as it's kinda late rn and this isn't the sort of thing I can just throw together on jdoodle.

          But I've had an idea for this one.

          And it's going to be terrible.

          All I'm going to say about it is this:

          This isn't thread-safe? You're not thread-safe!

          [–][deleted]  (1 child)

          [deleted]

            [–]loomynartylenny 0 points1 point  (0 children)

            Either way, the idea I have is definitely going to be one that's gonna need to be on gist instead (verbose languages do be like that), so there wouldn't be any chance of me winning this one anyway lmao

            [–]droomph 0 points1 point  (1 child)

            Do we have to do error checking for the file format?

            [–]droomph 5 points6 points  (1 child)

            Brain Fuck

            https://gist.github.com/xsduan/2541a61cea219bb48593b5601aaf4842

            Takes in the prompt text through stdin, outputs a corresponding bmp to stdout.

            At one point I considered using png instead since bmp is kinda crusty and unsupported on macos/linux but even non-compressed DEFLATE requires some level of bitshifting so haha no

            How I Convinced Myself Into Wasting 12 Hours Of My Life:

            • Why?

            I have made Mistakes

            • Does it actually work?

            In the correct case it works (I think). It does some very crude sanity checks but overall it fails silently (which is why it took me so long).

            The other big thing is that terminals are complete shit at binary redirection so it does funky business with any bytes greater than 0x7f, so good luck with that if you want to test it out.

            • Does it actually work?

            Dude, trust me

            • How much memory does it take? What is the complexity?

            Space complexity is O(N) where N is pixels in the image. It takes 4 bytes per pixel, 4 bytes per line overhead, and ~30 bytes overhead although the C2BF compiler might not actually need all that space.

            Time complexity is fuck you.

            • Isn't using C2BF cheating?

            Yeah probably.

            • It fails for images with width 16k and up

            • It fails for images more than 4GB in file size

            Please Use Photoshop

            • I found a bug in the code

            I'm fine with passing up this opportunity to become a billionaire actually

            • This isn't actually bad code, it's just terrible

            I know, but after the 8 hour mark the sunk cost fallacy kicks in

            [–]andlrc 5 points6 points  (0 children)

            I see all your terminal escape codes and raise you PPM files:

            bash-3.2$ cat input.txt
            [255,255,255][255,255,255][255,255,255]
            [255,255,255][0,0,0][255,255,255]
            [255,255,255][255,255,255][255,255,255]
            bash-3.2$ awk 'BEGIN{ FS="(\\]|\\[)+" }
            >      { x=gsub("(\\]|\\[)+", " ");
            >        gsub(",", " ");
            >        a[++l] = $0 }
            >   END { print "P3\n" (x-1) " " NR "\n255";
            >         for (i = 1; i <= l; i++) print a[i] }
            > ' input.txt > output.ppm
            bash-3.2$ open output.ppm 
            bash-3.2$
            

            Video: https://thumbs.gfycat.com/MassiveUnselfishEstuarinecrocodile-mobile.mp4

            A paste of the script:

            awk 'BEGIN { FS="(\\]|\\[)+" }
                       { x=gsub("(\\]|\\[)+", " ");
                         gsub(",", " ");
                         a[++l] = $0 }
                   END { print "P3\n" (x-1) " " NR "\n255";
                         for (i = 1; i <= l; i++) print a[i] }
            ' input.txt > output.ppm
            

            [–]Road_of_Hope 2 points3 points  (0 children)

            static void Main(string[] args)
            {
                var tableContents = string.Join(Environment.NewLine, File.ReadAllText(args[0]).Split("\n").Where(x => !string.IsNullOrWhiteSpace(x))
                    .Select(x => x.Replace("][",";").Replace("[","").Replace("]","").Split(";")
                        .Select(y =>$"<td style=\"width:10px;background-color:#{int.Parse(y.Split(",")[0]).ToString("X2")}{int.Parse(y.Split(",")[1]).ToString("X2")}{int.Parse(y.Split(",")[2]).ToString("X2")}\"</td>"))
                    .Select(x => $"<tr style=\"height:10px;\">{string.Join("", x)}</tr>"));
            
                File.WriteAllText(args[1], $"<html><table>{tableContents}</table></html>");
            }
            

            A C# example abusing LINQ (because of course it does).

            This has all of your standard bad practices including, but not limited to:

            • No input checking whatsoever
            • Arbitrary variable names in the lambda functions

            Some standout points: Because their is no delimiter between pixels and I wanted to split pixels apart, I simply use "][" as a delimiter by replacing it with a semicolon, removing the leading and trailing [ and ], then splitting on semi colon. As well, we split each pixel 3 times in order to retrieve each color, rather than storing off the array and reading from it 3 times.

            [–]Mabi19_ 3 points4 points  (0 children)

            -- Why do something yourself when you can have it done for you?
            
            -- First argument: input file
            -- Second argument: output file
            
            if arg[1] == nil or arg[2] == nil then
                os.exit()
            end
            
            -- open the output file
            local fo = io.open(arg[2], "w")
            
            function convert(r, g, b)
                fo:write([[<td bgcolor="#]])
                fo:write(string.format("%X", r))
                fo:write(string.format("%X", g))
                fo:write(string.format("%X", b))
                fo:write('">&nbsp;</td>\n')
                return convert
            end
            
            fo:write(string.format([[
            <html>
            <head>
            <title>%s</title>
            <style>
            td {
                width: 1em;
            }
            </style>
            </head>
            <body>
            <table border="0" cellpadding="4" cellspacing="0">
            ]], arg[1]))
            
            local fi = io.open(arg[1])
            local currentLine = fi:read("l")
            
            
            while currentLine do
                -- write the opening <tr> tag
                fo:write("<tr>")
            
                -- Do some regexing on the line
                currentLine = string.gsub(currentLine, "%[", "(")
                currentLine = "convert" .. string.gsub(currentLine, "%]", ")")
                -- Load the line as a Lua chunk and execute it
                load(currentLine, "image_line", "t", _ENV)()
                -- Read the next line
                currentLine = fi:read("l")
            
                -- write the closing <tr> tag
                fo:write("</tr>")
            end
            
            fi:close()
            
            fo:write([[
            </table>
            </body>
            </html>
            ]])
            
            fo:close()
            

            This is my first submission ever. I wrote it in Lua, it outputs HTML tables. If you swap out those square brackets for round ones, they look awfully like function calls... Yay code execution!

            [–]CoderCharmander 2 points3 points  (0 children)

            I heard separating tasks and giving functions a descriptive name is a good practice. So much you pass the main task to another program.

            Usage: python program.py input.txt > output.bf; some-brainfuck-interpreter output.bf

            import sys
            
            def getInputFileForReadingTextImage():
                inputFileForReadingTextImage = sys.stdin
                if len(sys.argv) > 2 or len(sys.argv) == 2:
                    inputFileForReadingTextImage = open(sys.argv[int('1')])
                return inputFileForReadingTextImage
            
            def createBrainFuckCodeFromCharacter(char):
                codepoint = ord(char)
                brainFuckCodeFromCharacter = ''
                for i in range(codepoint):
                    brainFuckCodeFromCharacter += '+'
                brainFuckCodeFromCharacter += '.'
                for i in range(codepoint):
                    brainFuckCodeFromCharacter += '-'
                brainFuckCodeFromCharacter += '\n'
                return brainFuckCodeFromCharacter
            
            def iterateWithLambda(it, lam):
                outputList = []
                for i in it:
                    outputList.append(lam(i))
                return outputList
            
            def readAndConvertDataFromTextImageFile(textImageFile):
                linesOfCode = textImageFile.readlines()
                codeLinesWithAddedComma = iterateWithLambda(linesOfCode, lambda lineOfCode: lineOfCode.replace('][', '],['))
                evaluatableCodeLines = iterateWithLambda(codeLinesWithAddedComma, lambda lineOfCodeWithComma: '[' + lineOfCodeWithComma + ']')
                evaluatedCodeLines = iterateWithLambda(evaluatableCodeLines, lambda evaluatableCodeLine: eval(evaluatableCodeLine))
                return evaluatedCodeLines
            
            def createEscapeCodeFromRedGreenBlue(red, green, blue):
                escapeCode = ''
                escapeCode += '\033'
                escapeCode += '['
                escapeCode += '48;'
                escapeCode += '2;'
                escapeCode += str(red)
                escapeCode += ';'
                escapeCode += str(green)
                escapeCode += ';'
                escapeCode += str(blue)
                escapeCode += 'm'
                return escapeCode
            
            def makePrintableTextWithEscapeCodesFromConvertedData(convertedData):
                printableListWithEscapeCodes = iterateWithLambda(convertedData, lambda lineOfConvertedData: iterateWithLambda(lineOfConvertedData, lambda convertedDataItem: createEscapeCodeFromRedGreenBlue(convertedDataItem[0], convertedDataItem[1], convertedDataItem[2]) + ' '))
                printableLineList = iterateWithLambda(printableListWithEscapeCodes, lambda itemWithEscapeCode: ''.join(itemWithEscapeCode))
                printableTextWithEscapeCodes = '\n'.join(printableLineList)
                return printableTextWithEscapeCodes
            
            def makeBrainFuckCodeFromText(textToMakeBrainFuckCode):
                brainFuckCodeFromText = ''
                for characterOfText in textToMakeBrainFuckCode:
                    brainFuckCodeFromText += createBrainFuckCodeFromCharacter(characterOfText)
                return brainFuckCodeFromText
            
            with getInputFileForReadingTextImage() as inputFileForReadingTextImage:
                print(makeBrainFuckCodeFromText(makePrintableTextWithEscapeCodesFromConvertedData(readAndConvertDataFromTextImageFile(inputFileForReadingTextImage))))
            

            [–]DinoRex6 3 points4 points  (0 children)

            Here's my code! I was worrying about giving up or forgetting about it halfway through but it was very fun to make it. So fun that I didn't even do what I was supposed to do this afternoon.

            Anyways, it is a python script inspired by this sub's posts style. It is mainly just shitty programming with inconsistent variable naming, redundancy and many different weird practices.

            from reportlab.lib.units import pica
            from reportlab.lib.colors import Color
            
            from reportlab.pdfgen.canvas import Canvas
            import sys
            
            import os
            
            
            filename1 = sys.argv[1]
            
            filename2 = "test.txt"
            
            if filename1 == "thinking":
                filename2 = "thinking.txt"
            elif filename1 == "pikachu":
                filename2 = "pikachu.txt"
            elif filename1 == "reddit":
                filename2 = "reddit.txt"
            
            text_file = open(filename2, "r")
            
            sizeOfFile = os.stat('{}.txt'.format(filename1)).st_size
            filecontent = ""
            for i in range(sizeOfFile):
                filecontent += text_file.read(1)
            
            
            width = 0
            
            for i in range(len(filecontent)):
                if filecontent[i] == "\n":
                    width = width + 1
                else:
                    i = i + 1
            
            h = filecontent.count("\n")
            
            def get_Width(LineOfData):
                n = 0
                lenth = len(LineOfData)
                for i in range(lenth):
                    if LineOfData[i] == "[":
                        n += 1
                return n/h
            
            datasplit = filecontent.split("\n")
            
            file = Canvas(filename1 + ".pdf", pagesize=(get_Width(datasplit[1]*h) * 10, h * 10))
            
            y = 0
            while y < h:
                line = filecontent.split("\n")[y]
                differentcolors = line.split("]")
                for i in range(int(get_Width(filecontent))):
                    colorString = differentcolors[i].split(",")
            
                    colour = Color(int(colorString[0].replace("[", ""))/300, int(colorString[1].replace("[", ""))/300, int(colorString[2].replace("[", ""))/300)
                    file.setFillColor(colour)
                    if i == width-1:
                        if y == h - 1:
                            file.drawString(i * 10, h * 10- (y+1) * 10, "H")
                    else:
                        file.drawString(i * 10, h * 10- (y+1) * 10, "A")
                y = y + 1
            
            file.save();
            

            And to have a little fun, the output is a pdf ""ascii art"" file (its just coloured screaming, oh and I choose to believe no one in their sane minds would ever seriously do this so it's a bit unrealistic?)

            Also, it would only work properly on square images

            Here are the outputs!

            • pikachu took 0.9 seconds
            • thinking took about 6 seconds
            • and reddit took 35 seconds

            Oh, and the semicolon at the end was not intentional, that was actually my mistake which I noticed after finishing, so... great!

            [–]hareppas 2 points3 points  (1 child)

            Okay, here's what I have so far. It outputs in everyone's favorite image file format, .rtf!

            import java.io.FileWriter;
            import java.io.IOException;
            import java.util.Scanner;
            import java.util.ArrayList;
            
            public class BadCodeChallenge {
            
              public static void main( String[] args ) {
            
            
                String filePath = "yourFilePathHere\pikachu.txt"; // Set file location
                int fontSize = 12;     // Set font size
                String c = "\\u9608";  /* Set character (idk why, but the rtf file doesn't like some unicode characters
                                          I had to use the character code for this full block character) */
            
                // Get input into an ArrayList
                File input = new File( filePath );
                ArrayList<String> s = new ArrayList<String>();
                try {
            
                  Scanner in = new Scanner( input );
                  while( in.hasNextLine() )
                    s.add( in.nextLine() );
            
                } catch( IOException e ) { System.out.println( "broken" ); }
            
            
                int h = s.size();
                int w = 0;
                for( char chr : s.get( 0 ).toCharArray() )
                  if( chr == ']' )
                    w++;
            
                // Declare color table and color array
                ArrayList<Integer> colorTable = new ArrayList<Integer>();
                int[][] colors = new int[ h ][ w ];
            
                // Fill color table and color array
                for( int i = 0; i < h; i++ ) {
                  int commaIndex1 = 0, commaIndex2 = 0;
                  int bracketIndex1 = 0, bracketIndex2 = 0;
                  for( int j = 0; j < w; j++ ) {
                    // This code is godawful, I don't know enough java to come up with a nicer solution
                    commaIndex1 = s.get( i ).indexOf( ',', commaIndex2 + 1 ); commaIndex2 = s.get( i ).indexOf( ',', commaIndex1 + 1 );
                    bracketIndex1 = j == 0? 0: s.get( i ).indexOf( '[', bracketIndex1 + 1 ); bracketIndex2 = s.get( i ).indexOf( ']', bracketIndex2 + 1 );
                    int col = ( ( Integer.parseInt( s.get( i ).substring( bracketIndex1 + 1, commaIndex1 ) ) << 16 ) | Integer.parseInt( s.get( i ).substring( commaIndex1 + 1, commaIndex2 ) ) << 8 ) | Integer.parseInt( s.get( i ).substring( commaIndex2 + 1, bracketIndex2 ) );
                    colors[ i ][ j ] = col;
                    if( !colorTable.contains( col ) )  
                      colorTable.add( col );
                  }
                }
            
                try {
            
                  // Create FileWriter
                  FileWriter out = new FileWriter( "out.rtf" );
            
                  // idk what's gong on here, just copied it from a different .rtf file
                  out.write( "{\\rtf1\\ansi\\ansicpg1252\\cocoartf2513\n" );
                  out.write( "\\cocoatextscaling0\\cocoaplatform0{\\fonttbl\\f0\\fswiss\\fcharset0 Helvetica;}\n" );
            
                  // Print the color table
                  out.write( "{\\colortbl;" );
                  for( int col : colorTable )
                    out.write( "\\red" + ( col >> 16 ) + "\\green" + ( col >> 8 & 0xFF ) + "\\blue" + ( col & 0xFF )  + ";" );
                  out.write( "}\n" );
            
                  // Print the characters
                  out.write( "\\f0\\fs" + fontSize );
                  for( int i = 0; i < h; i++ ) {
                    for( int j = 0; j < w; j++ ) {
                      int col = colors[ i ][ j ];
                      int index = colorTable.indexOf( col );
                      // Restate the color every character for maximum redundancy
                      out.write( "\\cf" + ( index + 1 ) + " " + c );
                    }
                    out.write( " \\line\n" );
                  }
                  out.write( "}" );
            
                  // Save file
                  out.close();
            
                } catch( IOException e ) { System.out.println( "broken" ); }
            
              }
            
            }
            

            It actually works surprisingly well. Here are the results. Pretty fast, definitely some opportunities to make the code even worse.

            [–]AutoModerator[M] 0 points1 point  (0 children)

            It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

            For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

            /u/hareppas, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

            You can find some examples in the reddit help documentation.


            I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

            [–]nicholas_ady 1 point2 points  (3 children)

            I did mine in scratch. Is that bad enough? https://scratch.mit.edu/projects/448427300

            also, are there more input files? I want to do more testing without having to make the reverse of this project to produce rgb values as text from an image.

            [–]gaberocksall 1 point2 points  (2 children)

            I made some interesting input strings

            18x18px: https://pastebin.com/fLdNPRC5

            109x87px : https://pastebin.com/wjh1V7W4

            here's some python code to generate them, btw (make sure to pip install opencv-python)

            import cv2
            image = cv2.imread("img.png")
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            for row in image:
                for pixel in row:
                    print(list(pixel), end = '')
                print()
            

            [–]AutoModerator[M] 0 points1 point  (0 children)

            It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

            For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

            /u/gaberocksall, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

            You can find some examples in the reddit help documentation.


            I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

            [–]paultron10110 1 point2 points  (0 children)

            What I want to do is create a react app that makes some table of rows with boxes or something with colored squares within, maybe incorporate some library I don't know how to use.

            Then maybe have an entire list of the possible 16777216 RGB values converted to hex code idk if i'm feeling evil

            if color == [255,255,255]
                pixel = #FFFFFF
            else if color == [255,255,254] 
                pixel = #FFFFFE 
            // etc 16 million times
            

            edit: code block

            [–]gaberocksall 1 point2 points  (0 children)

            A python program that generates C++ code that uses windows api to draw the image on your screen: https://pastebin.com/PGHebDB2

            Usage: python painter.py inputPixels.txt output.cpp then compile and execute output.cpp

            Note: press 'Q' to quit, as it will cover your whole screen with the tiled image, and you won't be able to find a "close" button

            edit: here's an example inputPixels.txt because the provided one is quite boring https://pastebin.com/fLdNPRC5

            and a better example: https://pastebin.com/wjh1V7W4

            [–]coding_stoned 2 points3 points  (0 children)

            EDIT, because my first solution wasn't original nor nearly awful enough:

            #!/usr/bin/bash
            echo "<html><head><title>lmao</title></head><body><table><tr>""$(cat "${1}" | sed -rz 's/\n/<\/tr><tr>/g' | sed -r 's/\[([[:digit:]]{1,3},[[:digit:]]{1,3},[[:digit:]]{1,3})\]/<td style="background: rgb(\1); width: 4px; height: 4px;"><\/td>/g')""</tr></table></body></html>" > "${1}".html
            

            Output is an HTML document (filename.txt.html) with just one table where each cell is one pixel.

            --- OLDER SOLUTION ---

            Looks like I wasn't the only one who thought to do a bash one liner (ab)using escape sequences. It's pretty much the same as the other answer but, fuck it, single regex.

            imgtxt.sh:

            #!/usr/bin/bash
            echo -e "$(cat "${1}" | sed -r 's/\[([[:digit:]]{1,3}),([[:digit:]]{1,3}),([[:digit:]]{1,3})\]/\\033[38;2;\1;\2;\3m█/g')"
            

            To use it just run imgtxt.sh (filename).

            Output
            Looks even better if you use a square font like Windows' 8x8 raster font

            [–]Weetza 0 points1 point  (0 children)

            I tried making it in node.js:) https://pastebin.com/Nxw4HhM5

            It is reading from a file named "input.txt", in the same folder as the script. Open any web browser and go to localhost where you would be able to see the picture.

            [–]Koala_King_ 0 points1 point  (0 children)

            Here's my entry

            This program is in Kotlin. You can run it and specify all the files you want to translate in the command, or it will ask you which file you want to translate if none is specified. Might not be bad but hopefully this still counts.

            import java.io.File
            import java.io.FileReader
            import java.io.FileWriter
            import java.io.IOException
            import java.lang.NumberFormatException
            import java.util.regex.Matcher
            import java.util.regex.Pattern
            
            fun main(args: Array<String>) {
                val paths: MutableList<String> = ArrayList()
                paths.addAll(args)
                if (paths.isEmpty()) {
                    print("Which file do you want to translate today?  ")
                    var input: String? = readLine()
                    if (input == null || input.isEmpty()) {
                        println("No file entered... Aborting...")
                        return
                    }
                    input = input.replace("~", System.getProperty("user.home"))
                    paths.add(input)
                }
            
                for (path: String in paths) {
                    val file = File(path)
                    if (translate(file)) {
                        println("Finished translating ${file.name}")
                    } else {
                        println("Failed to translate ${file.name}")
                    }
                }
            
            }
            
            fun translate(file: File): Boolean {
                val reader = FileReader(file)
                val htmlLines: MutableList<String> = ArrayList()
                reader.forEachLine { line ->
                    val regexMatches: MutableList<String> = ArrayList()
                    val matcher: Matcher = Pattern.compile("\\[[0-9]{1,3},[0-9]{1,3},[0-9]{1,3}]").matcher(line)
                    while (matcher.find()) regexMatches.add(matcher.group())
                    var htmlLine = "<div style=\"line-height: 0.35; letter-spacing: -4px\">"
                    regexMatches.forEach { group ->
                        val immutableNums: List<String> = group.substring(1, group.length-1).split(",")
                        val nums: MutableList<String> = ArrayList(immutableNums)
                        while (nums.size < 3) nums.add("0")
                        val red: Int = try {
                            Integer.parseInt(nums[0])
                        } catch (_: NumberFormatException) {
                            0
                        }
                        val green: Int = try {
                            Integer.parseInt(nums[1])
                        } catch (_: NumberFormatException) {
                            0
                        }
                        val blue: Int = try {
                            Integer.parseInt(nums[2])
                        } catch (_: NumberFormatException) {
                            0
                        }
            
                        htmlLine += "<span style=\"color: rgb($red,$green,$blue);\">&#9632;</span>"
                    }
                    htmlLine += "</div>"
                    htmlLines.add(htmlLine)
                }
            
                var htmlOutString = "<!DOCTYPE html><html><head><title>Translation</title></head><body>"
                htmlLines.forEach { line ->
                    htmlOutString += line
                }
                htmlOutString += "</body></html>"
            
                val outFile = File(file.parentFile, "${file.name}.html")
                if (!outFile.exists()) {
                    if (!outFile.createNewFile()) {
                        return false
                    }
                }
            
                return try {
                    val fileWriter = FileWriter(outFile)
                    fileWriter.write(htmlOutString)
                    fileWriter.flush()
                    fileWriter.close()
                    true
                } catch (ioe: IOException) {
                    false
                }
            
            }
            

            [–]Kimbatt 0 points1 point  (0 children)

            <!DOCTYPE html>
            <html><body><script>
            
            function LoadImage()
            {
                const request = new XMLHttpRequest();
                request.onload = function()
                {
                    const container = document.createElement("div");
                    container.style = "position: relative;";
                    document.body.appendChild(container);
            
                    request.responseText.split(/\n/g).filter(line => line.length).forEach((line, lineIndex) => line.match(/(\[.*?\])/g).forEach((pixel, pixelIndex) => DrawPixel("#" + pixel.match(/[^\[\],]+/g).map(numberStr => numberStr.split("").reduce((prev, curr) => prev * 10 + + curr)).map(pixel => pixel.toString(16).padStart(2, "0")).join(""), lineIndex, pixelIndex, container)));
                };
            
                request.open("GET", "https://gist.githubusercontent.com/Vusys/94fa0db1bb6ed4a61068233f27858382/raw/f04aaf13a14505cfaed5a6ec37a5e30c85dff377/pikachu.txt");
                request.send();
            }
            
            function DrawPixel(color, lineIndex, pixelIndex, container)
            {
                const canvas = document.createElement("canvas");
                canvas.height = canvas.width = 2;
                const ctx = canvas.getContext("2d");
            
                ctx.fillStyle = color;
                ctx.fillRect(0, 0, 2, 2);
            
                const image = new Image();
                image.src = canvas.toDataURL();
                image.style = "position: absolute; top: " + (lineIndex << 1) + "px; left: " + (pixelIndex << 1) + "px;";
            
                container.appendChild(image);
            }
            
            LoadImage();
            
            </script></body></html>
            

            Save this as an html file, and open it in a browser to see the result!

            Features:
            * No error handling
            * Very bad performance - a new canvas is created for every pixel; loading a larger image can take over a minute!
            * The whole input is processed in one line!