2012-05-05 41 views
3

有誰知道ImageMagick是否可以通過網頁字體驅動? (?也許通過STD在飼料中)我試圖線以下,沒有運氣:Imagemagick和網頁字體

convert -fill black -font http://fonts.googleapis.com/css?family=Diplomata+SC -pointsize 72 label:'Acme Dynamite Company, LLC' logo.png 

我的目標是讓用戶選擇谷歌的Web字體。

+0

只是一個更新 - 我已經決定了它可以使用谷歌API來獲取字體列表,然後拉下通過WGET的WOFF文件,但ImageMagick似乎不支持WOFF格式的字體。如果有人知道基於Linux的WOFF到TTF轉換器,我想我將免費在家.. – Anthony

+0

您可以使用'-font'指向像'-font。/ myfont.ttf'這樣的文件嗎? – Federico

回答

1

我知道這是很老的在這一點上,但在儲蓄他人的利益有時,這裏是一些基本的PHP做你想做什麼。它可以優化使用curl等,但這應該足以讓人們去。看起來,當從瀏覽器訪問時,它返回一個woff和woff2 url,但是當從其他任何地方訪問時,它會返回一個tff。

$fontUrl = 'http://fonts.googleapis.com/css?family=Anton'; 
    $fontDescription = file_get_contents($fontUrl); 

    $startStr = 'url('; 
    $startStrLen = strlen($startStr); 
    $start = strpos($fontDescription, $startStr) + $startStrLen; 
    $end = strpos($fontDescription, ')', $start); 
    $tffUrl = substr($fontDescription, $start, $end - $start); 

    $tffFile = '/tmp/anton.ttf'; 
    file_put_contents($tffFile, file_get_contents($tffUrl)); 

    $im = new Imagick(); 
    $im->setFont($tffFile); 
    $im->newPseudoImage(100, 100, "caption:Hello"); 
    $im->setImageFormat('png'); 
    $im->setImageBackgroundColor(new ImagickPixel('transparent')); 
    header('Content-Type: image/png'); 
    echo $im->__toString(); 
+0

有趣的答案! – JayKandari

1

非常感謝Floss爲您解決這個問題。我用類似的方式解決了它。

我使用隨機數而不是像font.ttf這樣的靜態文件名的原因是,如果其他用戶同時調用該函數,則可能會產生問題。

  1. 查詢的谷歌字體列表

    $url = 'https://www.googleapis.com/webfonts/v1/webfonts?key=YOUR KEY HERE'; 
    
    $responseString = file_get_contents($url); 
    $fontJSON = json_decode($responseString); 
    
  2. 訪問的字體,像這樣的網址:

    <select name="font"> 
        <?php foreach ($fontJSON->items as $font): ?> 
        <option value="<?= $font->files->regular ?>"><?= $font->family ?></option> 
        <?php endforeach; ?> 
    </select> 
    
    • 請注意,你必須做一些其他弄虛作假選擇變體(如粗體或斜體),但超出了這篇文章。
  3. 在將表單數據傳遞到服務器之後,按照以下方式使用它。

    //create a random number for a unique filename 
    $random_number = intval("0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9)); 
    
    //download the TTF from Google's server 
    $font_contents = file_get_contents($font); 
    
    //Make a local file of a unique name 
    $font_file = fopen("/tmp/$random_number.ttf", "w"); 
    
    //Write data from the Google Font file into your local file 
    fwrite($font_file, $font_contents); 
    
    //Close the file 
    fclose($font_file); 
    
    //Set iMagick to use this temporary file 
    $draw->setFont("/tmp/$random_number.ttf"); 
    
    //DO YOUR iMagick STUFF HERE 
    
  4. 刪除臨時字體文件

    unlink("tmp/$random_number.ttf"); //remove tmp font