处理内存中的png文件

Process png file in memory

我有一个 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.

抱歉,我把 Perl 美元符号误认为是 PHP,但界面和功能非常相似,希望您能适应。


你需要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");

?>

裁剪前:

之后: