Advertisement
HaLo2FrEeEk

Proper API Image Generation

Dec 13th, 2010
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.52 KB | None | 0 0
  1. <?php
  2. //
  3. // The first thing I did was clean up your code structure.  You had a lot of unnecessary spaces and newlines
  4. // Right now, code readability is key!
  5. //
  6. function fetchInfo($playerGamertag) {
  7.   $key = "********************************************";
  8.   $basic = file_get_contents("http://www.bungie.net/api/reach/reachapijson.svc/player/details/nostats/" . $key . "/" . rawurlencode($playerGamertag));
  9.   $map = file_get_contents("http://www.bungie.net/api/reach/reachapijson.svc/player/details/bymap/" . $key . "/" . rawurlencode($playerGamertag));
  10.   $json = json_decode($basic, 1);
  11.   $json_map = json_decode($map, 1); // There was no reason that this needed to be an object while the other was an array.
  12.   unset($basic, $map, $key);
  13.  
  14.   $emblem = $json['Player']['ReachEmblem'];
  15.   $colors = $emblem['change_colors'];
  16.   $emblemUrl = sprintf("http://www.bungie.net/Stats/emblem.ashx?s=70&0=%s&1=%s&2=%s&3=%s&fi=%s&bi=%s&fl=%s&m=3",
  17.                    $colors[0],
  18.                        $colors[1],
  19.                        $colors[2],
  20.                        $colors[3],
  21.                        $emblem['foreground_index'],
  22.                        $emblem['background_index'],
  23.                        ($emblem['flags'] + 1));
  24.    
  25.   foreach($json_map['StatisticsByMap'] as $stats) { // Updated to use the array instead of the object.
  26.     if($stats['MapId'] == "-1") {
  27.       if($stats['VariantClass'] == "1" || $stats['VariantClass'] == "2" || $stats['VariantClass'] == "3") {
  28.         $totalkills += $stats['total_kills'];         //
  29.         $totaldeaths += $stats['total_deaths'];       //
  30.         $totalbetrayals += $stats['total_betrayals']; // $variable = $variable + $newvariable is the same thing as $variable += $newvariable, so I changed that.
  31.         $totalassists += $stats['total_assists'];     //
  32.         $mvp += $stats['total_first_place'];          //
  33.         }
  34.       }
  35.     }
  36.  
  37.   $cache[] = time();
  38.   $cache[] = $json['Player']['gamertag'];
  39.   $cache[] = $json['Player']['service_tag'];
  40.   $cache[] = $json['Player']['games_total'];
  41.   $cache[] = $json['Player']['CampaignProgressSp'];
  42.   $cache[] = $json['CurrentRankIndex'];
  43.   $cache[] = $totalkills;
  44.   $cache[] = $totaldeaths;
  45.   $cache[] = $totalbetrayals;
  46.   $cache[] = $totalassists;
  47.   $cache[] = $mvp;
  48.   $cache[] = $emblemUrl;
  49.  
  50.   return $cache;
  51.   }
  52.  
  53. function generateImage($cache) {
  54.   $sig = imagecreatefrompng("images/sig_glass.png");
  55.   $getEmblem = file_get_contents($cache[11]);
  56.   $sig_emblem = imagecreatefromstring($getEmblem);
  57.   $sig_solo = imagecreatefrompng("images/solo/" . $cache[4] . ".png");
  58.   $sig_rank = imagecreatefrompng("images/ranks/" . $cache[5] . ".png");
  59.   $text_color = imagecolorallocate($sig, 255, 255, 255);
  60.    
  61.   imagesavealpha($sig, true); // sig_glass.png doesn't have alpha, but I'll leave this in case you update the template sometime.
  62.   imagesavealpha($sig_solo, true);
  63.   imagesavealpha($sig_rank, true);
  64.  
  65.   imagettftext($sig, 17, 0, 100, 26, $text_color, 'Utsaah.ttf', $cache[1]." - ".$cache[2]);                    //
  66.   imagettftext($sig, 13, 0, 105, 47, $text_color, 'Utsaah.ttf', "Games Played: ".$cache[3]);                   //
  67.   imagettftext($sig, 13, 0, 105, 85, $text_color, 'Utsaah.ttf', "Total Assists: ".$cache[9]);                  //
  68.   imagettftext($sig, 13, 0, 280, 47, $text_color, 'Utsaah.ttf', "Total betrayals: ".$cache[8]);                // There's no need to put parentheses around strings containing variables, just do it like I did here
  69.   imagettftext($sig, 13, 0, 105, 67, $text_color, 'Utsaah.ttf', "MVP ".$cache[10]." Time".(($cache[10] == 1) ? "" : "s")); //
  70.   imagettftext($sig, 13, 0, 280, 67, $text_color, 'Utsaah.ttf', "Total Kills: ".$cache[6]);                    //
  71.   imagettftext($sig, 13, 0, 280, 85, $text_color, 'Utsaah.ttf', "Total Deaths: ".$cache[7]);                   //
  72.  
  73.   imagecopyresampled($sig, $sig_emblem, 13, 12, 0, 0, 70, 70, imagesx($sig_emblem), imagesy($sig_emblem)); // I replaced imagecopyresized() with imagecopyresampled(), which retains a lot more quality when shrinking images
  74.   imagecopyresampled($sig, $sig_rank, 517, 39, 0, 0, 30, 30, imagesx($sig_rank), imagesy($sig_rank));      // I also added the imagesx() and imagesy() functions, which get the width and height of a supplied image resource.
  75.   imagecopyresampled($sig, $sig_solo, 429, 38, 0, 0, 30, 30, imagesx($sig_solo), imagesy($sig_solo));      // This makes it so that the whole source image is copied (and sized, if necessary), not just a portion of it.
  76.  
  77.   header("Content-type: image/png");
  78.   imagepng($sig); // I told you, calling imagepng() without the string filename parameter causes it to output to the browser.
  79.   imagedestroy($sig);
  80.   }
  81.  
  82. $playerGamertag = @$_REQUEST['gamertag']; // This sets the gamertag from the POST array
  83. if(!$playerGamertag) { // This checks that a gamertag was passed
  84.   die("No gamertag supplied"); // If not, kill the script.
  85.   } else if(strlen($playerGamertag) > 15) { // This checks that the gamertag is less than 15 characters long
  86.   die("Invalid gamertag"); // If it is, kill the script.
  87.   }
  88.  
  89. // A gamertag was passed that is considered "valid", so we continue.
  90.  
  91. $hash = md5($playerGamertag);           //
  92. $cachefile = "cache/" . $hash . ".txt"; // You had these variables copied all over the place, for some reason.  You only need them once.
  93.  
  94. if(file_exists($cachefile)) {
  95.   $file = file_get_contents($cachefile);
  96.   $cache = explode("#|#", $file);
  97.   unset($file);
  98.   $timeDiff = time() - $cache[0];
  99.   if($timeDiff > 3600) { // Timestamps are in seconds.  300 seconds is 5 minutes, that was just a demonstration from my script, you should use 1 hour, or 3600 seconds
  100.     // The cache file is older than 1 hour
  101.     $cache = fetchInfo($playerGamertag); // You also had this copied all over the place.  The more times you call this function, the more you'll hit the API with your key.  You were hitting it 4 times per run of this script before
  102.     $str = implode("#|#", $cache);
  103.     file_put_contents($cachefile, $str);
  104.     unset($str);
  105.     //generateImage($playerGamertag);
  106.     } else {
  107.     // The cache existed and was younger than 1 hour
  108.     // Notice how we don't do anything since we already have our $cache variable populated
  109.     }
  110.   } else {
  111.   // The cache didn't exist
  112.   $cache = fetchInfo($playerGamertag);
  113.   $str = implode("#|#", $cache);
  114.   file_put_contents($cachefile, $str);
  115.   unset($str);
  116.   }
  117.  
  118. // At this point we have a variable called $cache that contains information either from the text file, or from the API (which was written to the text file)
  119.  
  120. generateImage($cache); // Now we generate our image
  121. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement