2013-07-12 43 views
0

我是新來的PHP。我正嘗試上傳圖片,調整圖片大小,然後在不保存的情況下顯示圖片。我正在使用gd來做到這一點。這裏提供的代碼僅僅是該功能工作的基本方法。圖像調整大小和顯示使用PHP和GD

<?php 
if (!isset($_FILES['image']['tmp_name'])) { 
} 
else{ 
$file=$_FILES['image']['tmp_name']; 
$img_src = imagecreatefromstring(file_get_contents($file)); 
$img_dest = imagecreatetruecolor(851, 315); 
$src_width = imagesx($img_src); 
$src_height = imagesy($img_src); 
imagecopyresized($img_dest, $img_src, 0, 0, 0, 0, 851, 315, $src_width, $src_height); 
$text= $_POST['text']; 
$font_path = 'arial.TTF'; 
$grey = imagecolorallocate($img_dest, 128, 128, 128); 
$black = imagecolorallocate($img_dest, 0, 0, 0); 
imagettftext($img_dest, 25, 0, 302, 62, $grey, $font_path, $text); 
imagettftext($img_dest, 25, 0, 300, 60, $black, $font_path, $text); 
header("Content-type: image/png"); 
imagepng($img_dest); 
imagedestroy($img_dest); 
imagedestroy($img_src); 
} 
?> 

我通過表單上載圖像並運行此腳本。圖像正在顯示。但如何使用此方法顯示不同大小的多個圖像。 有關。

+0

嗨,網上有這麼多的例子,它不適合堆棧溢出問題。嘗試搜索'php resize image'和類似的東西。這些功能的手冊也有例子。 –

+0

例如http://php.net/manual/en/function.imagecopyresampled.php –

回答

0

您應該創建兩個圖像。一,你可以直接從源創建

$img_src = imagecreatefrompng($file); 

$img_src = imagecreatefromjpeg($file); 

$img_src = imagecreatefromstring(file_get_contents($file)); 

得到SRC文件的文件大小:

$sizes = imagesize($img_src); 
$src_width = $sizes[0]; 
$src_height = $sizes[1]; 

但現在圖像將被縮放到200x200 ev如果src圖像與高度不一樣。 您可以通過計算DST尺寸防止這種情況:

$faktor = ($src_width > $src_height ? $src_width : $src_height); 
$faktor = 100/$faktor; 

$f_width = round($src_width * $faktor); 
$f_height = round($src_height * $faktor); 

$new_w = 200 * $f_width; 
$new_h = 200 * $f_height; 

你可以從你的目標大小

$img_dest = imagecreatetruecolor($new_w, $new_h); 

創建,然後你可以複製的調整源新

第二個
imagecopyresized($img_dest, $img_src, 0, 0, 0, 0, $new_w, $new_h, $src_width, $src_height); 
header("Content-type: image/png"); 
imagepng($img_dest); 
imagedestroy($img_dest); 
imagedestroy($img_src); 

PS:當從字符串創建圖像時,我認爲它不適合添加內容。

+0

仍然會破碎圖像... :( –

+0

是否需要手動提及$ src_width和$ src_height。 –

+0

那麼你現在的代碼是什麼?嘗試註釋掉頭文件並回顯相關數據並檢查是否有正確的內容大小和圖像,或者先嚐試使用'imagepng($ img_src);'而不是'imagepng($ img_dest);'來檢查src在調整大小之前,圖像是正確的 – DaKirsche

0

我發現一個老問題的解決方案,用於改變尺寸的圖像的

$original_info = getimagesize($filename); 
$original_w = $original_info[0]; 
$original_h = $original_info[1]; 
$original_img = imagecreatefromjpg($filename); 
$thumb_w = 100; 
$thumb_h = 100; 
$thumb_img = imagecreatetruecolor($thumb_w, $thumb_h); 
imagecopyresampled($thumb_img, $original_img, 
        0, 0, 
        0, 0, 
        $original_w, $original_h 
        $thumb_w, $thumb_h); 
imagejpeg($thumb_img, $thumb_filename); 
destroyimage($thumb_img); 
destroyimage($original_img); 

Change Image Size - PHP