Image Signatures Group » Обсуждения

artist and track on seperate lines?

 
    • behooved пишет...
    • Пользователь
    • Янв 5 2006, 3:06

    artist and track on seperate lines?

    Is there any way to edit the ScrobblerSig code so that the artists and tracks appear on their own lines? I'm trying to squeeze the image into a sidebar on my blog, and when the artist/track are on the same line, it often extends past the horizontal space I've got.

    Also if it's possible to put the "last track played" message and the time/date on separate lines as well... making a total of 4 lines of text in the image.

    I'm running the script from my own server, so I've got the control for whatever needs to be done to make this work. Unfortunately I don't know php!

    Thanks in advance.

    • Manero пишет...
    • Пользователь
    • Янв 5 2006, 5:36
    Here is a really simple way to do it.

    <?php
    /* ScrobblerSig 2.1 by Timothy Humphrey (Humpty), http://timothyhumphrey.name/scrobblersig
    *
    * Contributors
    *
    * electrichamster - The original creator of ScrobblerSig
    * russ
    */

    /* ---------- Main User Config ---------- */

    /*
    * The options that are listed below may be specified in the url if the allowParameters option is
    * true. To do so first append a question mark ? to the end of the url. Next, specify the option
    * name followed by an equal sign = and then the value; for example, option=value. Multiple options
    * are specified by separating them with an ampersand &; for example, option1=value1&option2=value2.
    * Enter %26 to specify an ampersand & character in the url, %3D for an equal = sign.
    *
    * The username option is an exception and is always allowed to be specified in the url, but whether
    * or not it is actually used depends on other options.
    *
    * All parameters may be specified by their regular name or by a short form; the short form that can
    * be used is specified in parenthesis at the beginning of the parameter's description. The general
    * naming convention for the short name is to use the first letter of each word comprising the name.
    * Be aware of conflicts though, such as backgroundColor (bc) and borderColor (bdc). Whether the
    * full or short name is used specify the parameter name in lowercase.
    *
    * Examples
    *
    * scrobblersig.php
    * scrobblersig.php?fontsize=24
    * scrobblersig.php?labelcolor=aa0000&trackcolor=a9b200
    * scrobblersig.php?fs=24
    * scrobblersig.php?lc=aa0000&tc=a9b200
    */
    //(u) Audioscrobbler username, see the allowAnyUser and allowWhitelistedUser options for info about
    //using this option in the url.
    $username = "behooved";

    /*
    * All of the "-label" options below can display the time the track is played by specifying time
    * variables:
    *- <date> Outputs the date according to the dateFormat option
    *- <time> Outputs the time according to the timeFormat option
    *- <zone> Outputs the timezone according to the timeZoneOffset and timeZoneLabel options. The
    * timeZoneLabel is output instead of the timeZoneOffset if it is present.
    *
    * Example
    *
    * "This song was played at <time> <zone> on <date>"
    */
    //(cpl) Text to display if track is currently playing
    $currentlyPlayingLabel = "Currently playing:";

    //(lpl) Text to display if track isn't currently playing
    $lastPlayedLabel = "Last song played
    @ <time> <zone> on <date>:";

    //(el1 and el2) Text to display if the song parse failed
    $errorLabel1 = "Error:";
    $errorLabel2 = "Unable to parse song title from audioscrobbler.com";

    /*
    * Time formats, see http://www.php.net/date for details about the dateFormat and timeFormat
    */
    //(df) Format used to replace the <date> pattern
    $dateFormat = "D, M j, Y";

    //(tf) Format used to replace the <time> pattern
    $timeFormat = "g:i A";

    //(tzo) Time between your time zone and GMT in [-]hour[:minute] format; that is the beginning minus
    //sign is optional and so are the minutes, if minutes are included separate from hours with a colon.
    //This is also used to replace the <zone> pattern if the timeZoneLabel option isn't specified.
    $timeZoneOffset = "-5";

    //(tzl) Replaces the <zone> pattern
    $timeZoneLabel = "EST";

    /*
    * Formatting options. The various "-color" options specify colors using the RRGGBB format, where
    * RR represents the hexadecimal numerical amount of red, GG the amount of green, and BB the amount
    * of blue; for example FF0000 is red, A9B200 is a dull golden color.
    */
    //(f) The filename of the truetype font to use. Native PHP font searching rules are used:
    // - If the .ttf extension is not specified it is appended.
    // - Most systems will search in the same directory as the script for the font and if it can't be
    // found search system font directories, this allows you to use any font on the system as well as
    // custom fonts.
    $font = "Vera.ttf";

    //(fs) The size of the font in points
    $fontSize = 10;

    //(fc) The foreground color; the labelColor and trackColor parameters override this if set.
    $foregroundColor = "000000";

    //(lc) The color of the track label, the first line of text
    $labelColor = null;

    //(tc) The color of the track text, the second line of text
    $trackColor = null;

    //(a) Whether antialiasing should be applied to the text; specify 1 for true and 0 for false in the
    //url. If set to true you should set the backgroundColor to match the background of the page the
    //image will appear on for best results.
    $antialias = false;

    //(ha) Horizontal alignment of the text, can be "left" or "right"
    $horizontalAlign = "left";

    //(b) Whether or not a border is drawn around the image; specify 1 for true and 0 for false in the
    //url.
    $border = false;

    //(bdc) The color of the image border, see the border option
    $borderColor = "000000";

    //(p) The padding to appear on the sides of the image; the horizontalPadding and verticalPadding
    //parameters override this if set.
    $padding = 0;

    //(hp) The padding to appear on the left and right side of the image
    $horizontalPadding = null;

    //(vp) The padding to appear on the top and bottom of the image
    $verticalPadding = null;

    //(bc) The background color
    $backgroundColor = "000000";

    //(bi) Background image to use; may be GIF, PNG, or JPEG format
    $backgroundImage = "";

    //(bt) Whether the backgroundColor appears; specify 1 for true and 0 for false in the url.
    $backgroundTransparent = true;

    //(it) The image format, may be "png" or "jpg"
    $imageType = "png";

    //(mw) The maximum width of the image, 0 means unrestricted; ignored if a backgroundImage is used.
    $maxWidth = 0;

    //(mh) The maximum height of the image, 0 means unrestricted; ignored if a backgroundImage is used.
    $maxHeight = 0;


    /*
    * The following options may NOT be specified in the url
    */
    //Whether or not parameters specified in the url are used; setting this to false will result in
    //fewer variations of images being cached on the server.
    $allowParameters = true;

    //Whether or not any username can be specified for the username option in the url; this takes
    //precedence over the allowWhitelistedUser option.
    $allowAnyUser = false;

    //Whether or not whitelisted users can be specified for the username option in the url, see the
    //whitelistedUserFilename option.
    $allowWhitelistedUser = true;

    //The filename of a list of usernames, one on each line, that are allowed to be specified for the
    //username option; also see the allowWhitelistedUser option.
    $whitelistedUserFilename = "scrobblersig-whitelist.txt";

    //Whether or not the browser's cache should be used to help minimize bandwidth usage
    $useBrowserCache = true;

    //Number of seconds information is cached from Audioscrobbler
    $cacheDuration = 120;

    //Number of seconds to wait for a response from the Audioscrobbler server
    $timeout = 10;



    /* ---------- Main code, do not edit past this point ---------- */

    //error_reporting(E_ERROR | E_WARNING);

    function GetParameter($name, $altName, &$value, $bypassExtensionCheck = false) {
    //Get parameter while checking for disguising file extension
    if(isset($_GET[$name]) || isset($_GET[$altName])) {
    $name = isset($_GET[$name]) ? $name : $altName;
    $value = !$bypassExtensionCheck
    ? preg_replace("/(.*?)(\.png|\.jpg|\.gif)*/i", "\\1", $_GET[$name])
    : $_GET[$name];
    }
    }

    /* Get values from parameters */
    if($allowAnyUser)
    GetParameter("username", "u", $username);
    elseif($allowWhitelistedUser) {
    GetParameter("username", "u", $paramUsername);
    if($paramUsername) {
    $whitelistedUsers = @file_get_contents("./$whitelistedUserFilename");
    $username = preg_match("/\b$paramUsername\b/", $whitelistedUsers) ? $paramUsername : $username;
    }
    }

    if($allowParameters) {
    GetParameter("antialias", "a", $antialias);
    GetParameter("backgroundcolor", "bc", $backgroundColor);
    GetParameter("backgroundimage", "bi", $backgroundImage, true);
    GetParameter("backgroundtransparent", "bt", $backgroundTransparent);
    GetParameter("border", "b", $border);
    GetParameter("bordercolor", "bdc", $borderColor);
    GetParameter("currentlyplayinglabel", "cpl", $currentlyPlayingLabel);
    GetParameter("dateformat", "df", $dateFormat);
    GetParameter("errorlabel1", "el1", $errorLabel1);
    GetParameter("errorlabel2", "el2", $errorLabel2);
    GetParameter("font", "f", $font);
    GetParameter("fontsize", "fs", $fontSize);
    GetParameter("foregroundcolor", "fc", $foregroundColor);
    GetParameter("horizontalalign", "ha", $horizontalAlign);
    GetParameter("horizontalpadding", "hp", $horizontalPadding);
    GetParameter("image_type", "it", $imageType); //supported for compatibility
    GetParameter("imagetype", "it", $imageType);
    GetParameter("labelcolor", "lc", $labelColor);
    GetParameter("lastplayedlabel", "lpl", $lastPlayedLabel);
    GetParameter("maxheight", "mh", $maxHeight);
    GetParameter("maxwidth", "mw", $maxWidth);
    GetParameter("padding", "p", $padding);
    GetParameter("trackcolor", "tc", $trackColor);
    GetParameter("timeformat", "tf", $timeFormat);
    GetParameter("timezonelabel", "tzl", $timeZoneLabel);
    GetParameter("timezoneoffset", "tzo", $timeZoneOffset);
    GetParameter("verticalpadding", "vp", $verticalPadding);
    }

    /* Fix certain parameters to ensure proper values */
    if(!isset($labelColor)) $labelColor = $foregroundColor;
    if(!isset($trackColor)) $trackColor = $foregroundColor;
    if(!isset($horizontalPadding)) $horizontalPadding = $padding;
    if(!isset($verticalPadding)) $verticalPadding = $padding;

    $antialias = (bool) $antialias;
    $backgroundTransparent = (bool) $backgroundTransparent;
    $border = (bool) $border;
    $fontSize = (int) $fontSize;
    $horizontalAlign = $horizontalAlign == "right" ? "right" : "left";
    $horizontalPadding = (int) $horizontalPadding;
    $maxHeight = (int) $maxHeight;
    $maxWidth = (int) $maxWidth;
    $verticalPadding = (int) $verticalPadding;

    $temp = explode(":", $timeZoneOffset);
    $timeZoneOffset = (int) $temp[0];
    if(count($temp) > 1)
    $timeZoneOffset += (int) $temp[1] / 60 * (substr($temp[0], 0, 1) == "-" ? -1 : 1);

    /* Check to see if the song info needs updating */
    $safeUsername = escapeshellcmd($username);
    $dataFilename = "./sig-$safeUsername.txt";
    if(!file_exists($dataFilename) || (filemtime($dataFilename) + $cacheDuration < time())) {
    //Delete cached images
    $tempFiles = array_merge(glob("./sig-$safeUsername*.png"), glob("./sig-$safeUsername*.jpg"));
    if($tempFiles != null) {
    foreach($tempFiles as $filename)
    @unlink($filename);
    }

    //Get user track data from Audioscrobbler
    $data = "";
    $fp = @fopen("http://ws.audioscrobbler.com/txt/recent/$username";, "r");
    if($fp != null) {
    stream_set_timeout($fp, $timeout);
    $data = fread($fp, 100000);
    fclose($fp);
    }

    if(trim($data) != "") {
    $dataFile = @fopen($dataFilename, "wt");
    if($dataFile != null) {
    @fwrite($dataFile, $data);
    @fclose($dataFile);
    }
    }
    elseif(file_exists($dataFilename)) {
    //Remove currently playing track info and preserve cached Audioscrobbler data
    if($data = @file($dataFilename)) {
    $data[0] = "\n";
    if($dataFile = @fopen($dataFilename, "wt")) {
    @fwrite($dataFile, implode("", $data));
    @fclose($dataFile);
    }
    }
    }
    }

    /* Determine if client cache should be used */
    if($useBrowserCache
    && isset($_SERVER["HTTP_IF_MODIFIED_SINCE"]) && file_exists($dataFilename)
    && strtotime($_SERVER["HTTP_IF_MODIFIED_SINCE"]) == filemtime($dataFilename)
    ) {
    header("Status: 304 Not Modified", true, 304); //HTTP status set this way to work on IIS
    exit;
    }

    /* Create image if no cached version of it exists */
    $imageFilename = "./sig-$safeUsername" . ($allowParameters && $_SERVER["QUERY_STRING"] ? "-" . md5($_SERVER["QUERY_STRING"]) : "") . ".$imageType";
    $image = null;
    if(!file_exists($imageFilename)) {
    $trackData = @file($dataFilename);
    if($trackData != null) {
    $trackData[0] = trim($trackData[0]);

    //Check if a track is currently playing
    if($trackData[0] != "") {
    $track = $trackData[0];
    $label = $currentlyPlayingLabel;
    $date = time();
    }
    else {
    $track = $trackData[1];
    $label = $lastPlayedLabel;
    $date = strtotime($trackData[2]);
    }

    $track = html_entity_decode($track);

    if($timeZoneOffset != "")
    $date = strtotime((int) ($timeZoneOffset * 60) . " minute", $date);
    }
    else {
    $label = $errorLabel1;
    $track = $errorLabel2;
    $date = time();
    }

    //Split the Artist and Songtitle
    $track = preg_replace('/\ - +/', '
    ', $track);

    //Replace time format variables with actual values
    $label = str_replace("<date>", gmdate($dateFormat, $date), $label);
    $label = str_replace("<time>", gmdate($timeFormat, $date), $label);
    $label = str_replace("<zone>", $timeZoneLabel ? $timeZoneLabel : ($timeZoneOffset < 0 ? "-" : "+") . sprintf("%'02d", abs($timeZoneOffset)) . sprintf("%'02d", round(abs(($timeZoneOffset - (int) $timeZoneOffset) * 60))), $label);

    $label = trim($label);
    $track = trim($track);

    /* Generate the image */
    //Get the text sizes
    $labelBounds = imagettfbbox($fontSize, 0, $font, $label);
    $labelWidth = $labelBounds[2] - $labelBounds[0] + 1;
    $labelHeight = -$labelBounds[7] + $labelBounds[1] + 1;

    $trackBounds = imagettfbbox($fontSize, 0, $font, $track);
    $trackWidth = $trackBounds[2] - $trackBounds[0] + 1;
    $trackHeight = -$trackBounds[7] + $trackBounds[1] + 1;

    //Get image dimensions
    $dimension = max($labelWidth, $trackWidth) + ($horizontalPadding * 2) + ($border ? 2 : 0);
    $maxWidth = ($maxWidth > 0 && $dimension > $maxWidth) ? $maxWidth : $dimension;
    $dimension = $labelHeight + $trackHeight + ($verticalPadding * 2) + ($border ? 2 : 0);
    $maxHeight = ($maxHeight > 0 && $dimension > $maxHeight) ? $maxHeight : $dimension;

    //Generate image canvas
    if($backgroundImage != "") {
    preg_match("/[^\.]+$/", $backgroundImage, $extension);
    switch($extension[0]) {
    case "gif":
    $image = @imagecreatefromgif($backgroundImage);
    break;
    case "png":
    $image = @imagecreatefrompng($backgroundImage);
    break;
    case "jpg":
    $image = @imagecreatefromjpeg($backgroundImage);
    break;
    }
    }
    if($image == null)
    $image = imagecreate($maxWidth, $maxHeight);

    //Set the colors
    preg_match_all("/[\dabcdef]{2}/i", $backgroundColor, $backColorParts);
    preg_match_all("/[\dabcdef]{2}/i", $borderColor, $borderColorParts);
    preg_match_all("/[\dabcdef]{2}/i", $labelColor, $labelColorParts);
    preg_match_all("/[\dabcdef]{2}/i", $trackColor, $trackColorParts);
    $blackColorPart = array(0, 0, 0);
    if(count($backColorParts[0]) != 3) $backColorParts[0] = $blackColorPart;
    if(count($borderColorParts[0]) != 3) $borderColorParts[0] = $blackColorPart;
    if(count($labelColorParts[0]) != 3) $labelColorParts[0] = $blackColorPart;
    if(count($trackColorParts[0]) != 3) $trackColorParts[0] = $blackColorPart;

    $backColorIndex = imagecolorallocate($image, hexdec($backColorParts[0][0]), hexdec($backColorParts[0][1]), hexdec($backColorParts[0][2]));
    $borderColorIndex = imagecolorallocate($image, hexdec($borderColorParts[0][0]), hexdec($borderColorParts[0][1]), hexdec($borderColorParts[0][2]));
    $labelColorIndex = imagecolorallocate($image, hexdec($labelColorParts[0][0]), hexdec($labelColorParts[0][1]), hexdec($labelColorParts[0][2]));
    $trackColorIndex = imagecolorallocate($image, hexdec($trackColorParts[0][0]), hexdec($trackColorParts[0][1]), hexdec($trackColorParts[0][2]));
    if($backgroundTransparent)
    imagecolortransparent($image, $backColorIndex);

    //Check to see if antialiasing is used
    if(!$antialias) {
    $labelColorIndex = -$labelColorIndex;
    $trackColorIndex = -$trackColorIndex;
    }

    //Draw border
    if($border)
    imagerectangle($image, 0, 0, $maxWidth - 1, $maxHeight - 1, $borderColorIndex);

    //Draw label
    $x = ($horizontalAlign == "right" ? max($labelWidth, $trackWidth) - $labelWidth : 0) + $horizontalPadding + ($border ? 1 : 0);
    $y = $labelHeight - abs($labelBounds[1]) + $verticalPadding + ($border ? 1 : 0);
    imagettftext($image, $fontSize, 0, $x, $y, $labelColorIndex, $font, $label);

    //Draw track
    $x = ($horizontalAlign == "right" ? max($labelWidth, $trackWidth) - $trackWidth : 0) + $horizontalPadding + ($border ? 1 : 0);
    $y = $trackHeight - abs($trackBounds[1]) + $verticalPadding + $labelHeight + ($border ? 1 : 0);
    imagettftext($image, $fontSize, 0, $x, $y, $trackColorIndex, $font, $track);

    //Save image
    if($imageType == "jpg")
    @imagejpeg($image, $imageFilename);
    else
    @imagepng($image, $imageFilename);

    if(file_exists($imageFilename)) {
    imagedestroy($image);
    $image = null;
    }
    }

    /* Output the image */
    //Output image headers
    if($imageType == "jpg")
    header("Content-type: image/jpeg");
    else
    header("Content-type: image/png");

    if(file_exists($dataFilename)) {
    header("Last-Modified: " . gmdate("D, d M Y H:i:s", filemtime($dataFilename)) . " GMT");
    header("Expires: " . gmdate("D, d M Y H:i:s", filemtime($dataFilename) + $cacheDuration) . " GMT");
    }

    //Output image
    if(!$image)
    readfile($imageFilename);
    else {
    if($imageType == "jpg")
    imagejpeg($image);
    else
    imagepng($image);
    imagedestroy($image);
    }
    ?>

    Visit the Car Group - Anthing relating Cars
    • behooved пишет...
    • Пользователь
    • Янв 5 2006, 6:13
    Thank you so much! It worked like a charm :D

    The only problem I'm having still is that it never seems to want to use the "currently playing" text. Even when the song it lists is one that I'm listening to at that very moment, it still displays "last song played" and then the time/date. Are there any obvious explanations for this, or could it just be the free server I'm using not updating fast enough (100webspace)?

    Thanks again for the php code!

    • Manero пишет...
    • Пользователь
    • Янв 5 2006, 6:38
    Well the scipt chaches the data for so long. You cna edit the time on the line which shows "$cacheDuration = 120;" however it is not good to set too low as it puts strain on the last.fm site. The 120 means 120 seconds or 2 min.

    Visit the Car Group - Anthing relating Cars
    • lozzd пишет...
    • Alumni
    • Янв 6 2006, 2:38

    Re:

    Quoth behooved:
    Thank you so much! It worked like a charm :D

    The only problem I'm having still is that it never seems to want to use the "currently playing" text. Even when the song it lists is one that I'm listening to at that very moment, it still displays "last song played" and then the time/date. Are there any obvious explanations for this, or could it just be the free server I'm using not updating fast enough (100webspace)?

    Thanks again for the php code!


    The "current playing" text only worked on the old RSS feed and back in the old days when there was such a thing as "Currently Playing". Last.fm has an artifical "Now listening" on your profile page but that is not transferred to the feed like it used to; so your sig will never use that, because it never things any of the tracks are "currently playing".


    Want a fully customisable sig (like above?) CLICK HERE!
    Insert disclaimer here.
    • behooved пишет...
    • Пользователь
    • Янв 8 2006, 19:06
    Ah ok, thanks for clearing that up. I'll give up trying to get it to work then!

    • SLStratocaster пишет...
    • Пользователь
    • Апр 13 2006, 23:39
    How do you change it so the artist is under?

Анонимные пользователи не могут оставлять сообщения. Для того, чтобы писать в форумах, пожалуйста, войди на сайт или создай аккаунт.