我有一个perl程序,它将截图作为png抓取并将其插入变量中:
my $png_data = $s->chrome->render_content(format => 'png');
目前,我将$png_data
直接保存到磁盘,然后使用Imagemagick裁剪生成的文件。然后我将文件加载回一个变量,我将其作为BLOB写入数据库。
这显然是浪费。
不是将其保存到磁盘,然后将其从磁盘上读回来,我只想在内存中裁剪它,然后保存到数据库中。
我该如何做到这一点?
*更新* 这是我最终选择的解决方案,由于我对Imagemagick不太熟悉,因此需要花费一些时间来寻找和解决问题:
use Image::Magick;
# screenshot grabbed with WWW::Mechanize::Chrome;
# returned value of $png_data is a "blob" which can be saved in db or to file
my $png_data = $s->chrome->render_content(format => 'png');
# create object to process image
my $img = Image::Magick->new(magick=>'png');
# BlobToImage functions converts data to image that IM can process
$img->BlobToImage($png_data);
# do some processing of image
my $x = $img->Crop(geometry => "1028x5000+370+880");
print "$x" if "$x";
# now, the tricky part is saving the image by writing the $img back into a Perl string like this:
open (my $fh, '>', \$png_data) || die 'Could not write to string';
$img->Write(filename => $fh, quality => 100, depth => 4);
close $fh;
# The Write() method basically converts it back to a blob. Then you can store the $png_data string into the database in a BLOB column.
# NOTE: I'm not 100% sure if last line worked as I decided to save the image to a file. It seemed to work as I didn't get any errors but I did not verify that the data was actually in the database. But some variation of that last line should work if that one doesn't.
答案 0 :(得分:1)
抱歉,我误认为PHP的Perl美元符号,但界面和功能非常相似,希望你能适应。
您需要readImageBlob()
。第一块代码合成一个blob,第二个块将其裁剪并保存到磁盘:
<?php
// Synthesize blob by creating a radial gradient
$image = new \Imagick();
$image->newPseudoImage(300, 300, "radial-gradient:red-blue");
$image->setImageFormat("png");
$blob=$image->getImageBlob();
// Now crop the blob
$imgFromBlob=new \Imagick();
$imgFromBlob->readImageBlob($blob);
$imgFromBlob->cropImage(150,150,150,150);
$imgFromBlob->writeImage("result.png");
?>
裁剪前:
后: