2014-01-14 68 views
1
  • 我正在從一個網址獲取PNG圖像,如下所示。
  • 我想將PNG圖像轉換爲JPEG,而不用PHP保存磁盤。
  • 最後,我想將JPEG圖像分配給$ content_jpg變量。將圖像格式PNG轉換爲JPEG,而不保存到磁盤 - PHP

    $url = 'http://www.example.com/image.png'; 
    $content_png = file_get_contents($url); 
    
    $content_jpg=; 
    
+1

你說的意思是「將圖像轉換?如果你想編輯圖像,你不需要保存圖像,只需輸出圖像。請參閱:http://us1.php.net/manual/en/ref.image.php –

+1

我在Oxwall中這樣做。轉換後我會將jpg圖像保存到系統生成的位置。但我想知道在不寫入磁盤的情況下將png圖像內容($ content_png)轉換爲jpg的可能性。這可能是C#作爲我發現的教程。 – Duli

+0

@Josh,我想將圖像的格式從PNG更改爲JPEG。這就是我想通過轉換圖像而不是編輯圖像的意思。謝謝 – Duli

回答

4

您要使用的gd library這一點。這是一個例子,它將採用PNG圖像並輸出一個JPEG圖像。如果圖像是透明的,透明度將被渲染爲白色。

<?php 

$file = "myimage.png"; 

$image = imagecreatefrompng($file); 
$bg = imagecreatetruecolor(imagesx($image), imagesy($image)); 

imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255)); 
imagealphablending($bg, TRUE); 
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image)); 
imagedestroy($image); 

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

$quality = 50; 
imagejpeg($bg); 
imagedestroy($bg); 

?> 
+0

函數imagecreatefrompng也可以接受URL。所以我已經通過url來代替文件。此代碼按預期工作,並將JPEG文件發送到瀏覽器。非常感謝喬希。 – Duli

5

簡化的答案是,

// PNG image url 
$url = 'http://www.example.com/image.png'; 

// Create image from web image url 
$image = imagecreatefrompng($url); 

// Start output buffer 
ob_start(); 

// Convert image 
imagejpeg($image, NULL,100); 
imagedestroy($image); 

// Assign JPEG image content from output buffer 
$content_jpg = ob_get_clean(); 
相關問題