【问题标题】:Resizing a BLOB image in PHP before sending to client在发送到客户端之前在 PHP 中调整 BLOB 图像的大小
【发布时间】:2015-07-28 11:01:09
【问题描述】:

我有一个图像,我从数据库中获取一个 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 的大小?

【问题讨论】:

    标签: php html mysql blob


    【解决方案1】:

    这应该适合你。取自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 图像转换为文件使用。

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

    【讨论】:

    • 嘿,这里有点困惑。 $filename 会引用什么?
    • $filename 是对您在服务器上的图像文件的引用。请参阅更新的答案以了解如何将 BLOB 转换为图像文件。
    • 我有同样的(非常老的)问题,即调整 blob 的大小。但是,这里的答案似乎是从文件系统而不是从 blob 调整图像文件的大小。这些函数是否也可以直接在 blob 中工作,还是需要文件?
    【解决方案2】:

    和我一起工作!

    <?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) ) . '" />';
    

    【讨论】:

      猜你喜欢
      • 2017-10-30
      • 2013-11-29
      • 2018-09-20
      • 2015-09-22
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      相关资源
      最近更新 更多