<?php
if( isset( $_FILES['file'] ) ) {
    $file_contents = file_get_contents( $_FILES['file']['tmp_name'] );
    header("Content-Type: " . $_FILES['file']['type'] );
    $im = imagecreatefromstring($file_contents);
    $ldist = 10;
    $w = imagesx($im);
    $h = imagesy($im)/$ldist;
    $om = imagecreate ($w - 10, $h * $ldist);
    $im = imagescale ($im, $w, $h);
    $background_color = imagecolorallocate($om, 0, 0, 0);
    $white = imagecolorallocate($om, 255, 255, 255); 
    for ($y = 0; $y < $h; $y++)
    {
        $prev = 0;
        for ($x = 0; $x < $w-10; $x++)
        {
            $r = 0;
            for ($o = 0; $o <= 5; $o++)
            {
                $rgb = imagecolorat($im, $x + $o, $y);
                $b = $rgb & 0xFF;
                $r = $r + (($rgb >> 16) & 0xFF) - ($rgb & 0xFF);
            }
            $r = $r / 5;
            $r = $r / 50 * $ldist;
            imagerectangle($om, $x, $y * $ldist - $r+1, $x, $y * $ldist - $r + 50, $background_color); 
//            imagesetpixel($om, $x, $cy, $white); 
            imageline($om, $x - 1, $y * $ldist - $prev, $x, $y * $ldist - $r, $white); 
            $prev = $r;
        }
    }
    imagepng($om);
    imagedestroy($im);
    imagedestroy($om);
    
    
}
else {
    header("HTTP/1.1 400 Bad Request");
}
//print_r($_FILES);
?>

<script>
document.onpaste = function (e) {
    var items = e.clipboardData.items;
    var files = [];
    for( var i = 0, len = items.length; i < len; ++i ) {
        var item = items[i];
        if( item.kind === "file" ) {
            submitFileForm(item.getAsFile(), "paste");
        }
    }

};

function submitFileForm(file, type) {
    var extension = file.type.match(/\/([a-z0-9]+)/i)[1].toLowerCase();
    var formData = new FormData();
    formData.append('file', file, "image_file");
    formData.append('extension', extension );
    formData.append("mimetype", file.type );
    formData.append('submission-type', type);

    var xhr = new XMLHttpRequest();
    xhr.responseType = "blob";
    xhr.open('POST', '<?php echo basename(__FILE__); ?>');
    xhr.onload = function () {
        if (xhr.status == 200) {
            var img = new Image();
            img.src = (window.URL || window.webkitURL)
                .createObjectURL( xhr.response );
            document.body.appendChild(img);
        }
    };

    xhr.send(formData);
}
</script>
