Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing binary data in the __DATA__ handle

Tags:

perl

In a module I need an image data (BMP) for some Imager::Search operation. The following works,

my $pattern = Imager::Search::Pattern->new(
     driver => 'Imager::Search::Driver::BMP24',
     file   => 'test.bmp', #load the image from a file
);

The image (test.bmp) is constant for me, so want store it directly in the source code as

my $image = ... the image data ... ;

or in the __DATA__ section.

What is an recommended method storing binary data (such test.bmp) in the __DATA__? (2.3kb).

like image 508
kobame Avatar asked Dec 11 '22 00:12

kobame


1 Answers

You probably wouldn't want to deal with the headaches of storing raw binary data in a source file, but that doesn't mean that you can't still use a solution that stores the image in the __DATA__ segment. You would just encode it in a plain-text format first, such as Base64.

Mojolicious is an example of this sort of thing. With Mojolicious::Lite it is possible to embed templates and other static content in segments within the __DATA__ section. And Base64-encoded data is one possibility, as documented in Mojolicious::Guides::Tutorial#Static Files.

The point to this is to demonstrate that this type of approach is sometimes used. If you wanted to implement a solution that uses this approach, you would use the core Perl module MIME::Base64. Here's an example where some arbitrary plain old text is stored in Base64 format, and retrieved for use. However, since Base64 encoding can be used on binary data, this example could be adapted to store an image instead.

use MIME::Base64;

my $foo = do {
    local $/ = undef;
    decode_base64(<DATA>);
};

print "<<$foo>>\n";

__DATA__
SnVzdCBhbm90aGVyClBlcmwgaGFja2VyLA==
like image 190
DavidO Avatar answered Jan 04 '23 17:01

DavidO