Picasa

From XennisWiki
Jump to: navigation, search

Picasa ist eine kostenlose Bilderverwaltungssoftware zu der es als Ergänzung Picasa-Webalben, welches zur Präsentation von Bilder im Internet dient.

Software

In Picasa kannst du ein Album u.a. als XML-Datei exportieren. Diese kannst du wie folgt mit PHP verarbeiten (geschrieben für Picasa):

function readPicasaXML($file) {
	
	$xml_file = simplexml_load_file($file);
	
	$dbpath = 'galerien/';
	
	// Informationen uber das Albumg
		// (string): Zu String konvertieren, da es sich um Objekte handelt
		// trim: Leerzeichen am Anfang und Ende entfernen
	// Albumname
	$albumName	= trim( (string) $xml_file->albumName );								
	// Albumbeschreibung
	$albumCaption	= trim( (string) $xml_file->albumCaption );
	// Anzahl der Fotos im Album
	$albumItemCount	= trim( (string) $xml_file->albumItemCount );
	// Absoluter Pfad zum ersten Bild
	$albumPath	= trim( (string) $xml_file->images->image[0]->itemOriginalPath );
	//Den Dateiname des ersten Bildes entfernen
	$albumPath	= strstr($albumPath, trim( (string) $xml_file->images->image[0]->itemName ), true);
	// str_replace: '\' durch '/' ersetzen		
	$albumPath	= str_replace('\\', '/', $albumPath);
	// Pfad erst nach $dbpath betrachten
		// strstr: Substring ab $dbpath; str_replace: Substring ohne $dbpath
	$albumPath	= str_replace($dbpath, '', strstr($albumPath, $dbpath));
	// Pfad in Einzelteile zerlegen ohne Album (-1)
	$albumPathArray = explode('/', $albumPath, -1);
	
	foreach($albumPathArray as $c)
		echo $c,"<br />";
	
	// Ausgabe
	echo $albumName;
	echo "<br>";
	echo $albumCaption;
	echo "<br>";
	echo $albumPath;
	echo "<br>";
	echo $albumItemCount;
	echo "<br>";

	// Informationen ueber die Bilder
	foreach($xml_file->images->image as $image) {
		// Dateiname; trim: Entfernt Leerzeichen am Ende und am Anfang
		$itemName	= trim((string) $image->itemName);
		// Beschreibung; trim: siehe Oben; htmlentities: Zeichen in HTML-Codes umwandeln
		$itemCaption	= htmlentities( trim( (string) $image->itemCaption ) );
		
		// ANMERKUNG: Exestiert keine Bildbeschreibung, so wird der Dateinname des Bildes als Bildbeschreibung gewaehlt
		if($itemCaption == $itemName) {
			$itemCaption = "";
		}

		// Ausgabe
		echo $itemName;
		echo "-";
		echo $itemCaption;
		echo "<br>";
	}
	
}

Aufruf der Funktion mit der Datei test.xml

readPicasaXML('test.xml');

Webalben - API

Protocol (XML)

Hilfe und Infos

Um auf nicht öffentliche Daten eines Benutzer zugreifen zu können, ist eine Autorisation notwendig

Alben eines Benutzers

Auf die öffentlichen Alben eines Benutzers kannst du wie folgt zugreifen

https://picasaweb.google.com/data/feed/api/user/USER-ID

Die Daten kannst du mit PHP wie folgt abrufen

/**
 * Read Picasa albums XML
 *
 * @param  string $userID  Picasa user ID
 * @return void
 */
function readPicasaAlbumsXML($userID) {
	
	// Get XML file
	$xml_file = simplexml_load_file('https://picasaweb.google.com/data/feed/api/user/'.$userID);
	
	// Get namespaces declared in document
	$xml_namespaces = $xml_file->getDocNamespaces();
		// Register xpath namespace
		while($namespace = current($xml_namespaces)) {
			if(key($xml_namespaces) != "") {
				$xml_file->registerXPathNamespace(key($xml_namespaces), $namespace);
			}
			next($xml_namespaces);
		}
	
	// General information
	$numAlbums				= (string) array_pop($xml_file->xpath('//openSearch:totalResults'));

	// Album information
	foreach($xml_file->entry as $entry) {
		$album				= array();
		$album['published']		= strtotime( (string) $entry->published );// strtotime: string to timestamp
		$album['updated']		= strtotime( (string) $entry->updated );
		$album['title']			= htmlentities( (string) $entry->title );
		$album['summary']		= htmlentities( (string) $entry->summary );
		$album['id']			= (string) array_pop($entry->xpath('//gphoto:id'));
		$album['numPhotos']		= (string) array_pop($entry->xpath('//gphoto:numphotos'));
		$album['keywords']		= htmlentities( (string) array_pop($entry->xpath('//media:keywords')) );
		
		var_dump($album);
	}
}

Album eines Benutzers

Und auf ein bestimmtes Album eines Benutzers zu zugreifen, musst du folgenden Link verwenden

https://picasaweb.google.com/data/feed/api/user/USER-ID/albumid/ALBUM-ID

Zugriff mit PHP

/**
 * Read Picasa album XML
 *
 * @param  string $userID   Picasa user ID
 * @param  string $albumID  Picasa album ID
 * @return void
 */
function readPicasaAlbumXML($userID, $albumID) {

	// Read xml file
	$xml_file = simplexml_load_file('https://picasaweb.google.com/data/feed/api/user/'.$userID.'/albumid/'.$albumID);

	// Get namespaces declared in document
	$xml_namespaces = $xml_file->getDocNamespaces();
		// Register xpath namespace
		while($namespace = current($xml_namespaces)) {
			if(key($xml_namespaces) != "") {
				$xml_file->registerXPathNamespace(key($xml_namespaces), $namespace);
			}
			next($xml_namespaces);
		}

	// Photo information
	foreach($xml_file->entry as $entry) {
		$photo				= array();
		$photo['published']		= strtotime( (string) $entry->published );// strtotime: string to timestamp
		$photo['updated']		= strtotime( (string) $entry->updated );
		$photo['summary']		= htmlentities( (string) $entry->summary );
		$photo['content']		= (string) $entry->content['src'];
		$photo['id']			= (string) array_pop($entry->xpath('//gphoto:id'));
		$photo['license']		= (string) array_pop($entry->xpath("//gphoto:license['name']"));
		$photo['keywords']		= htmlentities( (string) array_pop($entry->xpath('//media:keywords')) );
		
		var_dump($photo);
	}
}

PHP client library

Beispiel Code

Dieses Beispiel beeinhalt bereits eine Reihe von Funktionen.

  • framework.zend.com
  • Oder in den heruntergeladenen Dateien: demos > Zend > Gdata > Photos.php

Album eines Benutzers

<?php

// Zend_Loader
require_once 'Zend/Loader.php';

// Load Zend classes
Zend_Loader::loadClass('Zend_Gdata_Photos');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_Photos_AlbumQuery');

// Config
$user			= "E-MAIL";
$pass			= "PASSWORT";

// Service name and client
$serviceName		= Zend_Gdata_Photos::AUTH_SERVICE_NAME;
$client			= Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $serviceName);

// update the second argument to be CompanyName-ProductName-Version
$gp = new Zend_Gdata_Photos($client, "Google-DevelopersGuide-1.0");

// In version 1.5+, you can enable a debug logging mode to see the
// underlying HTTP requests being made, as long as you're not using
// a proxy server
// $gp->enableRequestDebugLogging('/tmp/gp_requests.log');

// update the second argument to be CompanyName-ProductName-Version

/**
 * Returns the path to the current script, without any query params
 *
 * Env variables used:
 * $_SERVER['PHP_SELF']
 *
 * @return string Current script path
 */
function getCurrentScript()
{
    global $_SERVER;
    return $_SERVER["PHP_SELF"];
}

/**
 * Outputs an HTML unordered list (ul), with each list item representing a
 * photo in the user's album feed.
 *
 * @param  Zend_Http_Client $client  The authenticated client object
 * @param  string           $user    The user's account name
 * @param  integer          $albumId The album's id
 * @return void
 */
function outputAlbumFeed($client, $user, $albumId)
{
	
    /*
     * ### Album ###
     * title			$albumFeed->getTitle()
     * icon			$albumFeed->getIcon()
     * updatet			$albumFeed->getUpdated()
     * subtitle			$albumFeed->getSubtitle()
     * numPhotos		$albumFeed->getGphotoNumPhotos()
     *
     * ### Photo ###
     * id			$entry->getGphotoId()
     * title			$entry->getTitle()
     * published		$entry->getPublished()
     * updated			$entry->getUpdated()
     * summary			$entry->getSummary()
     * keywords			$entry->getMediaGroup()->getKeywords()
     * content			$entry->getContent()->getSrc()
     * url (small)		$thumb = $entry->getMediaGroup()->getThumbnail();
     *				$thumb[1]->getUrl()
     * timestamp		substr( $entry->getGphotoTimestamp(), 0, -3 ) - 3600 )
     *
     */
		
    $photos = new Zend_Gdata_Photos($client);

    $query = new Zend_Gdata_Photos_AlbumQuery();
    $query->setUser($user);
    $query->setAlbumId($albumId);

    $albumFeed = $photos->getAlbumFeed($query);
    echo "<h2>Album Feed for: " . $albumFeed->getTitle() . "</h2>";
    echo "<ul class='albums'>\n";
    foreach ($albumFeed as $entry) {
        if ($entry instanceof Zend_Gdata_Photos_PhotoEntry) {
            echo "\t<li class='albums'>";
            echo "<a href='" . getCurrentScript() . "?command=retrievePhotoFeed&user=" . $user;
            echo "&album=" . $albumId . "&photo=" . $entry->getGphotoId() . "'>";
            $thumb = $entry->getMediaGroup()->getThumbnail();
            echo "<img class='thumb' src='" . $entry->getContent()->getSrc() . "' /><br />";
            echo $entry->getSummary() . "</a><br />";
            echo "</li>\n";
        }
    }
    echo "</ul><br />\n";
}
?>

Advanced

	/**
	 * Zend HttpClient
	 *
	 * @var Zend_Gdata_HttpClient
	 */
	private $client;

	/**
	 * Picasa username
	 *
	 * @var string
	 */
	private $user;

	/**
	 * Create PicasaXViewerAPI object
	 *
	 * @param  string $user    Google username
	 * @param  string $pass    Google password
	 * @return void
	 */
	public function __construct( $user, $pass ) {

		// Load required classes
		Zend_Loader::loadClass( 'Zend_Gdata' );
		Zend_Loader::loadClass( 'Zend_Gdata_ClientLogin' );
		Zend_Loader::loadClass( 'Zend_Gdata_Photos' );
		Zend_Loader::loadClass( 'Zend_Gdata_Photos_UserQuery' );
		Zend_Loader::loadClass( 'Zend_Gdata_Photos_AlbumQuery' );
		
		$this->user = $user;
		$service = Zend_Gdata_Photos::AUTH_SERVICE_NAME;

		try {
			$this->client  = Zend_Gdata_ClientLogin::getHttpClient( $this->user, $pass, $service );
		} catch( Zend_Gdata_App_Exception $e ) {
			echo $e->getMessage();
		}

	}
	/**
	 * Returns an list, with each list item representing an album in the
	 * user's feed
	 *
	 * @param  string $access     Visibility filter for entries returned
	 * @param  string $thumbsize  Thumbnail size filter for entries returned
	 * @return Zend_Gdata_Photos_UserFeed
	 */
	public function getUserFeed( $access = NULL, $thumbsize = NULL ) {

		// Create instances
		$photos = new Zend_Gdata_Photos( $this->client );
		$query = new Zend_Gdata_Photos_UserQuery();

		// Construct query
		$query->setUser( $this->user );
		if( isset( $access ) ) {
			$query->setAccess( $access );
		}
		if( is_numeric( $thumbsize ) ) {
			$query->setThumbsize( $thumbsize . 'c' );
		}

		try {
			return $photos->getUserFeed( null, $query );
		} catch ( Zend_Gdata_App_Exception $e ) {
			echo $e->getMessage();
			return false;
		}
	}
	/**
	 * Get album's feed: Returns an list, with each list item representing a
	 * photo in the user's album feed.
	 *
	 * @param  string $id          The ID of the album to retrieve
	 * @param  string $thumbsize   Thumbnail size filter for entries returned
 	 * @param  string $imgMax      Maximum image size for entries returne
	 * @param  string $maxResults  Pictures per page
 	 * @param  string $page        
	 * @return Zend_Gdata_Photos_AlbumFeed
	 */
	public function getAlbumFeed( $id, $thumbsize = NULL, $imgMax = NULL, $maxResults = NULL, $page = NULL) {

		// Create instances
		$photos = new Zend_Gdata_Photos( $this->client );
		$query = new Zend_Gdata_Photos_AlbumQuery();
	
		// Construct query
		$query->setAlbumId( $id );
		if( is_numeric( $imgMax ) ) {
			$query->setImgMax( $imgMax );
		}
		if( is_numeric( $maxResults ) ) {
			$query->setMaxResults( $maxResults );
		}
		if ( is_numeric( $page ) ) {
			$query->setStartIndex( ( ( $page - 1 ) * $maxResults ) + 1 );
		}
		if( is_numeric( $thumbsize ) ) {
			$query->setThumbsize( "$thumbsize".'c' ); // 'c' to crop thumbnail
		}

		try {
			return $photos->getAlbumFeed( $query );
		} catch ( Zend_Gdata_App_Exception $e ) {
			echo $e->getMessage();
			return false;
		}
	}

See also