1 回答

TA貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個(gè)贊
確實(shí),正如您所說,代碼中的以下行是錯(cuò)誤的:
$imageData = base64_encode(file_get_contents($image_p));
該$image_p變量不是文件名,而是由 imagecreatetruecolor 創(chuàng)建的資源。您首先必須使用 將其轉(zhuǎn)換為 jpeg 文件imagejpeg()。您可以避免在使用ob_*xxx*函數(shù)編碼為 base64 之前保存中間文件
ob_start();
imagejpeg($image_p);
$imageContent = ob_get_contents();
$imageData = base64_encode($imageContent);
ob_end_clean();
這行也有問題,同樣$image_p不是文件名:
$src = 'data: '.mime_content_type($image_p).';base64,'.$imageData;
在創(chuàng)建 jpeg 文件時(shí),只需將其替換為:
$src = 'data: image/jpeg;base64,'.$imageData;
為方便起見,這里是完整的工作腳本:
$filename = 'https://jooinn.com/images/nature-319.jpg'; // URL of the image
$percent = 0.25; // percentage of resize
// Content type
header('Content-type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
ob_start();
imagejpeg($image_p);
$imageContent = ob_get_contents();
$imageData = base64_encode($imageContent);
ob_end_clean();
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: image/jpeg;base64,'.$imageData;
// Echo out a sample image
echo '<img src="' . $src . '">';
imagedestroy($image_p);
- 1 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報(bào)