PHP直接将文件流转换为字符串

有时候不需要图片直接输出到浏览器,需要如下处理!

输出到浏览器

$qrCode = new QrCode();
$qrCode
    ->setText('Life is too short to be generating QR codes')
    ->setSize(300)
    ->setPadding(10)
    ->setErrorCorrection('high')
    ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
    ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
    ->setLabelFontSize(16)
    ->setImageType(QrCode::IMAGE_TYPE_PNG);
header('Content-Type: '.$qrCode->getContentType());

$qrCode->render();

转为字符串

$qrCode = new QrCode();
$qrCode
    ->setText('Life is too short to be generating QR codes')
    ->setSize(300)
    ->setPadding(10)
    ->setErrorCorrection('high')
    ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
    ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
    ->setLabelFontSize(16)
    ->setImageType(QrCode::IMAGE_TYPE_PNG);

// 开启缓冲区
ob_start ();
// 将图片写入内存
imagepng ($qrCode->render());
// 从内存中读取图片
$imageData = ob_get_contents();
// 关闭缓冲区
ob_end_clean ();
// 将内容写入cdn
$up_res = $this->upload_cdn($imageData);

dump($up_res);

或者再折腾成base64

$qrCode = new QrCode();
$qrCode
    ->setText('Life is too short to be generating QR codes')
    ->setSize(300)
    ->setPadding(10)
    ->setErrorCorrection('high')
    ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
    ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
    ->setLabelFontSize(16)
    ->setImageType(QrCode::IMAGE_TYPE_PNG);

// 开启缓存
ob_start();
imagepng($qrCode->render());
// 从内存中读取图片
$imageData = ob_get_contents();
// 关闭缓冲区
ob_end_clean ();
$imageDataBase64 = 'data:image/png;base64,' . base64_encode ($imageData);
echo "<img src='$imageDataBase64'/>";
posted @ 2019-03-14 14:28  TBHacker  阅读(3234)  评论(1编辑  收藏  举报