简体   繁体   English

使用 Perl 的 Image::Magick 创建带有文本的图像

[英]Creating an image with text using Perl's Image::Magick

I am working on some examples for a lunch-n-learn talking about HTTP context headers and some of the things they are used for.我正在研究一些关于 HTTP 上下文标头及其用途的午餐学习示例。 I figured to add some flare into things, to create an image with Perl's Image::Magick.我想在事物中添加一些耀斑,用 Perl 的 Image::Magick 创建一个图像。

Thanks to a comment on this original post I have learned the problem is a missing Content-Length.感谢对这篇原始帖子的评论,我了解到问题是缺少 Content-Length。 How do I get the correct context length from the image?如何从图像中获取正确的上下文长度?

PS I tweaked the Content-Type to make type capital. PS 我调整了 Content-Type 以使类型大写。

#!/perl/bin/perl.exe

use Image::Magick;

$image = Image::Magick->new;
$image->Set(size=>'100x100');
$image->ReadImage('canvas:white');
$image->Set('pixel[49,49]'=>'red');

$text = 'Works like magick!';
$image->Annotate(font=>'kai.ttf', pointsize=>40, fill=>'green', text=>$text);

print "Content-Type: image/png\n\n";
binmode STDOUT;
$image->Write('png:-');

Why not Mojolicious ( An amazing real-time web framework )?为什么不 Mojolicious(一个了不起的实时 Web 框架)?

use Mojolicious::Lite;

use Image::Magick;

get '/' => sub {
  my $c = shift;

  ...

  $c->render( data => $image->ImageToBlob( magick => 'png' ), format => 'png' );
};

app->start;

run it with perl my_script.pl daemon使用perl my_script.pl daemon运行它

And open in browser localhost:3000并在浏览器中打开 localhost:3000

Or fix for original code:或修复原始代码:

#!/usr/bin/env perl

use strict;
use warnings;

use Image::Magick;

my $image = Image::Magick->new;
$image->Set( size => '200x200' );
$image->ReadImage( 'canvas:white' );
$image->Set( 'pixel[49,49]' => 'red' );

$image->Annotate(
    font      => 'kai.ttf',
    pointsize => 22,
    fill      => 'green',
    text      => 'Works like magick!',
    gravity   => 'northwest',
);

my $img_size;
my $img_data = $image->ImageToBlob( magick => 'png' );

{
    use bytes;
    $img_size = length $img_data;
}

binmode STDOUT;
print <<EOD;
Content-Type: image/png
Content-Length: $img_size

$img_data
EOD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM