PDF to JPG Imagic page selection - php

Loads of answers on how to do it for a command line
convert /path/to/file/file.pdf[3] output.jpg
great... but what if I am using in memory processing, I am generating PDF with PDFlib and then output its buffer to a function that I want to generate jpg preview of selected page. How? My code :
[...]
$buf = $pdf->get_buffer();
//$buff is just a PDF stored in a string now.
$im = new Imagick();
$im->readimageblob($buf);
$im->setImageFormat("jpg");
$im->setimagecompressionquality(60);
$len = strlen($im);
header("Content-type: image/jpeg");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=test.jpg");
echo $im;
This creates a jpeg but always returns last page of the PDF. I want to be able to choose which one will be converted. Is it doable without saving temporary files and using command line (exec('convert /path/to/file/file.pdf[3] output.jpg')) syntax?
Let me add that I tried
$im->readimageblob($buf[2]);
and it did not work :)

For the ones who is still searching for solution of reading specific page number from blob, please check this question Creating array populated by images from a PDF using PHP and ImageMagick
$img_array = array();
$im = new imagick();
$im->setResolution(150,150);
$im->readImageBlob($pdf_in);
$num_pages = $im->getNumberImages();
for($i = 0;$i < $num_pages; $i++)
{
$im->setIteratorIndex($i);
$im->setImageFormat('jpeg');
$img_array[$i] = $im->getImageBlob();
}
$im->destroy();

I'm loading the PDF binary into memory from Amazon S3 and then selecting the specific page I want using setIteratorIndex() followed by getImage()
function get_image_from_pdf($pdf_bytes, $page_num){
$im = new \Imagick();
$im->setResolution(150, 150);
$im->readImageBlob($pdf_bytes);
$im->setIteratorIndex($page_num);
$im = $im->getImage();
$im->setImageFormat('png');
return $im->getImageBlob();
}

version 3.0.1
being on the last image or first image in imagic object
$image_obj = new Imagick("test.pdf"); then you on last image in $image_obj
if you use
fp_pdf = fopen("test.pdf", 'rb');
$image_obj = new Imagick();
$image_obj -> readImageFile($fp_pdf);
then you on the first image in $image_obj
In second case to switch to last image you can do
fp_pdf = fopen("test.pdf", 'rb');
$image_obj = new Imagick();
$image_obj -> readImageFile($fp_pdf,2); // 2 can be any positive number?
then you on the last image in $image_obj
echo $image_obj->getNumberImages() // Returns the number of images in the object
then
if ($image_obj->hadPreviousImage)
$image_obj->previousImage() //Switch to the previous image in the object
}
or
if ($image_obj->hasNextImage()) {
$image_obj->nextImage()) //Switch to the next image in the object
}
e.g. if you have 6 images total and you need 4th then do from the end
$image_obj->previousImage()
$image_obj->previousImage()
$image_obj->setImageFormat("png");
header("Content-Type: image/png");
echo $image_obj;
EDIT: Another find is that you can
foreach($image_obj as $slides) {
echo "<br>".$Obj_img->getImageWidth();
//or wehatever you need to do.
}
EDIT 2: Very simple solution would be to use this function $image_obj->setIteratorIndex(4) count starts with zero.

It's not good news unfortunately, but I can definitively say that, as of time of writing, the ImageMagick (and PHP libraries) don't support the page notation that you're trying to use. (For people from the future finding this: I'm checking php-imagick-3.0.1 and imagemagick-6.6.0.4).
I'm trying to do the exact same thing as you, and I've just spent the last few hours trawling through the source, trying to figure out what it does and how it gets the pages, and it looks like it simply won't use it when reading from a stream (ie. the readBlob() call).
As such, I'm just going to be putting it in a temporary file and reading it from there instead. Not as elegant, but it'll work.

Related

How to processing an image downloaded from AWS S3 with Laravel 5?

I want download an image from AWS S3 and process it with php. I am using "imagecreatefromjpeg" and "getimagesize" to process my image but it seem that
Storage::disk('s3')->get(imageUrlonS3);
retrieve the image in binary and is giving me errors. This is my code:
function createSlices($imagePath) {
//create transform driver object
$im = imagecreatefromjpeg($imagePath);
$sizeArray = getimagesize($imagePath);
//Set the Image dimensions
$imageWidth = $sizeArray[0];
$imageHeight = $sizeArray[1];
//See how many zoom levels are required for the width and height
$widthLog = ceil(log($imageWidth/256,2));
$heightLog = ceil(log($imageHeight/256,2));
//more code here to slice the image
.
.
.
.
}
// ex: https://s3-us-west-2.amazonaws.com/bucketname/image.jpg
$content = Storage::disk('s3')->get(imageUrlonS3);
createSlices($content);
What am I missing here ?
Thanks
I think you are right in your question what the problem is - the get method returns the source of the image of itself, not the location of the image. When you pass that to createSlices, you're passing the binary data, not its file path. Inside of createSlices you call imagecreatefromjpeg, which expects a file path, not the image itself.
If this indeed the case, you should be able to use createimagefromstring instead of createimagefromjpeg and getimagesizefromstring instead of getimagesize. The functions createimagefromstring and getimagesizefromstring each expects the binary string of the image, which I believe is what you have.
Here's the relevant documentation:
createimagefromstring - http://php.net/manual/en/function.imagecreatefromstring.php
getimagesizefromstring - http://php.net/manual/en/function.getimagesizefromstring.php
Resulting code might look something like this:
function createSlices($imageData) {
$im = imagecreatefromstring($imageData);
$sizeArray = getimagesizefromstring($imageData);
//Everything else can probably be the same
.
.
.
.
}
$contents = Storage::disk('s3')->get($imageUrlOnS3);
createSlices($contents);
Please note I haven't tested this, but I believe from what I can see in your question and what I read in the documentation that this might just do it.

Binary image data not converting into image

$data = b"""
\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x18\x00h\x03\x00\x00\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00\x18\x00\x00\x00\x00\x00\x00\x00\x00\x00d\x00\x00\x00d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00X;ÿ%\x1Cï\t$÷\x07\x11ÿ$\x16ÿ\x11\x1Eü\x13\x19ôçó÷ÈÈø\x07\fû#\x1Fÿ\e\x15ÿ\x0E\x17û,$ú\x13\x17èAHÿODÿ%\x1Dÿ\t\x11ÿ\x18\x0Eú)\x04ô\x1C\n
ñ-\x1AóïÝÿµ±ý\f\tï\x1F\x07ï \x07ñ\x19\x11ø%\tÿ(\x1AÿTOÿFLó!\x1Cô21ý•›þ©÷—–þ““÷üôÿêåÿŽÿ£‘ü¦žõƒ“ý'\x1Dó\e\x1DóISôELõ\e\x0FñO?þìüÿüÿ÷ñüÿêüÿúþÿûþÿóúÿÿúÿøÿõÒíÿ,)ô\e\e÷ORú;Mø\x13\fýN4ÿðõÿÿûýÿüÿÿÿéÿþ÷üÿïÿÿîÿþÿþþþÛãÿ*\eÿ$\x15ÿWLü0Aü\r\rùL;üòùÿÿýþÏ°™’f\x1F•`.a+•g1ØÌ°ÿÿùÞáÿ$!ò\x15\x16ôACÿxÿYRùuëõü÷ÿþÿÎ¥„~6\x00C\x01#\x03‹3\x04àϨÿÿøëåübkëXañ}ÿÿÿòø÷ÿÿûÿÿÿéöïþͤ‹‹?\x00˜S\x03”M\x039\x11ÍÓ°øöõÿþûøùÿÿþýÿÿò‹}ÿLYûmoýøôÿÿþüǬl~A\x00‡D\x00E\x00z7\x06æØ£öÿéìîÿhe÷Saúˆ~ÿBFø\x00\fèD>÷ýüÿÿÿøÔ¨›”[\x1Ee*£c-•Z3ëÍÂÿÿôëãÿ,\x12ø\x06\fóFOöIIÿ\x12\x0FøM9þöþóÿÿôÿöÿÿþôÿøÿÿøÿÿüùý÷ÿûÿùìêÿ:\x14ÿ\x1F\x16ÿKRý?Gþ\x18\x1CñJBúîúÿöÿòúÿþÿÿþÿúýÿÿñýÿþñúýøÿùçóÿ7,ç\x1C ñCMþJAÿ&\x17ô6(ü”ŽÿŸ™ÿŸý üþûöçåñŸÿ˜•øŸ˜ÿŒÿ,&é&\x1AðYNÿQIÿ+\x1Cù\x16\x14ÿ\v\x11ø\t\tï\x06\fù\x0E\x0EöÑ÷ü©Ãÿ\x02\x00ô\x08\rò\f\x06í\n
\x0Fô\x18\x18ÿ&\x15ùXOÿ;Aþ"\x1Eé\x1C\x1Eø\x19 ó'\x1Aò\e\x13ô3#ýææÿµ°ÿ \x12ì+\x1Eö5\eÿ\x19\eõ\e ÿ$\x1DðFLÿýüÿÿþúøøÿøÿþÿþýîþÿíõÿÿÿóÿÿùêýÿúÿÿÿõÿöþ÷øÿþÿÿøûùÿ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
"""
The above data is image binary data.
I am converting the above binary data into actual image. I have written the code as follows:
Note: I am using image intervention package - Laravel and I have written the code for displaying favicons of banks(Financial Institutions). This api is provided by Yodlee Interactive.
$img = Image::make($data)->save('images/favicons/icon1.jpg');
return $img->response();
OR
$img = Image::make($data)->save('images/favicons/icon1.ico');
return $img->response();
When I am executing the code, I am getting following error,
NotReadableException in Decoder.php line 91:
Unable to init from given binary data.
The response you receive is not byteArray, it is string so you probably have to first convert into byte array and then into image.
This should give you some pointers to start.
<?php
//Here write your code to get $byte_array
$data = base64_decode($byte_array);
$im = imagecreatefromstring($data);
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
?>
Or you can probably refer to these links.
Converting a byte array into an image using PHP and HTML
http://www.zoubi.me/blog/php-get-image-byte-array
Please use the following sample code for getting the captcha image.
$bytes = array(Paste byte-array from Yodlee-API response here Ex: 0,2,3,4,1,1,1);
$byteArray = implode(array_map("chr", $bytes));
$imgData =base64_encode($byteArray);
$img = "<img src= 'data:image/jpeg;base64,$imgData' />";
print($img);
Hope this helps.
Regards,
Krithik N

Image from database into PDF using FPDF

I have an image that is sent from an iPad app to an SQL database. I can retrieve this image and display in a web page using the following php:
$img = base64_encode($row['photoData']);
echo "<img src=\"data:image/jpg;charset=utf8;base64, $img\"/>";
This displays fine. What I want to do now is put this image into a PDF document using FPDF however I am struggling to do this.
This:
$img = base64_encode($row['photoData']);
$pdf->Image($img);
give this error:
FPDF error: Image file has no extension and no type was specified:
So I tried this (although I realise I will then have to look at how to get the size of the image sorted):
$pdf->Image($img, 20, 20, 20, 20 'JPG');
which give me:
FPDF error: Missing or incorrect image file:
What is the correct way to do this?
Or would it be easier to temporarily save the image to the server and then place the saved image into the PDFdoc?
As mentioned in the comments above this is possible by using a stream ("data url") to hand over the image data to the fpdf library without writing physical files to disk:
<?php
// load the 'fpdf' extension
require('fpdf.php');
// just for demonstration purpose, the OP gets the content from a database instead
$h_img = fopen('img.jpg', "rb");
$img = fread($h_img, filesize('img.jpg'));
fclose($h_img);
// prepare a base64 encoded "data url"
$pic = 'data://text/plain;base64,' . base64_encode($img);
// extract dimensions from image
$info = getimagesize($pic);
// create a simple pdf document to prove this is very well possible:
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello Image!');
$pdf->Image($pic, 10, 30, $info[0], $info[1], 'jpg');
$pdf->Output();
If this is a good advice is another question, this is merely meant to prove that this is possible...
According to the Docs FPDF::Image accepts a filename as the first argument, not a binary blob.
If you want to use FPDF specifically, save the image to a temporary file first, and then pass that to FPDF::Image.
To do that, something like this should work:
$tmpFile = tempnam(sys_get_temp_dir(), 'fpdfimg');
if (file_put_contents($tmpFile, $row['photoData'])) {
$fpdf->Image($tmpFile);
// save/display image
unlink($tmpFile);
}
Alternatively, if you want to just serve the image as a PDF (with no other content) you could use Imagick:
$im = new \Imagick();
$im->readImageBlob($row['photoData']);
$im->setImageFormat('pdf');
header('Content-Type: application/pdf');
echo $im;
Since FPDF cannot use base64 data to produce images on the PDF, I would recommend saving the file to the disk permanently as opposed to writing a temp file for every PDF operation.
This will save you a lot of I/O overhead.
Assuming your table has unique photo_id or photo_name to accompany photoData then you can use something like this to create your images and use them in FPDF.
I will also assume you have a last_update and photo_extension column.
<?php
$path = '/path/to/fpdf/images/';
$filename = $row['photo_id'].'.'.$row['photo_extension'];
$filepath = $path.$filename;
// If a physical file is not available then create it
// If the DB data is fresher than the file then make a new file
if(!is_file($filepath) || strtotime($row['last_update']) > filemtime($filepath))
{
$result = file_put_contents($filepath, $row['photoData']);
if($result === FALSE)
{
die(__FILE__.'<br>Error - Line #'.__LINE__.': Could not create '.$filepath);
}
}
$pdf->Image($filepath);
If you plan on updating the photoData which is stored in your DB then you will have to make sure to also have a timestamp column and compare that timestamp against the filemtime($filepath) of the image on your disk.
Another solution for this ;)
Make a new php by copying and pasting this (piece of fpdf's code edited):
require('fpdf.php');
class DATAIMAGE extends FPDF
{
protected function _parsedata($file)
{
// Extract info from a JPEG file
$a = getimagesizefromstring($file);
if(!$a)
$this->Error('Missing or incorrect image file: '.$file);
if($a[2]!=2)
$this->Error('Not a JPEG file: '.$file);
if(!isset($a['channels']) || $a['channels']==3)
$colspace = 'DeviceRGB';
elseif($a['channels']==4)
$colspace = 'DeviceCMYK';
else
$colspace = 'DeviceGray';
$bpc = isset($a['bits']) ? $a['bits'] : 8;
return array('w'=>$a[0], 'h'=>$a[1], 'cs'=>$colspace, 'bpc'=>$bpc, 'f'=>'DCTDecode', 'data'=>$file);
}
}
Then call this php instead of fpdf.php in your main php.
You'll now be able to display an image simply by adding 'data' to the end of the function:
$pdf->Image($mysqlrow["blob"],0,0,40,0,'data');

Merging animated Gif into background image

I'm trying to merge an animated gif into a static jpeg as a background, this is being generated by html canvas and a file upload that the user uploads. I had it working great with imagemagick command line
exec("convert ".$_paths['images_dir'].$fname.".gif \( gif/cleared_dance".$dance.".gif -resize '80%' -repage 0x0-10+$imgHeight\! \) -coalesce -delete 0 -deconstruct -loop 0 ".$_paths['images_dir'].$fname.".gif");
this was taking about 15~ seconds to process which was acceptable, but then I found out I can't use the exec command and must use Imagick API, I was eventually able to recreate the process using the following code:
$data = $_POST["imgData"];
$dance = $_POST["dancer"]+1;
$spriteLeft = $_POST['left'];
$spriteTop = $_POST['top'];
$scale = $_POST['scale'];
$canvas = new Imagick();
$data = str_replace("data:image/png;base64,", "",$data);
$data = base64_decode($data);
$canvas->readImageBlob($data);
$fname = 'tmp_'.uniqid();
$gif = new Imagick();
$gif->readImage('gif/cleared_dance'.$dance.'.gif');
do {
$canvas->addImage($gif);
} while ($gif->nextImage());
foreach($canvas as $frame){
if($frame->getIteratorIndex() != 0){
$page = $frame->getImagePage();
$frame->setImagePage(200,200,$page['x']+$spriteLeft,$page['y']+$spriteTop);
}
}
This code takes about 5 seconds which is great but their is a blank frame in the gif when it loops that was super annoying so i added this after:
$canvas->setIteratorIndex(0);
$canvas->removeImage();
$canvas = $canvas->deconstructImages();
$canvas->writeImages('tmp/'.$fname.'.gif', true);
This takes out the blank frame, but adds about 20 - 30 seconds of processing. Am I doing something wrong, I've played around a good bit with the order of the code and trying different approaches. Is there a way to get the processing time back under 20 seconds like it was with the command line?
Your code is quite odd. Why are you setting the format of the Imagick object that is going to contain an animated gif to JPG? Why are you fiddling with the image page after you composited the image?
I'm pretty sure you want your code to look a lot more like
$static = new Imagick();
//$static->readImage("./testFile.png");
$inputGif->readImageBlob($data);
$inputGif = new Imagick();
//$inputGif->readImage('./testGif.gif');
$inputGif->readImage('gif/cleared_dance'.$dance.'.gif');
$gifFrames = $inputGif->coalesceImages();
$outputGif = new Imagick();
$outputGif->setFormat('gif');
foreach ($gifFrames as $gifFrame) {
$frame = clone $static;
$frame->compositeimage(
$gifFrame,
Imagick::COMPOSITE_OVER, // or maybe \Imagick::COMPOSITE_ATOP,
0, 0 // Set the offset here if you don't want the gif in the top left corner.
);
$outputGif->addImage($frame);
}
$outputGif->setImageIterations(0); //loop forever
$outputGif->deconstructImages();
$outputGif->writeImages("./outso.gif", true);

Remove background after comparing two images with Imagick

i'm new using imagick with php and i have a problem:
I'm comparing two images with the compareImages() function. I'm using the same code as in the documentation page:
<?php
$image1 = new imagick("image1.png");
$image2 = new imagick("image2.png");
$result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);
$result[0]->setImageFormat("png");
header("Content-Type: image/png");
echo $result[0];
?>
This code is working right, but the result image has a background with the original image with a bit of opacity.
I've been searching and I found the result that I want but with imagemagick commands:
http://www.imagemagick.org/Usage/compare/
My current result is like the image of the first command ("compare bag_frame1.gif bag_frame2.gif compare.gif") and I want a result like the shown in this command:
compare bag_frame1.gif bag_frame2.gif \
-compose Src compare_src.gif
Is there any way of doing this with the compareImages() function of imagick?
Thanks
You'll need to use Imagick::SetOption before reading the first image.
<?php
$image1 = new imagick(); // Init empty object
$image2 = new imagick("image2.png");
// Set Lowlight (resulting background) to transparent, not "original image with a bit of opacity"
$image1->setOption('lowlight-color','transparent');
// Switch the default compose operator to Src, like in example
$image1->setOption('compose', 'Src');
// Now read image
$image1->readImage("image1.png");
// Result will not have a background
$result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);

Categories