我正在开发 SimpleQrcode Laravel。 我试图在数据库中以 rgba 格式(ajax)存储特定 id 的 qrcode 背景色的颜色,并将其作为变量调用以更改 qr 码的 bgcolor。我无法使用十六进制格式,因为 simpleqrcode 依赖项仅接受 rgba 格式。
所以我已将 rgba 存储在数据库中,当我将其调用到控制器时,它会向我显示错误:
遇到格式不正确的数值。
我进一步研究发现,当我从数据库中调用颜色时,它默认带有引号,我尝试用
str_replace()
替换它,但这不起作用。
这是我的代码:
public function qrcode($id){
$article = Article::find($id);
$rgba = $article->bgcolor;
$html = str_replace('"', '', $rgba);
$image_path = \QrCode::format('png')
// ->merge('../storage/app/public/'.$article->image, .15, true)
->size(200)
->backgroundColor($html)
->errorCorrection('H')
->generate('127.0.0.1:8000/articles/'.$article->id , '../public/Qrcodes'.$article->image);
// dd($article->bgcolor);
// $image = '../public/'.$article->image;
return view('articles.modify_qrcode', compact('article'));
有人告诉我更新作曲家。我已经更新了
根据您的评论;
dd($html); result: "135, 56, 56"
你编码
$rgba = $article->bgcolor;
$html = str_replace('"', '', $rgba);
将使用字符串值
$html
创建变量 "135,56,56"
但是您需要 3 个整数变量 $red
、$green
和 $blue
,因为 backgroundColor(int $red, int $green, int $blue, ?int $alpha = null)
分别采用 3 种颜色。
你能做的是;
$article = Article::find($id);
list($red, $green, $blue) = array_map('intval', explode(',', $article->bgcolor));
$image_path = \QrCode::format('png')
->size(200)
->backgroundColor($red, $green, $blue)
->errorCorrection('H')
->generate('127.0.0.1:8000/articles/'.$article->id , '../public/Qrcodes'.$article->image);
说明:
explode(',', $article->bgcolor)
将把 string "135, 56, 56"
转换为 string 数组:["123"
, "56"
和 "56"
]array_map('intval', [])
将迭代 string 数组,将它们转换为 int 数组:["123"
, "56"
和 "56"
] 将变为 [123
, 56
和 56
]
]list($red, $green, $blue)
会将 array 值分配给每个变量; $red
、$green
和 $blue
解析 RBG 或 RBGA 字符串的最佳、最直接的方法是使用
sscanf()
。这不仅会从严格格式化的字符串中提取所需的值,还会忽略空格,允许存在 alpha 值(可选),并将所有值转换为指定的整数或浮点类型。
令人担忧的是,应用程序中
backgroundColor()
的方法签名接收 alpha
参数作为可为 null 的整数,但它当然应该接受浮点类型值。
对于您的精确场景,您可以在不声明单个变量的情况下实现调用,然后只需将整数的平面数组解压为
backgroundColor()
的方法参数:
->backgroundColor(
...sscanf(
$article->bgcolor,
'%d,%d,%d,%d'
)
)
这是一个带有一些测试用例的脚本,向您展示它是如何工作的。 (注意
%f
)演示
$tests = [
'12, 34, 56',
'233, 0, 0, 1',
'99, 68, 135',
'0, 0, 0, 0.31',
];
foreach ($tests as $test) {
unset($r, $g, $b, $a);
sscanf($test, '%d,%d,%d,%f', $r, $g, $b, $a);
var_dump($r, $g, $b, $a);
echo "\n";
}
输出:
int(12)
int(34)
int(56)
NULL
int(233)
int(0)
int(0)
float(1)
int(99)
int(68)
int(135)
NULL
int(0)
int(0)
int(0)
float(0.31)