Search code examples
perlqr-code

How do I generate a QR code with a picture in Perl?


I want to generate a QR code with a picture in the center of QR code.

Is this possible to generate QR code with a picture inside the QR code with Perl? I tried different libraries, but still can't find the solution.

Here is a clear example, how it should look, QR code contains logo (picture) in the center:

I tried different Perl modules, and there is no possibility to customize QR code.


Solution

  • Using Image::Magick and Imager::QRCode you can pretty easily do this:

    use strict;
    use warnings;
    
    use Imager::QRCode;
    use Image::Magick;
    use Carp qw(croak);
    
    my $qrcode = Imager::QRCode->new(
        size          => 10,
        margin        => 0,
        version       => 1,
        level         => 'H',
        casesensitive => 1,
        lightcolor    => Imager::Color->new( 255, 255, 255 ),
        darkcolor     => Imager::Color->new( 0,   0,   0 )
    );
    
    my $qrcode_img = $qrcode->plot('foo bar baz');
    
    $qrcode_img->write( file => 'qrcode.gif' )
      or croak q{Failed to write QRCode: } . $qrcode_img->errstr;
    
    my $magick_qrcode = Image::Magick->new;
    $magick_qrcode->Read( filename => 'qrcode.gif' );
    
    my $embedded_image = Image::Magick->new;
    $embedded_image->Read( filename => 'embedded_image.png' );
    
    $magick_qrcode->Composite(
        image => $embedded_image,
        qw(compose StcAtop gravity Center)
    );
    
    $magick_qrcode->Write( filename => 'final_qrcode.png' );
    

    You can adjust the settings in the Imager::QRCode constructor to make the QRCode the colors and dimensions you're looking for as well.

    Result:

    enter image description here