无法使用 PHP 在 PDF 中显示调整大小的图像

Failed to show the resized image in a PDF using PHP

我正在尝试从外部 URL 加载图像,然后调整其大小并以 PDF 格式显示。我目前正在尝试使用单个图像来实现它,但整个功能将在一个 foreach 循环中处理大量非常大的图像。

首先,我调整了图像的大小,然后获取图像的内容,应用 base65 编码,从中构建源字符串并将该字符串添加到我的 img src 标签中。这是我的代码 -

    $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
    $imageData = base64_encode(file_get_contents($image_p));

    // Format the image SRC:  data:{mime};base64,{data};
    $src = 'data: '.mime_content_type($image_p).';base64,'.$imageData;

    // Echo out a sample image
    echo '<img src="' . $src . '">';
    imagedestroy($image_p);

我认为问题出在这一行$imageData = base64_encode(file_get_contents($image_p));,我做错了。它与 URL's 一起工作得很好,但我怎样才能让它在此处用于调整大小的图像?例如,只要我不使用调整大小的图像,以下内容就可以完美运行 -

    $filename = 'https://jooinn.com/images/nature-319.jpg'; // URL of the image
    // Output
    $imageData = base64_encode(file_get_contents($filename));

    // Format the image SRC:  data:{mime};base64,{data};
    $src = 'data: '.mime_content_type($filename).';base64,'.$imageData;

    // Echo out a sample image
    echo '<img src="' . $src . '">';

确实如你所说,代码中的下面一行是错误的:

$imageData = base64_encode(file_get_contents($image_p));

$image_p 变量不是文件名,而是 imagecreatetruecolor 创建的资源。 您首先必须使用 imagejpeg() 将其转换为 jpeg 文件。 您可以使用 ob_*xxx* 函数

避免在编码为 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;

在创建 jpeg 文件时,您应该将其替换为:

$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);