今天在做项目的时候,需要把科室的ID添加在二维码上,使用Intervention/Image扩展包来实现这个功能,刚开始代码如下:
$image = Image::make($path.$keshiQrcode)->text('科室ID:'.$unique_id, 150, 10, function($font) {
$font->file(public_path('css/font.ttf'));
$font->size(20);
$font->align('center');
$font->valign('top');
});
$image->save($path.$filePath);这样生成的图片"科室ID" 就 会乱码,如下图:

解决方法需要把中文转码一下,实现代码如下:
$text = $this->to_unicode('科室ID:'.$unique_id);
$image = Image::make($path.$keshiQrcode)->text($text, 150, 10, function($font) {
$font->file(public_path('css/font.ttf'));
$font->size(20);
$font->align('center');
$font->valign('top');
});
$image->save($path.$filePath);
// to_unicode转码
function to_unicode($string)
{
$str = mb_convert_encoding($string, 'UCS-2', 'UTF-8');
$arrstr = str_split($str, 2);
$unistr = '';
foreach ($arrstr as $n) {
$dec = hexdec(bin2hex($n));
$unistr .= '&#' . $dec . ';';
}
return $unistr;
}