2011-12-12 54 views
1

我已經編輯了基本的php.net腳本來調整大小以適合我的規格。它適用於本地文件,但涉及到遠程文件(這是試圖調整圖像從一個WordPress博客去與博客帖子)我似乎無法弄清楚如何GRAB圖像,操縱它,然後輸出它。從URL調整PHP大小

// The file 
$filename = 'like-father-like-son.jpg'; 

// Set a maximum height and width 
$width = 150; 
$height = 150; 

// Content type 
header('Content-Type: image/jpeg'); 

list($width_orig, $height_orig) = getimagesize($filename); 

$ratio_orig = $width_orig/$height_orig; 

if ($width/$height > $ratio_orig) { 
    $width = $height*$ratio_orig; 
} else { 
    $height = $width/$ratio_orig; 
} 

// Resample 
$image_p = imagecreatetruecolor($width, $height); 
$image = imagecreatefromjpeg($filename); 
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); 

// Output 
imagejpeg($image_p, null, 100); 

上述腳本有效,但我想要$ filename來訪問:http://USERNAME.files.wordpress.com/DATE/like-father-like-son.jpg


編輯:這個腳本工作正常。這是我嘗試在本地運行WAMP的網絡出現問題。這會教會我在午餐時間嘗試做它! 因爲浪費任何人的時間而致歉,並感謝那些捐款的人。

請隨意使用下面的腳本,它會調整文件或URL中的圖像大小,使其適合聲明的尺寸(只要其爲jpeg)並保持相同的縱橫比。

編輯2:我想我只是在這裏添加這個,因爲我有這個麻煩實施它。我個人還有兩個問題,我想用它來生成一個圖像,並打印一些帶有'header('Content-Type:image/jpeg')的文本;不起作用。我也希望resize腳本能夠運行多個圖像。

解決方案:將圖像調整大小腳本放置在單獨的文件(imageresizer.php)中,並使用GET數據將圖像的URL發送給它。因此,圖像大小調整腳本的頂部,現在將改爲:

// The file 
$filename = $_GET['imagesrc']; 

,並在底部,我有圖像回:

//Output 
return (imagejpeg($image_p,null,100)); 

腳本引用和渲染圖像(一個發送數據到圖像大小調整)將有類似這樣的東西:

$imagesrc = "put your image sourcing script here"; 
echo '<img src="imageresizer.php?' . $imagesrc . '" />'; 

我希望這可以幫助那裏的人!

+0

定義'遠程files' ...怎麼會使用它們?通過HTTP,FTP等? – DaveRandom

+0

我現在編輯它,它只是通過http URL。 – user1093553

回答

1
<?php 
    $remote_file = 'http://l.yimg.com/g/images/soup_hero-04.jpg'; 
    $new_width = 100; 
    $new_height = 100; 
    list($width, $height) = getimagesize($remote_file); 
    $image_p = imagecreatetruecolor($new_width, $new_height); 
    $image = imagecreatefromjpeg($remote_file);   
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
    header('Content-Type: image/jpeg'); 
    imagejpeg($image_p, NULL, 100); 
    imagedestroy($image_p); 
?> 

注:確保無空格之前或PHP標籤後

+0

我得到:「[function.getimagesize]:未能打開流:連接嘗試失敗,因爲連接的方沒有正確一段時間後響應或已建立的連接失敗,因爲連接主機未能響應」使用此 – user1093553

+0

時@ user1093553:您可能需要在您的php.ini中啓用'allow_url_fopen'。 –