2013-06-19 30 views
0

我有一個允許Jpegs和PNG的上傳功能。上傳圖片後,會調用一個php文件來處理剪裁功能,以剪裁上傳的圖片。如何在裁剪腳本中允許使用PNG?

圖像被剪切後,再次以新名稱保存到服務器。在當前的設置中,只能將jpegs寫入服務器。其他任何東西都會畫出黑色的圖像。 我不知道我怎麼寫這個代碼,以便作物也允許PNG的

處理該作物的代碼:

$imageLocation = $_SESSION['image_location']; 
$newNameOverwrite = $_SESSION['new_name']; 

if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{ 
$jpeg_quality = 100; 

$src = $imageLocation; 
list($width, $height, $type, $attr) = getimagesize($src); 
$targ_w = $width; 
$targ_h = $height; 
$img_r = imagecreatefromjpeg($src); 
$dst_r = imagecreatetruecolor($_POST[('w')], $_POST[('h')]); 
$uploadLocation = 'uploads/'; 
$name = $uploadLocation.'resized_'.$newNameOverwrite; 

imagecopy(
$dst_r, $img_r, 
0, 0, $_POST['x'], $_POST['y'], 
$_POST['w'], $_POST['h'] 
); 

imagejpeg($dst_r,$name,100); 

$imageCropped = $name; 
$_SESSION['image_cropped'] = $imageCropped; 

//Thumbnail generate 
include('SimpleImage.php'); 
$imageThumbnail = new SimpleImage(); 
$imageThumbnail->load($name); 
$imageThumbnail->resizeToWidth(200); 
$imageThumbnail->save($uploadLocation.'resizedThumbnail_'.$newNameOverwrite); 

$imageThumbnailCropped = ($uploadLocation.'resizedThumbnail_'.$newNameOverwrite); 

$imageThumbnailCroppedSession = $imageThumbnailCropped; 
$_SESSION['image_cropped_thumbnail'] = $imageThumbnailCroppedSession; 
} 

更新代碼:

$imageType = $_SESSION['image_type']; 

if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{ 
$jpeg_quality = 100; 

$src = $imageLocation; 
list($width, $height, $type, $attr) = getimagesize($src); 
$targ_w = $width; 
$targ_h = $height; 
    if ($imageType == '.jpg' || $imageType == '.jpeg'){ 
     $img_r = imagecreatefromjpeg($src); 
    } 
    if ($imageType == '.png'){ 
     $img_r = imagecreatefrompng($src); 
    }  

$dst_r = imagecreatetruecolor($_POST[('w')], $_POST[('h')]); 
$uploadLocation = 'uploads/'; 
$name = $uploadLocation.'resized_'.$newNameOverwrite; 

imagecopy(
$dst_r, $img_r, 
0, 0, $_POST['x'], $_POST['y'], 
$_POST['w'], $_POST['h'] 
); 
var_dump($imageType); 
if ($imageType == '.png'){ 
    imagepng($dst_r,$name); 
} 
if ($imageType == '.jpg' || $imageType == '.jpeg'){ 
    imagejpeg($dst_r,$name, 100); 
    } 
$imageCropped = $name; 
$_SESSION['image_cropped'] = $imageCropped; 


include('SimpleImage.php'); 
$imageThumbnail = new SimpleImage(); 
$imageThumbnail->load($name); 
$imageThumbnail->resizeToWidth(200); 
$imageThumbnail->save($uploadLocation.'resizedThumbnail_'.$newNameOverwrite); 

$imageThumbnailCropped = ($uploadLocation.'resizedThumbnail_'.$newNameOverwrite); 

$imageThumbnailCroppedSession = $imageThumbnailCropped; 
$_SESSION['image_cropped_thumbnail'] = $imageThumbnailCroppedSession; 
} 
+0

'$ img = imagecreatefromstring(readfile('file.whatever'))''會打開GD支持的任何圖像,不管類型如何。 –

回答

1

使用PHP,以確定哪些類型它的圖像,然後動態使用* _png函數而不是* _jpeg函數。 IE,而不是imagecreatefromjpeg使用imagecreatefrompng

+0

相應地更新了我的代碼。我已經有一個變量,它包含了上傳文件的php腳本中的擴展名,所以我在會話中發送了這個變量。然後用你的建議寫了一個if else語句。 – user25312

相關問題