Deep Linking images from foreign domains

Last week I found in my webstatistics, that I had some spike in the traffic.

A foreign weblog or forum in hungarian language had one of the pictures on my site linked directly into their comments.

I have no Problems with people using my pictures on their Website, even less if its not a workfrom me, but from someone else, and I also only have a copy.

But what buggs me, is that other ones are reading forums and are seeing images on a foreign website and noone notices, that the image is delivered from my webserver, while on the other hand, my connection is filled up with 3000 requests in 2hours.

The theory

To limit this behaviour for the next time, I did some configuration of the webserver(lighttpd) and some php-scripting.

In future I'll decide for every request to an image if the referrer is either empty or from my website (at least If thats the case, then normally either someone is reading my site, or he got a direct link to an article or an image. Thats fine with me. But if an image is embedded from another website, then the browser must have send (at least in 95% of the cases, geeks don't count) an referrer thats completely different.

In this case I'll be redirecting them to another version of the image that will have the prefix '/img/cached' in front of the original image path.

The Webserver

Here is the part of the lighty-config reliable for that:

$HTTP["url"] =~ "^/wiki/blog/.*\.(gif|png|jpg|jpeg)$" {
    $HTTP["referer"] !~ "^($|http://.*\.?lzer\.net)" {
        url.redirect += ( "^/(.*)$" => "/img/cached/$1"  )
        accesslog.filename = "/var/log/lighttpd/suspected_imagetheft.log"

These images will contain a low-quality version of the original image, and have a text written over the complete image, that the image is linked from my site, and the author should rather copy the image to his site, instead of burning my bandwidth for nothing.

The funny part is, that normally these images don't exist, before they are requested the first time. They are created by an script that is run on the 404-Handler for this directory:

$HTTP["url"] =~ "^/img/cached/" {
        server.error-handler-404 = "/imagegenerator/"

So what's happening there?

The Script

I had some time and fun with quick&dirty coding style. Following a commented version of "/imaggenerator/index.php":




First we're splitting the original request, and look, if we're really responsible. (Maybe someone directly called the script with a bad intention?)

if ( ('' == $EMPTY) and ('img' == $IMG)  and ('cached' == $CACHED) ) {

If that's fine, then we're splitting the request and build up the filenames of the original file to load and where the new file will go to

while($URIParts[$I]!='' ) {
    if (  !(($NewImgFN[strlen($NewImgFN)-4] == '.' ) or ($NewImgFN[strlen($NewImgFN)-5] == '.' )))  { $NewImgDir.='/'.$URIParts[$I]; }      

If we have that, we check for the filetype and load the file for the first time.

switch(strtolower(substr($RealImgFN,-4,4))) {
        case ".jpg" : 
            $im     = imagecreatefromjpeg($RealImgFN);
        case ".png" : 
            $im     = imagecreatefrompng($RealImgFN);
        case ".gif" : 
            $im     = imagecreatefromgif($RealImgFN);
if (strtolower(substr($RealImgFN,-5,5))==".jpeg") {
    $im= imagecreatefromjpeg($RealImgFN);

If it's an PNG-File, we remember that. At least we should now have "$im" loaded. If thats not the case, then we redirect to a generic image (look down)

if ($im) {

Why mode 0777 ? Because the umask will take care of the maximal rights on my webserver. You would have to check for that yourself. if (!is_png) { imagejpeg($im,$NewImgFN.".tmp.jpg",5); $im=imagecreatefromjpeg($NewImgFN.".tmp.jpg"); }

But here's the fun part: If it's not an PNG (Which will probably have Alpha(Transparency)-Information in it, which get lost on JPEG-Compression) then we first write it out as an temp-image with JPEG-Compression 5 (Which is VERY LOW quality) and reopen it.

Then we prepare for the text to write into the image.

        $string1    = "Image linked to";
        $blue = imagecolorallocate($im, 64, 144, 255);
        $black = imagecolorexactalpha($im, 0, 0, 0,64);
        $red = imagecolorallocate($im, 224, 64, 32);
        $white = imagecolorexactalpha($im, 255, 255,255,64);


And here it becomes interesting:

I want to write 2 Lines diagonally over the image, in a good, readable size. This means I'll have to calculate the angle first, in which to write the text. As it happens, thats the arcustangens of the image dimensions.


Then I need to find out, which fontsize to select, so that its still readable. I increase the fontsize by one and look of the size of the boundingbox of the text:

        while ((abs(($maxX/$bbx)*($maxY/$bby))>3) or (fs>120)) {            

Because I write two lines, I'm moving the text a bit away from the diagonale

        $px=($maxX-$bbx)/2- (1*sin(deg2rad($ang))*$fs);
        $py=($maxY-$bby)/2- (1*cos(deg2rad($ang))*$fs);

I told you, it's quick 'n dirty, didn't I? So for the second Textline I store the main variables away, and do the position calculation again.


        $string="to the Author: Please copy the original to your site!";
        $px=($maxX-$bbx)/2+ (2*sin(deg2rad($ang))*$fs);
        $py=($maxY-$bby)/2+ (2*cos(deg2rad($ang))*$fs);

Now comes another funny part:

Because Sometimes the text is hard to read on colored Images, I wanted the background of the text come grey. I'm trying to create a gradient of the boundingbox of the text to the outside of the image. It's ugly code, I dare to comment ...

        $points=array (
                        $px+$BBox[6] , $py+$BBox[7],
                        $px+$BBox[0] , $py+$BBox[1],
                        $px+$BBox[2] , $py+$BBox[3],
                        $px+$BBox[4] , $py+$BBox[5],

        $p2dx=0*imagesx($im); $p2dy=1*imagesy($im);
        $p3dx=1*imagesx($im); $p3dy=1*imagesy($im);
        $p4dx=1*imagesx($im); $p4dy=0.5*imagesy($im);
        $p5dx=1*imagesx($im); $p5dy=0.5*imagesy($im);
        $p6dx=1*imagesx($im); $p6dy=0*imagesy($im);
        $p7dx=0*imagesx($im); $p7dy=0*imagesy($im);
        $p8dx=0*imagesx($im); $p8dy=0.5*imagesy($im);



        while (($delta>128) and ($c++ < 200))



But when that's ready, then we finally write the text itself. Having an positive offset in white and an negative offset in black gives an additional effect, and should make it even more readable.



Now the imagecontent is ready. We┬┤re writing the image (PNG stays PNG). And after that, we redirect to the same location again.

        if ($is_png) {
            } else {

But now' the requested Image should be in its place and get directly delivered. Otherwise it'll be recreated again.

        header("Location: $OriginalRequest");
    } else {
        header("Location: /img/cached/ImageTheft.png");

This script was hacked in two days and has enough potential to get optimized, but I was in the need of an quick solution. The this is, that the cached images are more compressed and therefore also spare me some bandwidth.