Data URL-s

March 19, 2007

I had known about this before, but never really tried them until yesterday. I needed a really quick way to post photos from my phone, so decided to write a little photogallery app. You just dump pictures off the phone to a certain directory and that’s it. In the process of reading about imagecopyresized, I stumbled on this method of embedding images:

<img src='data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD' alt='Picture' />

That’s called a data URL and they were first introduced in 1998.

In PHP, I couldn’t find a way to read the data directly with imagejpeg(), so I end up overwriting 1 thumbnail for a whole directory of images. Working with images, the PHP memory limitations will quickly come into play. Anyways, here’s the whole PHP code that goes through a directory and creates 80x80 px thumnails of a random portion of the picture. You can also see it in action. The source for that script is here.

$id = 'data/';

$dh = opendir($id);

while ($f = readdir($dh))


  $fp = $id . $f;

  if (is_file($fp) && $f != 'tmp')


    list($w, $h) = getimagesize($fp);

    $scale = 0.6;

    $ns = 80;

    $im = imagecreatetruecolor($ns, $ns);

    imagecopyresized($im, imagecreatefromjpeg($fp), 0, 0,

      rand(0, $w*$scale), rand(0, $h*$scale), $w*$scale, $h*$scale, $w, $h);

    imagejpeg($im, 'data/tmp');

    echo "

<a href='javascript:show(\"$fp\",$w,$h)' title='" . date('r', filectime($fp)) . "'>

   <img src='data:image/jpg;base64," . base64_encode(file_get_contents('data/tmp')) . "' />