Birk http://birk-jensen.dk dot dot dot Sun, 28 Jul 2013 10:37:01 +0000 en-US hourly 1 https://wordpress.org/?v=5.9.9 Cowon Emulator status http://birk-jensen.dk/2011/07/cowon-emulator-status/ http://birk-jensen.dk/2011/07/cowon-emulator-status/#comments Wed, 06 Jul 2011 10:55:11 +0000 http://birk-jensen.dk/?p=398 Read more »

]]>
This post is mainly for my self, if you don’t have the basic understanding of how to make UCI’s for the Cowon this post wont make much sense.
I’ve been busy at work lately, so I haven’t really gotten as far as I wanted on my Cowon J3 & S9 emulator. But I’ll write a quick status update here and which problems I’ve encountered.

As it turns out, my understanding of how the device worked was very limited, and some of what I knew turned out to be wrong. My main fault was not understanding how the launcher.swf worked. It turns out that I only need to implement the ext_fscommand2 functions and not the functions starting with “gn_” (I found references to this function in some decompiled UCI’s). The “gn_” functions are in the launcher.swf which I simply load from the emulator (I had implemented about 25% of the launcher.swf in my emulator before I realized this :().

I’ve also figured out how I will make the file listing, or I’m down to 2 ideas. Both ideas include an AIR application that reads the device folders (which is going to be fun because I’ve never made an AIR application before).
The first solution (the one I’ll probably end up using), will have the application save an XML file with the folder and file structure. This XML is then loaded by the emulator and used to mimic the file system, requiring a manual update of the filesystem every time a file is changed (but like on the actual device the files don’t change that often).

After I get the filesystem up and running, it should be rather easy to emulate the actual playing of an MP3. But then again I thought a lot of the things that caused trouble in this project would’ve been easy.

Another thing I’ll give it a week or to and see if I get started up on the emulator again, if I don’t I’ll just release it in it’s current form, so you can see how it works for yourself. The current form however is a not to well documented and still in progress, set of classes with no actual UI everything I change I do code time.

]]>
http://birk-jensen.dk/2011/07/cowon-emulator-status/feed/ 1
Cowon J3 (Cow’n’Emu) http://birk-jensen.dk/2011/04/cowon-j3-cownemu/ http://birk-jensen.dk/2011/04/cowon-j3-cownemu/#comments Sat, 16 Apr 2011 14:53:08 +0000 http://birk-jensen.dk/?p=384 Read more »

]]>
So I’ve recently bought the Cowon J3 32gb mp3 player. It’s a small upgrade from my Cowon S9, which was the 16gb version.

Both players has an excellent sound quality, the best I’ve ever had in an mp3 player (I’ve owned a couple of different ones, Rio, Creative, iPod, Samsung and something that starts with F that I can’t remember the name of anymore).
My only problem with the 2 Cowons is the touch-screen user interface, which has gotten a lot better with the J3. The problem is, even though the touch UI is improved, the new button(buttons on the actual device) layout is not as good as it was with the S9 (my own opinion).

But to the point of it all. Both the S9 and J3 runs on a Adobe Flash UI, and Cowon have opened up for their API, so you can make your own UI with flash and Actionscript 2 (unfortunatly the UI runs on a AVM 1 in Flash Player 7, so you can’t use AS3).
So I started out making a simple SWF to test out what the J3 was capable of, and how to use the Cowon API. And everything was really straight forward, to call their API you use the ext_fscommand2 function, and passed along some arguments letting the device know what you want to do.
The main problem is the testing phase. You need to plugin the player, transfer your SWF to it, plug it out, turn it on and then test it. The first couple of times it wasn’t an issue, but the 5th time you do it, it gets annoying, and the 10th time I did it, I stopped. It was to much of a hassle. So I searched the net for an emulator so I could test my project right away.
Now the only emulator I could find had no download link, and no one seemed to update it. So I decided to start working on my own.

So far I’ve implemented the ext_fscommand2 function and have it working as intended. But I haven’t made any actual functionality that simulates the device yet. One of the things I’m still having a hard time with is the Key events. I need to catch all the events from the UserSWF (the SWF you wish to load onto the device), and handle them in my own emulated environment instead of having Flash doing it for me.

Anyway, that was a long post just to tell you that I had started work on a Cowon S9+J3 emulator. Hopefully I’ll have a running alpha version next time I post about the subject.

]]>
http://birk-jensen.dk/2011/04/cowon-j3-cownemu/feed/ 3
CSSParser release http://birk-jensen.dk/2011/04/cssparser-release/ http://birk-jensen.dk/2011/04/cssparser-release/#respond Sun, 10 Apr 2011 19:46:23 +0000 http://birk-jensen.dk/?p=367 Read more »

]]>
So… I haven’t really been doing any work at all on the CSSParser(my own CSS Tidy project for reading and compressing CSS) I started on a couple of months ago. What happened is what always happens with my own projects. After I’ve implemented the initial idea, I start to loose interest.
But I’ve made it further with this CSSParser than I usually do, so I’ve decided to release the source code for the project. Not every function will be well documented but I’ve tried to comment as much as possible.
Download it here.

I’ll do a quick explanation of how the process, just to give an idea of how it all works.

  1. The CSSParser class reads a given CSS, using a single preg_match_all call.
  2. Now then class will start to build up an array of CSSSelector classes. This class will hold all the properties and identifiers of a CSS selector from the given CSS.
  3. Each property of the CSSSelector will be held in a CSSProperty class or a class extended the CSSProperty like CSSBorder and CSSBox. This way it’s easy to add more specific output on properties, simply by extending the CSSProperty class and making your own property class.
  4. Now all the data is structured in the CSSParser class. And by calling the printCSS() function with a CSSOut class as the argument, we can get the CSS out the way we want.

When printing the CSS a very primitive templating system is used, where the template simply is PHP that has access to the list of selectors after they’ve been run through a preProcess function optimizing the data for output.
An example can be the template1.php file (found in the downloadable zip):

identifier);
    echo " {\n";
    foreach ($selector->properties as $property) {
        foreach ($property->getProperty($settings) as $key => $value) {
            echo "\t$key: $value;\n";
        }
    }
    echo "}\n";
}?>


In the bottom of the CSSParser.php file, there’s a small test which outputs a CSS file using 2 different templates. This little example shows you how you can easily use the parser:

readCSS(file_get_contents(dirname(__FILE__) . "/data/test.css"));

$settings = new CSSOut();

echo "Readability:\n";
$settings->templateFile = "data/template1.php";
var_dump($css->printCSS($settings));

echo "\nSmallest:\n";
$settings->templateFile = "data/template2.php";
var_dump($css->printCSS($settings));
?>

This project is far from done (or well tested), so even though it can read and parse the simple test.css file included in the zip, it’s not ready for an actual live deployment. It’s simply a piece of code that shows how I would’ve implemented a CSS Parser if I had the time to finish it all.

So if you decide to download the project, here’s a little guide with places of interest (code pieces in the project I feel is vital for this to work or had most fun writing).

  • CSSParser->readCSS($cssString) This function is the heart of it all. It processes the CSS and sets up the selectors with the correct properties. I feel I’ve documented this function well, and since I don’t do regular expressions very often I’m particularly proud of the 2 patterns just at the start of this function!
  • CSSSelector->getHandler($property) The function that makes sure the correct CSSProperty class is used for a property. It’s actually a bit confusing, and I had to read it a couple of times again before realising what I was trying to achieve when I wrote it. It’s important to note that it’s connected with the $propertyList variable at the top of the CSSSelector.php file.
  • CSSBorder Yep the entire class. This was my first property class, then I wrote the CSSProperty class, so the CSSBorder could fit on it, and then wrote the CSSBox in between these to classes. The getBorderArray() function in this class, is also responsible for my Checking for a value speed test
]]>
http://birk-jensen.dk/2011/04/cssparser-release/feed/ 0
Checking for a value http://birk-jensen.dk/2010/12/checking-for-a-value/ http://birk-jensen.dk/2010/12/checking-for-a-value/#respond Sun, 19 Dec 2010 08:39:46 +0000 http://birk-jensen.dk/?p=322 Read more »

]]>
Reasoning behind the bench

I’ve been working a bit on my CSSParser (which I will rename to CSSReader og CSSHandler when I get around to it), and one thing I found out was, when reading shorthand values (like: border: 1px solid #00ffff;) you can’t assume they always come in the same order.
If we take a border property as an example:

.something {
  border-right: 1px dashed #00ff00;
  border-left: dashed 1px rgb(255,0,0);
  border-top blue solid 1px;
}

This shows that the border shorthand value can have a different order of subvalues, and the actual value data can change alot (notice the 3 different ways of defining a color, the rgb() still cause me a bit of trouble). So to set an array (mapped with [‘width’], [‘style’] and [‘color’]) I can’t just split the string and set it, I need to split the string and then try to guess every value. To guess the values I’ll be running through the following process:

I’ve tried to put the checks in the order I would assume most common, so I can continue the loop quickly after each check and skip the following ones.

The test

Link to test

Now the thing is I need to check if one value exists in a predefined list of values (this case it’s particularly the styles, but colors and width as well has some constant names they can use to define the numeric value). I figured there’s 3 ways of doing this. Actually I started with 5 ways, but as I learned previously I have to keep these tests down in size for it to work properly (the 2 ways I cut will be grayed in the list below):

  1. Having an array with all the predefined values, and checking it with in_array.
  2. Having all the predefined values in a string separated by spaces, then using strpos to look for our value.
  3. Flipping (array_flip) our array from earlier, and instead of in_array we use isset($array[‘our_value’]).
  4. Again using strpos to check, but instead of a string separated by spaces I tried a constant.
  5. Tried a preg_match on a string of values.

I’ve run the test for the same dataset, but testing for values on different positions in the set.

  • first value, is testing for the value which is placed as the first value in the dataset.
  • mid value, is a value there’s somewhere the middle of the set.
  • last value, is last value of the set.
  • no hit, here I test for a value that doesn’t exist in the set.


The obvious winner is the isset method which is almost 5 times faster than checking for the value using the in_array (which was what I would have chosen to start with). To avoid using the array_flip you can always just write the array up with keys and then equal some value, like:

 0, "dotted" => 0, "dashed" => 0);
?>

It’s just a hassle to write larger sets of data that way, so using the array_flip function really helps out here, which is also the method I’ve chosen for my CSS project.

]]>
http://birk-jensen.dk/2010/12/checking-for-a-value/feed/ 0
Benchmark class, release (& first test) http://birk-jensen.dk/2010/11/benchmark-class-release-first-test/ http://birk-jensen.dk/2010/11/benchmark-class-release-first-test/#respond Thu, 04 Nov 2010 10:09:50 +0000 http://birk-jensen.dk/?p=290 Read more »

]]>
So as promised I’ve cleaned up and commented a bit on my Bench class. And let me get to it, you can
Download it here.

Bench suite

I’ve also made my first test in my new (and not to pretty, but working) bench suite. The bench suite is a site where I can gather my different tests, and be able to easily access them later on for references. So far it’s a very simple setup, where I have:

  • A list of the tests. This goes through a directory where each test has it’s own test file, and use some of the data in the file to make an informative list.
  • A runner. Which will run each test, and output the results in an easy to read table, along with the actual source code of the test.

Down the road I would like to improve a bit on the interface which is lacking to say the least. I’ve also been planning on saving the test data so I can get an average result of all the tests run.

Empty loops test

So the very first test I’ve done is a simple empty loop(it will run the test every time you, so the result wont be identical to what I’ve displayed below) test. And it also works as a quick how-to for the class it self.
What I wanted to test with this bench, was the difference between the for, while and do..while loops, and as an added bonus I also tested a goto loop (more for the fun of things). I’ve also tested everything with a pre and post increment. Anyway the result of the test looks as following after it’s been through google docs:

To reach my conclusion I’ve run the test multiple times (the above chart is just from a single run), and it seems that the do..while is the fastest loop most of the time, followed by the while loop. A thing that I noticed was the for loop runs faster with pre incrementing(++$i) instead of post($i++). But the other loops tend to be faster with a post increment, don’t ask me why it’s just what I’ve observed.
Even though the do..while is notably faster (almost every time) I think I’ll stick to using the for loop for these kind of loops, unless I really need the speed. In case I needed the speed I would probably do a test with each loop to see what gain I actually would get in that specific case.

All in all a good first test, I think I’ll need to test fewer things in my next tests if possible. I could have skipped pre and post incrementing to make the chart a more readable, something I might keep in mind for my next bench.

]]>
http://birk-jensen.dk/2010/11/benchmark-class-release-first-test/feed/ 0
Benchmark class v1 http://birk-jensen.dk/2010/10/benchmark-class-v1/ http://birk-jensen.dk/2010/10/benchmark-class-v1/#respond Thu, 28 Oct 2010 11:27:40 +0000 http://birk-jensen.dk/?p=257 Read more »

]]>
So I’ve made a first version of the benchmarking class I’ve been talking about previously. While working on the CSSParser I encountered one of those micro-optimization situations, so I made a quick first draft of the Bench class (I’ll post the actual benchmark in another post).
The outline of the Bench class is as the following:

Function Description
start($test, $subTest = “”) Start a test, with a test title (which is also the identifier for the test). It’s possible to supply additional sub tests to the test, this is helpful when doing the same code test but with different inputs.
end($test, $subTest = “”) Ends the test with the test and subTest identifier.
tick($test, $subTest = “”) Set a mid point in a test, this way we can easily make more fix points if needed.
getResult($dec = 6) Returns all the tests in a neatly packed table, the $dec is the amount of decimals on the time measurement.

Let me show a simple example where we test 2 empty for and while loops and a recursive function:

start("for loop", "1000");
for ($i = 0; $i < 1000; $i++) {
}
$b->end("for loop", "1000");
$b->start("for loop", "10000");
for ($i = 0; $i < 10000; $i++) {
}
$b->end("for loop", "10000");

$b->start("while", "1000");
$i = 0;
while ($i++ < 1000) {
}
$b->end("while", "1000");
$b->start("while", "10000");
$i = 0;
while ($i++ < 10000) {
}
$b->end("while", "10000");

$b->start("recursive", "1000");
recursive(1000);
$b->end("recursive", "1000");
$b->start("recursive", "10000");
recursive(10000);
$b->end("recursive", "10000");

echo $b->getResult();
?>
simple bench output

for loop 	0.000097	0.000810	0.000454	100.00%
while    	0.000074	0.000629	0.000351	77.48%
recursive	0.001844	0.016954	0.009399	2072.14%

The first column is the name of the test.
The following 2 columns is each sub test, so the first number is the time of our “1000” iterations and the second number is “10000” iterations.
The fourth column represents the average of all the sub tests (it’s not always this is informative, so there will be an option to remove this in future versions).
The last column is the difference between all the tests average. It will set the first test to 100%, the rest of the tests will be calculated in relation to this number.
With the output formatted this way, you can easily copy and paste it into a spreadsheet and display it in what ever chart that fits your purpose. Just remember not to use the percentage in your data set:
An example of the data in a Google Docs spreadsheet

I still need to clean up and comment the class some more, before I’m comfortable with putting it up online. But it’s rather small so if I get some time this weekend I’ll run through it, and it will be up next week.

]]>
http://birk-jensen.dk/2010/10/benchmark-class-v1/feed/ 0
Starting up my CSS Minify project http://birk-jensen.dk/2010/10/starting-out-my-css-minify-project/ http://birk-jensen.dk/2010/10/starting-out-my-css-minify-project/#comments Tue, 19 Oct 2010 09:48:55 +0000 http://birk-jensen.dk/?p=246 Read more »

]]>
This is just a status update on my CSS Minify project, I will make more updates as I progress through the project. It’s basically a journal of my thoughts and design process, so if anything strikes you please do comment with some feedback.

So I started working on a way to minify my CSS files. I know (or well I found out, just after I started working on my own project) that there’s a well written and very functional CSSTidy which does exactly what I want to do. I will anyhow still continue my own project, mostly for the learning process, but also because it’s been a long time since I’ve had a project of my own and I miss that.
My initial thought was to parse the CSS using regular expressions, but the lexical approach CSSTidy uses caught my eye.
I’ve decided to start out parsing with the regular expressions. I will eventually try to copycat the CSSTidy way, just to get a better understanding of lexical analysis, and having CSSTidy as a result sheet.

So far I’ve made the parser, and it seems to work on proper CSS I will need to test it up against some messy CSS.
I had my CSSParser class, with a $selectors array holding all the selectors (my CSSSelector classes). The CSSSelector class had a similar $properties array, holding all the properties (CSSProperties class) for the selector.
This seemed a bit overkill, the arrays were both using a key being the selector/property name and a value being the class, the class it self just being a class with a value property. So I will remove the 2(selector and property) classes, and just use a simpler array structure.
I do however still like the idea of having the selector and property classes, it fits nicely into the whole CSS principal. I’ve been planing to use them when it comes to outputting the CSS again, but in that case why not just use them to start with … I’m torn.

]]>
http://birk-jensen.dk/2010/10/starting-out-my-css-minify-project/feed/ 1
XML-RPC http://birk-jensen.dk/2010/09/xml-rpc/ http://birk-jensen.dk/2010/09/xml-rpc/#respond Wed, 29 Sep 2010 08:26:31 +0000 http://birk-jensen.dk/?p=221 Read more »

]]>
This is simply a copy of my old XML-RPC article (2005). I’ve done a bit of content editing when converting the article to this blog format, but still most of the content is unchanged.

1. Introduction

So you’ve decided to learn XML-RPC[1], or did the name just sound “freaky” and raised a little interest? If it did I suggest you read on, if you already know what XML-RPC is, then just skip the next intro part

1.1 What is XML-RPC

XML-RPC is a way to make web services, it packs the requests and responses in XML both the client and the server can understand.
For those who don’t know a web service is a function of some sort placed on the net (it could be a function to convert a string into all upper case letters, which we are going to make in the examples below). The smart thing is that, a web service can be programmed in any kind of language, and any other language can use it. Many big sites have a web service, for example Amazon has a web service that allows you to search books and information.
Another smart thing about XML-RPC (and to my knowledge all other web services), is that they can be run from a web server. Not only is this smart, because you don’t need to install some high-end server dedicated to the purpose. But you don’t have to worry about firewalls.

1.2 Installing XML-RPC

If you’ve installed an extension before, this should be no problem at all, just install the XML-RPC extension. But if this is your first time, the following links will help a bit:
Windows users: http://www.php.net/manual/en/install.windows.extensions.php
Unix users: http://www.php.net/manual/en/install.unix.php
OS X users: http://www.php.net/manual/en/install.macosx.php
For you guys(and gals) who compile PHP: –with-xmlrpc.

2. The Server

For obviusly reasons we start making the server, which contains the function our client will be calling later on.
I’ve decided to comment the code, this way I don’t have to explain it to you after you’ve read it. And you can by remember what it all does later on:

All done with the server part. If you haven’t figured out exactly how the server works yet, then let me give you a little insight. In short terms, it’s just a php file, that is called by the client, through a normal URL. It then processes the contents which the client send, and return a result.

3. The Client

Well you made it so far, so why not make the client to test your server as well. Even though we made the server first, I must admit you’ll probably be using the client part a “wee” bit more. Of course it’s fun to mess around with the server, but chances are you’ll be using other webservices most of the time?
Anyway, as you might notice, the client code contains a little socket[2] programming. If you’ve never worked with sockets before don’t think to much of it, it’s not that hard, and you’ll propably pick up the on the code anyway.
When I wrote this article I had no idea of the cURL library, which I would propably be using for an actual project instead of my own request function.

The response from the serverstring(49) “Come again: All hail Philip the almighty… Obey!”

Hey, now wasn’t that funny! Ya I bet it was … Anyway let’s take one last example just to try out all of our functions. This time we parse more than one argument with the request, just to get the whole picture:

goLarge outputarray(3) {
[0]=>
string(4) “1234”
[1]=>
string(6) “LITTLE”
[2]=>
string(12) “1 SMALL STEP”
}

Well I don’t realy know how to explain this any better, so I guess all the practical stuff ends here.

4. Theory

I’ve chosen to place this section at the end of the article, because it’s just a little extra on how XML-RPC works underneath. And let me just tell you, that I quickly go through this, if you want more detailed information try the XML-RPC Specification[3], which will go more in depth.

4.1 Request

I’ll start by pasting in our own request to the server (the echo request we made in the example above), leaving out the headers:



  echo
  
   
    
     All hail Philip the almighty... Obey!
    
   
  

It’s pretty straight forward, the first thing we do is state that we would like to call a function <methodCall>.
We then tell the server which function we’re calling <methodName>, this is followed by out list of parameters.
A <params> can have any number of <param>, which each holds a <value>. In our case this value is a string (<string>), but it can be any one of XML-RPCs 5 supported data types:

Tag Type Example
<i4> or <int> four-byte signed integer -12
<boolean> 0(false) or 1(true) 1
<string> string hello world
<double> double-precision signed floating point number -12.214
<dateTime.iso8601> date/time 19980717T14:08:55
<base64> base64-encoded binary eW91IGNhbid0IHJlYWQgdGhpcyE=

XML-RPC also supports arrays and structures, but you’ll have to read about them in the XML specs.

4.2 Response

Again I’ve stripped the HTML header from the server response:



  
    
      
        Come again: All hail Philip the almighty... Obey!
      
    
  

Like with the request, this is rather understandable, so I wont add anything to this.
Sometimes an error happens, you might have supplied to many arguments, or you might misspelled a function so the server can’t find it. When this happen the server will return a fault code. I’ve (besides stolen the idea of showing this fault code here from the XML-RPC Specs) chosen to give you an example on a fault code:



  
    
      
        
          faultString
          
            server error. method not found.

echos
          
        
        
          faultCode
          
            -32601
          
        
      
    
  

Again, it’s easy to understand, but this shows the <struct> and how it works.

Conclusion

To be honest I don’t really know what to make of all this, except that it works like a charm. If you compare the XML-RPC protocol to some of the other web service protocols you can find “out there”, you’ll find that the difference is small. Some are a little bit more advanced, some are more compact, others are exactly the same and some are useless.
Finding the right web service, is all about what you like to work with, my personal favorit is XML-RPC (hence this article). So my suggestion is try some of the other big web services, and find the one you’re most comfortable with, and then stick with it!
Honestly I haven’t used XML-RPC since I wrote this article. And if I should make a service available, I would first search through any new alternatives, and find a solution that would fit my problem.

a. sources

[1] http://www.xmlrpc.com
[2] http://dk.php.net/manual/en/function.fsockopen.php
[3] http://www.xmlrpc.com/spec

]]>
http://birk-jensen.dk/2010/09/xml-rpc/feed/ 0
Pic2HTML http://birk-jensen.dk/2010/09/pic2html/ http://birk-jensen.dk/2010/09/pic2html/#respond Thu, 23 Sep 2010 12:04:39 +0000 http://birk-jensen.dk/?p=138 Read more »

]]>
BeeThis is simply a copy of my old pic2html article (2005). I’ve done some minor content editing, mostly spelling but there still might be a few lines that doesn’t make any sense.

1. Introduction

A long long time ago, I was a little trip by http://romanm.ch (no longer the same site), and well I must admit pretty impressing, try to take a look your self, especially the movies are well made.
Anyway, this gave me the idea of making an image to pure html code. My theory was that it would be simple to make a picture look good even with nothing but html (and as you’ll see later this was the truth, it’s possible to make 100% replicas), even though it’ll be size heavy.
Before we get going, remember to enable the GD library[1], for PHP. If you don’t know how, consult the PHP manual. I wont be going into details about the different GD lib functions, so you’ll need to read up on the GD functions you’re not familiar with in the manual as well.

2. rgb2html

First off we need a function to change the RGB color code to HTML color code (or simple from decimal to hexadecimal[2]). Lucky for us PHP is filled with a lot of helper functions, that sometimes turns out to be, well useful. This time it’s the great comeback for the dechex function, which convert a decimal number to hexadecimal. I’ve packed this down in a little function:

 $clrR, 'green' => $clrG, 'blue' => $clrB);
    elseif ($intReturn == 2)
        return $clrR . $clrG . $clrB;
}
?>

In our code, all we need is the function which spits out the color code as a string, but I got carried away and made a little extra (return as an array). And you can like any other of my functions in any of my articles, (ab)use them like a mad man, if that’s you desire, just as long as you don’t say you’ve written then your self. And just for the fun of it, lets try the code.

output#ff9600

And well it seems fine.

3. pic2html

And now this is where all the magic happens. In this function, we’ll be reading a picture pixel by pixel, and printing it out as HTML. I’ve made a couple of considerations about the HTML before I started:
I’ve used the <pre<, this way we save some valuable space, byt not having to use the evil <br /> code. And i’ve chosen to use the <font color=”#[COLOR]”>char</font> instead of the (now a days) “correct” <span>, again to save some Kb. The stylesheet i’ve chosen is the following:

font-size: 1px;
line-height: 1px;

For the less fortunate (this including myself. It took me several tries to find this obvious css syntax), this sheet will give it so that every character fills up 1 single pixel.
Anyway here you have it:

';
    echo '';

    for ($y = 0; $y <= $imgY; $y++) {
        for ($x = 0; $x <= $imgX; $x++) {
            $clrIndx = imagecolorat($img, $x, $y);
            if ($lastIndx != $clrIndx) {
                echo ';';
                $clrRGB = imagecolorsforindex($img, $clrIndx);
                
                echo '';
                $lastIndx = $clrIndx;
            }
            echo $char;
        }
        echo "\n";
    }
    echo "<"."/pre>"; // You don't need to . concatenate the string, but my WP-plugin brakes if I don't.
    return imagedestroy($img);
}
?>

It shouldn’t be that hard to understand, but I’ll run through the code in briefs below:
First of we find the size of the image, so we know how many times to run our loops.
Next we find the very first color. This is done outside our loops, this way we can optimize our code, so if the same color appears 2 times after each other, we will keep the same . This will in pictures with few colors make the size of the file dramatically less.
Now we print the selected character with the right color. Running from the top left corner till the lower right when it’s done.

When you call the pic2html function, remember to do it with an image handle, and not just with a path:


output<pre style=”font-size: 1px; line-height: 1px;”><font color=”#0c0b09″>#</font><fo
nt color=”#0f0e0c”>#</font><font color=”#100f0d”>##</font><font color=”#0f0e0c”> [……….]

4. Conclusion

Actually I must conclude that – for once – everything was as I’ve expected. It’s possible to make a replica of an image, but it’s heavy. Another problem with a large picture is that it doesn’t go all the way through the image, it makes it till one point, and then it just stops. i don’t know if it’s my PHP script timeout, or if it’s my system that lags the resources. But if you notice the beautiful picture below (captured by yours truly, during a massive hangover), you’ll see the script stops:

4.1 Useful?

So far I haven’t found any useful purpose for this. But if anyone can come up with something please do throw a comment and let me know.

– Added –

While converting the article to my new blog, I’ve read through it quickly, changing a few obvious spelling mistakes and altered a couple of lines (and removed a few sentences). But what strike me now is, that we can actually decrease the size of the end HTML, if we used <span> with a class. The class names would be c[ITERATED_NUMBER] and define a color, this way we could reuse a small class name many times instead of replicating a full color=”#000000″ (15 chars) class=”c1″ (10 chars, allowing up to class=”c999999″ different colors, that could be reused.
Anyway I still really can’t seem to figure out where this could be used, if you got an idea please do tell…

a. sources

[1] http://www.php.net/manual/en/ref.image.php
[2] http://en.wikipedia.org/wiki/Numeral_system

]]>
http://birk-jensen.dk/2010/09/pic2html/feed/ 0
Benchmark class, what do I need? http://birk-jensen.dk/2010/09/benchmark-class-what-do-i-need/ http://birk-jensen.dk/2010/09/benchmark-class-what-do-i-need/#respond Mon, 20 Sep 2010 09:35:58 +0000 http://birk-jensen.dk/?p=114 Read more »

]]>
Although micro-optimizing don’t give the biggest performance improvement, I often find my self wondering if using function X() instead of Y() is faster, and if my own function Z() is better. Most of the time I end up writing a small tiny benchmark test on the two or three functions, which then gives me a quick overview of the functions speed.
So I’ve decided to make a small and simple to use micro-benchmarking class.

Goal

Basically this class is all about being easy to use, so you don’t have to spend a long time setting up a test.

  • Easy to set up. The class should be used for those small tests, where you’re in doubt of which piece of code is fastest. And if one is to test a piece of code, for a tiny performance increase (maybe more out of curiosity than an actual application improvement), it should only take a couple of minutes to set the test up. If it takes 15 minutes to create a test every time, you wont take the time to write the test if you’re in the middle of something else.
  • Readable output. For the same reasons it should be easy to set up, the output needs to be readable when the test is done, without any post-test-processing. It would be good if the output could be chosen, so you could either get the easy to read, or a more in-depth detailed result (maybe formatted for post-processing in another environment).

Nice to have

Again with the intentions of making this easier to work with, it would be great to have a feature, where you would just write the piece of code you wanted to test, and then have the class handle the rest. I’ve been brainstorming a few ways to do this.

  • Functions. Assign a function, the class can call when doing the test. Perhaps it should be possible to assign a set of functions, so you had an init, bench and close function. This would make the testing process easy, write the functions, and then get the result, and even though calling a function will have an impact it should be the same for every test case.
  • Eval the code. This crossed my mind, but I think it’s generally bad practice to use the eval function if you can avoid it. And the code written has to be a string, which will mess up the syntax highlighting. And I don’t really know the overhead of using eval.
  • External files. I could make the class read an external file, which is setup in a way the class would understand. Although this would just be separating the tests in different files, it could have some advantages when doing larger tests. And that is the problem with this solution, I don’t want to do larger tests with this class.

Another thing that would be nice to have, would be an external interface. Mainly a tiny app that could read the output from the class (XML perhaps). Have the class automatically send the output to the app, which then stores it and gives you a quick overview of previous tests as well.
But these are all just nice to have, so far I’ll aim for the goal when I get some free time.

]]>
http://birk-jensen.dk/2010/09/benchmark-class-what-do-i-need/feed/ 0