Serving an image programatically I want to serve an image programatically and execute custom code, something usal and simple in plain php.

&lt;img src='test.php?image=1234.jpeg' /&gt;


Then you just serve the image in "test.php" and execute your custom code.

However I have not idea how to achieve this in Drupal.

The code should be in a module of course, but, how to I create a path equivalent the one above, that execute that custom code in my module?

Another solution could be to trigger a rule each time an image is download but that is too heavy. Even another could be something like URL alias to a content, and on display rewrite the output of that content? Is this possible?
You should be using hook_menu() to create a custom page from code. The hook_menu() allows to define a URL and page callback which will be called when user hit the url. Check the example below:

/**
  * Implements hook_menu().
  */
function [MODULE_NAME]_menu() {
  $items['MODULE_CALLBACK'] = array(
    'title' =&gt; 'My Custom URL',
    'page callback' =&gt; '_MODULE_NAME_page_callback',
    'access arguments' =&gt; array('access content'),
  );

  return $items;
}

function _MODULE_NAME_page_callback() {
  $image_name = (!empty($_GET['image']) ? $_GET['image'] : '');

  // Write code here.
  $data = $image_name;

  return $data;
}


The _MODULE_NAME_page_callback() callback will be called when user hit the URL as sitename.com/MODULE_CALLBACK?image=imagename.jpg.