在发送给客户端之前在 PHP 中调整 BLOB 图像的大小

Resizing a BLOB image in PHP before sending to client

我有一张图像,我正在从数据库中以 BLOB 形式获取图像,但是我正在向客户端发送全尺寸图像,然后在他们这边调整大小。图片可能会变得很大,所以我想在将图片发送给客户端之前调整图片大小。

我目前有以下代码:

if (!empty($row['img'])) {$img = $row['img'];}
$width = imagesx(imagecreatefromstring($img));
$height = imagesy(imagecreatefromstring($img));
$resizer = $width/200;
$newHeight = floor($height/$resizer);
$news = $news . "<div class='newsItem' style='min-height:".$newHeight."px;'>";
if (isset($img)) {$news = $news . "<img src='data:image/jpeg;base64,".base64_encode($img)."' width='200' height='".$newHeight."'>";}
$news = $news . "<h2>".$title."</h2><hr class='newsHr'><span>".$text."</span></div>";

我可以使用哪些函数来调整 $img 的大小?

这应该适合你。示例取自 Manual

<?php    
// Load
    $thumb = imagecreatetruecolor($newwidth, $newheight);
    $source = imagecreatefromjpeg($filename);

    // Resize
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    // Output
    imagejpeg($thumb);
?>

将 BLOB mage 转换为文件使用。

file_put_contents('/path/to/new/file_name', $my_blob);

和我一起工作!

<?php
function resize($blobImage, $toWidth, $toHeight) {

  $gdImage = imagecreatefromstring($blobImage);
  if ($gdImage) {
     list($width, $height) = getimagesizefromstring($blobImage);
     $gdRender = imagecreatetruecolor($toWidth, $toHeight);
     $colorBgAlpha = imagecolorallocatealpha($gdRender, 0, 0, 0, 127);
     imagecolortransparent($gdRender, $colorBgAlpha);
     imagefill($gdRender, 0, 0, $colorBgAlpha);
     imagecopyresampled($gdRender, $gdImage, 0, 0, 0, 0, $toWidth, $toHeight, $width, $height);
     imagetruecolortopalette($gdRender, false, 255);
     imagesavealpha($gdRender, true);
     ob_start();
     imagepng($gdRender);
     $imageContents = ob_get_contents();
     ob_end_clean();
     imagedestroy($gdRender);
     imagedestroy($gdImage);
    return $imageContents;
  }
}

$image = '<img src="data:image/jpeg;base64,'. base64_encode( resize($row['image_data'], 45, 45) ) . '" />';