Search code examples
phplaravelqr-codetext-parsingrgba

Parse RGB string to integers and avoid "non-well formed numeric value encountered" in Laravel SimpleQrcode


I am working on SimpleQrcode Laravel. I'm trying to store color in rgba format(ajax) in database for a specific id's qrcode's background color and calling it as a variable to change the qr-code's bgcolor. I cannot use hex format because simpleqrcode dependency only accepts rgba format.

So I have stored rgba in database and when I call it to the controller it shows me the error:

A non well formed numeric value encountered.

Further I researched that when I call colors from database it comes with quotations by default and I tried to replace it with str_replace() but that didn't work.

This is my code:

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'));

error

error

Somebody told me to update composer. I have already updated it.


Solution

  • Based on your comment; dd($html); result: "135, 56, 56"

    You code

    $rgba = $article->bgcolor;
    $html = str_replace('"', '', $rgba);
    

    Will create the variable $html with the string value "135,56,56" But you need 3 integer variables $red, $green and $blue since backgroundColor(int $red, int $green, int $blue, ?int $alpha = null) take 3 colors separately.

    What you can do is;

    $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);
    
    

    Explanation:

    • explode(',', $article->bgcolor) Will transform the string "135, 56, 56" into an array of string: ["123", "56" and "56"]
    • array_map('intval', []) Will iterate through the array of string to cast them into an array of int : ["123", "56" and "56"] will become [123, 56 and 56]
    • list($red, $green, $blue) will assign the array values into each variables; $red, $green and $blue