Animated sparkling sunset in Skanör
by Klas Lundberg on Jul.27, 2010, under Graphics and effects, Portfolio
I got a bit inspired by my previous Sparkling sunset made with Photoshop and wanted to make a proof of concept for Adobe Flash. So I animated the sunset. This is what you can do with Flash without using much code. I have just used a few lines to randomize starting points. All other graphic effects are built into Flash and needs no coding.
Wouldn’t it be cool if sunsets like these existed?
Sparkling Sunset in Skanör
by Klas Lundberg on Jun.14, 2010, under Portfolio
I found some amazing colorful wallpapers in a theme pack for Windows 7 called Surreal Territory by Chuck Anderson of NoPattern. He has really done a lot of great colorful designs! I got a bit inspired to make something similar. So I took one of my photos from Skanör last weekend and made a truly colorful sparkling sunset! Feel free to download it as a wallpaper or something. =)
Mailing function for PHP with UTF-8, HTML and attachments
by Klas Lundberg on Jun.13, 2010, under Check this out
I found a function a couple a years ago which I’ve been using for mailing in my projects. The function was rather basic from the start and then I’ve added functionality as needed. Nowadays it is changed into only having UTF8 support (since I almost always use UTF8 encoding) and also support for HTML. the HTML encoding is detected automatically if the <html> tag is present in the text. You can attach images and files by adding them into an array. Feel free to use it however you like.
To get UTF-8 to work correctly in your PHP pages, see my post about Setting up PHP for UTF8 and XHTML compatibility.
The nice mailman image is from The Invisible Agent.
//////////////////////////////////////////// // Function: send_mail() // UTF-8 Mail sending with html and attachments //////////////////////////////////////////// /** Sends a mail. * * @code { # To Email Address $to_address = "to@address.com"; # From Email Address $from_address = "from@address.com"; # From Name $from_name = "Send Mail"; # Message Subject $email_subject = "This is a test mail with some attachments"; # Use relative paths to the attachments $attachments = Array( Array("file"=>"../../test.doc", "content_type"=>"application/msword"), Array("file"=>"../../123.pdf", "content_type"=>"application/pdf") ); # Message Body $email_body = "<html><head></head><body>This is a message with <b>".count($attachments)."</b> attachments and maybe some <i>HTML</i>!</body></html>"; send_mail($to_address, $from_address, $from_name, $email_subject, $email_body, $attachments); } */ function send_mail($to_address, $from_address, $from_name, $email_subject, $email_body, $attachments=false) { $eol="\r\n"; $mime_boundary = md5(time()); $headers = ''; $msg = ''; $html = (mb_strpos($email_body, "<html>") !== false); $mail_site = "send_mail@" .$_SERVER['SERVER_NAME']; # Common Headers $headers .= 'Sender: ' . $mail_site . $eol; $headers .= 'From: ' . mb_encode_mimeheader($from_name) . " <" . $mail_site . ">" . $eol; $headers .= 'Reply-To: ' . mb_encode_mimeheader($from_name) . " <$from_address>" . $eol; $headers .= 'Return-Path: ' . mb_encode_mimeheader($from_name) . " <$from_address>" . $eol; // these two to set reply address $headers .= "Message-ID: <".time().$mime_boundary."@".$_SERVER['SERVER_NAME'].">".$eol; $headers .= "X-Mailer: PHP v" . phpversion() . $eol; // These two to help avoid spam-filters # Boundry for marking the split & Multitype Headers $headers .= 'MIME-Version: 1.0' . $eol; if ($attachments !== false) { $headers .= "Content-Type: multipart/mixed; boundary=\"1$mime_boundary\"" . $eol; $msg .= "--1".$mime_boundary.$eol; if($html) { $msg .= "Content-Type: multipart/alternative; boundary=\"2$mime_boundary\"" . $eol.$eol; } } else { if($html) { $headers .= "Content-Type: multipart/alternative; boundary=\"2$mime_boundary\"" . $eol; } } # Setup for text OR html # Text Version if($html) { $msg .= "--2".$mime_boundary.$eol; $msg .= "Content-Type: text/plain; charset=UTF-8".$eol; $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol; } else { $headers .= "Content-Type: text/plain; charset=UTF-8".$eol; $headers .= "Content-Transfer-Encoding: 8bit"; } $msg .= strip_tags(str_replace("<br>", $eol, str_replace("<br />", $eol, $email_body))).$eol.$eol; if($html) { # HTML Version $msg .= "--2".$mime_boundary.$eol; $msg .= "Content-Type: text/html; charset=UTF-8".$eol; $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol; $msg .= $email_body.$eol.$eol; # Finished $msg .= "--2".$mime_boundary."--".$eol.$eol; // finish with two eol's for better security. see Injection. } if ($attachments !== false) { for($i=0; $i < count($attachments); $i++) { if (is_file($attachments[$i]["file"])) { # File for Attachment $file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1)); $handle=fopen($attachments[$i]["file"], 'rb'); $f_contents=fread($handle, filesize($attachments[$i]["file"])); $f_contents=chunk_split(base64_encode($f_contents)); //Encode The Data For Transition using base64_encode(); fclose($handle); # Attachment $msg .= "--1".$mime_boundary.$eol; $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol; $msg .= "Content-Transfer-Encoding: base64".$eol; $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !! $msg .= $f_contents.$eol.$eol; } } $msg .= "--1".$mime_boundary."--".$eol.$eol; // finish with two eol's for better security. see Injection. } # SEND THE EMAIL ini_set('sendmail_from',$from_address); // the INI lines are to force the From Address to be used ! mail($to_address, mb_encode_mimeheader($email_subject), $msg, $headers); ini_restore('sendmail_from'); }
Setting up PHP for UTF8 and XHTML compatibility
by Klas Lundberg on Jun.13, 2010, under Check this out
PHP is usually not configured for working well with UTF8 multilingual support and XHTML from start. To get it working correctly, you need to adjust a few settings.
UTF-8
There are two things to think about. First, make sure your php files are saved using UTF8 encoding. Even notepad can achieve this in the file save dialog. Then you have to set the php.ini settings to UTF8. This can be done with the ini_set() function. The ini_set() have to be called before outputting any text or HTML/XHTML in the document.
// UTF8 settings ini_set('mbstring.language', 'Neutral'); ini_set('mbstring.internal_encoding', 'UTF-8'); ini_set('mbstring.http_input', 'UTF-8'); ini_set('mbstring.http_output', 'UTF-8'); ini_set('mbstring.encoding_translation', 'On'); ini_set('mbstring.detect_order', 'auto'); ini_set('mbstring.substitute_character', 'long');
Normally, the server sets the content type correctly if the file is coded in UTF8, but sometimes you need to force the content-type to have UTF8 charset. The header() function also have to be called before outputting any text or HTML/XHTML in the document.
// Set XHTML content type and character encoding of the document // You may also use text/html as mime type instead of application/xhtml+xml header('Content-Type: application/xhtml+xml; charset=utf-8');
Sometimes you may have problems with getting data from MySQL encoded correctly as UTF8. Most of the time this isn’t a problem, but you can also force some UTF8 settings on the MySQL server. Use the mysql_set_charset if you have PHP version 5.2 or higher and SET NAMES/SET CHARACTER SET if you have an older version of PHP.
$conn = mysql_connect('localhost', 'user', 'password'); // PHP 5.2 and above mysql_set_charset('utf8',$conn); // PHP below v 5.2 mysql_query("SET NAMES utf8"); mysql_query("SET CHARACTER SET utf8");
At last, do not forget to add the Content-Type <meta> tag in the <head> section of your HTML/XHTML. Otherwise the web browsers will display your page incorrectly anyway.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />XHTML
To get correct XHTML compatibility you need to adjust the session settings of PHP so that sessions is integrated the right way into your code. The server is often configured to insert session id:s into url:s on your PHP page.
// XHTML compatibility ini_set('arg_separator.output', '&'); ini_set('url_rewriter.tags', 'a=href,area=href,frame=src,input=src,form=action,fieldset=');
For security reasons, I recommend you to disable the url rewriting, since it makes it possible to hijack another user’s session under certain circumstances. This makes the previous XHTML settings unnecessary, but keep them if you intend to use sessions by URL.
// Disable session by URL ini_set('session.use_only_cookies', '1');
Still having problems?
To see your PHP version and how the settings are affected, simply call php_info() after changing the settings. Master value is the original server setting and Local value is the value after changing it using ini_set().
php_info();
These UTF8 settings works most of the time, but many servers may have other configuration issues. If you still have issues with UTF8 check the php_info() output for any settings set to ISO-8859-1 and change them to UTF-8 using the ini_set() function. If you still have problems, check that your document files really are saved using correct UTF-8 character encoding.
My music project: Klassy
by Klas Lundberg on May.17, 2010, under Check this out, Portfolio
I’ve been busy producing music lately. I got my music computer up and running again after about a month of deadness. Just then I saw a remix competition for the Lundakarnevalen, which is a carnival for students in Lund every fourth year. I’m not really a student anymore (well technically I am), but my heart still beats a little for Lund, especially beacause I participated in the last two carnivals in 2002 and 2006.
So I decided to join the competition for remixing the official song of Lundakarnevalen – Karnevalsmelodin 2010. About two weeks later I actually managed to finish my remixing and I actually produced two remixes.
The theme of the carnival this time is Right & Wrong and I got inspired by the Karnevalsmelodin LIP UN-DUB video. So I made a right and a wrong mix. The other mix is actually the same as the first but with the beat in mixed order; instead of 1-2-3-4 it’s 1-3-2-4. This gives the other mix a whole different sound, which I almost like even more than my first mix. Naturally, the song gets totally screwed up, but that was my intention anyway. The cool thing is that if you mix the beat the same way once more, you get the original mix back! =)
You can check out my very basic music project page which will be extended further during my progress. You can also listen to my two first remixes below. Judge yourself which one is right and which is wrong. =)
Using the fast asynchronous Alchemy JPEG encoder in Flash
by Klas Lundberg on Apr.14, 2010, under Graphics and effects
If you want to encode JPEG images in AS3 there are a number of encoders to use and obviously there is one that is better than all the rest. Mateusz Małczak has made an excellent JPEG encoder based on the libjpeg C-library compiled into Actionscript using Adobe Alchemy. It not only produces small JPEGs with high quality really fast, but it’s also asyncronous meaning that it doesn’t lock up your application while encoding, like many of the other encoders do. This way you can also monitor the progress of the encoding process while encoding. The disadvantage is that you need an extra click from the user to save the file when the process is complete. This is due to limitations in the security model in the Flash Player, which only allow file saving exactly when you make a click, which doesn’t work with asynchronous scripts. However, this isn’t a big problem if you make a logic design.
Step 1
Start by making a new Flash File (Actionscript 3.0) and save it in a folder of your choice.
Step 2
Download the jpegencoder.swc from segfaultlabs. Just click on the jpegencoder.swc in the folder /libs/. Save the file to the folder where you have your .fla file.
Step 3
Open the publish settings in flash and select the flash tab.
To get the SWC library working when you publish your swf you need to do a little magic trick, otherwise you will get the error ReferenceError: Error #1065: Variable MainTimeline is not defined when publishing or testing the SWF. To deal with this error we need to include the required things to use SWC libraries in the SWF.

Check the Export SWC checkbox in the publish settings.
Note: this setting will also produce another SWC file with the same name as your SWF when publishing. This file is not needed when distributing the SWF to the web or similar and can be deleted.
Step 4
Click on Actionscript settings.

Go to the Library path section. Click on Browse to SWC file and locate the jpegencoder.swc and include it.

Click OK to save your library settings.
Voilà! Now you are ready to use the Alchemy JPEG Encoder in your code!
Initializing the library
To initialize the Alchemy JPEG library use the following lines in your actionscript:
import cmodule.jpegencoder.CLibInit; /// init alchemy object var jpeginit:CLibInit = new CLibInit(); // get library var jpeglib:Object = jpeginit.init(); // initialize library exported class to an object
Starting the encoder
To use the encoder simply call the jpeglib.encodeAsync function and use it with a ByteArray. There is also a non-asyncronous function you can use which is a little bit faster. Even if its faster I recommend using the asynchronous function, since it doesn’t lock up your application while encoding.
// Refer to your own BitmapData object var imgBitmap:BitmapData = someBitmapDataYouHaveAlreadyCreated; // Prepare Alchemy objects var imgData:ByteArray = imgBitmap.getPixels(imgBitmap.rect);; var imgEncoded:ByteArray = new ByteArray(); imgData.position = 0; // Function called when completed var encodeComplete:Function = function() { trace("Encoding complete"); }; // Start JPEG encoder trace("Start encoding"); var jpegQuality:Number = 80; jpeglib.encodeAsync(encodeComplete, imgData, imgEncoded, imgBitmap.width, imgBitmap.height, jpegQuality);
Monitor progress
To see the progress of the encoding you need to set up a function that monitors the position of the ByteArray reader in the encoder. This is done by simply using a setInterval function during the encoding. Don’t forget to clear the interval when the encoding is complete.
// Encoding progress monitor function var encodeProgress:Function = function() { // Listen to the position of the data reader trace("Encoding progress: " + Math.round(imgData.position/imgData.length*100) + "%"); }; // Start monitoring the progress of the encoding var progressMonitor:Number = setInterval(encodeProgress, 20); // Encoding progress complete function var encodeComplete:Function = function() { trace("Encoding complete"); // Stop monitoring the progress clearInterval(progressMonitor); };
Full example
Here is a full example of encoding some graphics into a JPEG while monitoring the progress and then saving it onto the user’s hard drive.
Animated Graffiti
by Klas Lundberg on Apr.08, 2010, under Portfolio
In a school project I had now, we were supposed to make a simple animated link button with a sound using Flash (really not very difficult). Well, I felt like doing some graffiti to get some bonus out of it. The drawing functions in Flash are actually pretty good for fast graffiti production.
Trends 2010: It’s all about color baby
by Klas Lundberg on Apr.01, 2010, under Trends
Color is maybe the strongest trend of this year. Strong, vivid colors is the thing to look for and be inspired by. Just try to look beyond the basic colors and look for those who are not obvious. Well, the obvious will work great too, but my point is that there are a lot of colors and color combinations that we don’t think about right away. And yeah, you have to combine them with strong contrast in any way you can think of. If you need a tool for it, Adobe Kuler is the way to go.
Here are a couple of sources for inspiration:

Size Matters Poster by The Steve Angello Team
You can also try my Channel Colorizer to put some color into your own images.
Using Adobe Kuler via AS3 in Flash
by Klas Lundberg on Apr.01, 2010, under Graphics and effects
A great source for inspiration and making your own color themes is Adobe Kuler. It’s a free service and features all the common color picking techniques. They also have an API available for non-commercial use. It’s perfect for use with flash and its really simple to use thanks to the ColorMunch AS3 class by Ben Kanizay. I used it for color picking in my ChannelColorizer.
Here is a basic example for making a search for “banana”-themes from Kuler in Actionscript 3. To use it you need the ColorMunch class an your own Kuler API key. There are some more examples in the ColorMunch wiki, but you’ll find the most useful information in the documentation provided in the ColorMunch zip-package.
- Register for a Kuler API key
- Download the ColorMunch class and extract it to your fla-folder.
Example of using Adobe Kuler in Flash AS3 via the ColorMunch class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | import beekay.colormunch.*; // creates a new ColorMunch instance with your Kuler API key var colormunch:ColorMunch = new ColorMunch("INSERT_YOUR_KULER_API_KEY_HERE"); // At a minimum listen for the 'resultReady' event // This will fire when the result has been recieved and processed colormunch.addEventListener(ColorMunchEvent.RESULT_READY, onResultReady); colormunch.addEventListener(ColorMunchEvent.ERROR, onResultError); function onResultReady(event:ColorMunchEvent) { trace("Kuler recieved"); var theme:Theme = colormunch.getRandomTheme(); var themeSprite:Sprite = theme.getThemeSprite(); themeSprite.width = stage.stageWidth; themeSprite.height = stage.stageHeight; // Put the theme sprite on the stage addChild(themeSprite); // Get information about the selected theme trace("Loading theme: " + theme.getThemeTitle()); // access swatch information through the theme object var swatch:Swatch; var col:uint; var cR:uint; var cG:uint; var cB:uint; for (var i:int = 0; i < theme.getSwatchCount(); i++) { // get the color swatch= theme.getSwatchByIndex(i); col = swatch.getHex(); // Split the color into RGB cR = (col >> 16) & 0xFF; cG = (col >> 8) & 0xFF; cB = col & 0xFF; trace("RGB:", cR, cG, cB); } } function onResultError(event:ColorMunchEvent) { trace("Kuler error: " + event.data); } // Everything prepared, now search for 10 "banana" themes starting at 0 colormunch.searchThemes(ColorMunch.FILTER_NONE, "banana", 0, 10); |
I found some amazing colorful wallpapers in a theme pack for Windows 7 called 







