PHP library object error - php

I am having an issue with imagick php library.
I am doing a recursive search in my file system and look for any pdf files.
$it = new RecursiveDirectoryIterator("/test/project");
$display = Array ('pdf');
foreach(new RecursiveIteratorIterator($it) as $file){
if (in_array(strtolower(array_pop(explode('.', $file))), $display))
{
if(file_exists($file)){
echo $file; //this would echo /test/project/test1.pdf
$im = new Imagick($file);
$im->setImageFormat("jpg");
file_put_contents('test.txt', $im);
}
}
}
However, I am getting an error saying
Fatal error: Uncaught exception 'ImagickException' with message 'Can not process empty Imagick object' in /test.php:57
Stack trace:
#0 /test.php(57): Imagick->setimageformat('jpg')
#1 {main}
thrown in /test.php on line 57
line 57 is $im->setImageFormat("jpg");
However, if I replace my $im = new Imagick($file) with $im = new Imagick('/test/project/test1.pdf'), the error is gone.
I don't know why this is happening. Can someone give me a hint for this issue? Thanks so much

According to this, the .jpg files' format is JPEG.
Note 1:
Your $file variable is an object SplFileInfo, but you are using it always like a string. Use RecursiveDirectoryIterator::CURRENT_AS_PATHNAME flag in RecursiveDirectoryIterator's constructor, to be a real string.
Note 2:
You can filter the iterator entries with RegexIterator, f.ex.: new RegexIterator($recursiveIteratorIterator, '/\.pdf$/') (after Note 1). Or, you can use GlobIterator too for searching only pdf files.

As #pozs pointed out
Note 1: Your $file variable is an object SplFileInfo, but you are
using it always like a string.
Here's a code snippet which gets you the filename as string and has an optimized method to get the file extension:
<?php
$display = array ('pdf');
$directoryIterator = new RecursiveDirectoryIterator('./test/project');
// The key of the iterator is a string with the filename
foreach (new RecursiveIteratorIterator($directoryIterator) as $fileName => $file) {
// Optimized method to get the file extension
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
if (in_array(strtolower($fileExtension), $display)) {
if(file_exists($fileName)){
echo "{$fileName}\n";
// Just do what you want with Imagick here
}
}

Maybe try this approach from : PDF to JPG conversion using PHP
$fp_pdf = fopen($pdf, 'rb');
$img = new imagick();
$img->readImageFile($fp_pdf);
It also seems from reading other posts that GhostScript is faster?

Related

Error in creating pdf file using google drive sdk

I am using google drive sdk for uploading files and also I think i can possibly create pdf file on it - so I tweak the code. So in my code, I generate HTML text format to be used as content for the PDF to be created in google drive.
this is a snip-it of my code.
$subcontent = "<h1>Hello World</h1><p>some text here</p>";
$file = new Google_DriveFile();
....
$mkFile = $this->_service->files->insert($file, array('data' => $subcontent));
$createdFile = $fileupload->nextChunk($mkFile, $subcontent); // I got error on this line
$this->_service->files->trash( $createdFile['id'] );
...
when I run the code I got an error based the comment I put in my code above:
Catchable fatal error: Argument 1 passed to Google_MediaFileUpload::nextChunk() must be an instance of Google_HttpRequest, array given, called in /home/site/public_html/mywp/wp-content/plugins/mycustomplugin/functions.php on line 689 and defined in /home/site/public_html/mywp/wp-content/plugins/mycustomplugin/gdwpm-api/service/Google_MediaFileUpload.php on line 212
I have no idea what should be the value in the 2nd parameter in nextChunk, in the original code it goes like this:
.....
$handle = fopen($path, "rb");
while (!$status && !feof($handle)) {
$max = false;
for ($i=1; $i<=$max_retries; $i++) {
$chunked = fread($handle, $chunkSize);
if ($chunked) {
$createdFile = $fileupload->nextChunk($mkFile, $chunked);
break;
}elseif($i == $max_retries){
$max = true;
}
}
.....
my question is that, how can I deal with this error? and how can I successfully create pdf file in google drive by tweaking this code? because I need the created file ID of the file to be linked in my post.
Thanks in advance...
You shouldn't be passing $mkFile to nextChunk. Have a read though the resumable uploads section in the documentation.
You have more fundamental issues than that though. For instance, the insert call you do already sets the data for the file. There is no need to do anything with nextChunk unless you are doing resumable uploads. Follow the "Multipart File Upload" section of the above doc to fix your insert statement and just remove the nextChunk line.

Check if file exists in .tar using PHP

In my program I need to read .png files from a .tar file.
I am using pear Archive_Tar class (http://pear.php.net/package/Archive_Tar/redirected)
Everything is fine if the file im looking for exists, but if it is not in the .tar file then the function timouts after 30 seconds. In the class documentation it states that it should return null if it does not find the file...
$tar = new Archive_Tar('path/to/mytar.tar');
$filePath = 'path/to/my/image/image.png';
$file = $tar->extractInString($filePath); // This works fine if the $filePath is correct
// if the path to the file does not exists
// the script will timeout after 30 seconds
var_dump($file);
return;
Any suggestions on solving this or any other library that I could use to solve my problem?
The listContent method will return an array of all files (and other information about them) present in the specified archive. So if you check if the file you wish to extract is present in that array first, you can avoid the delay that you are experiencing.
The below code isn't optimised - for multiple calls to extract different files for example the $files array should only be populated once - but is a good way forward.
include "Archive/Tar.php";
$tar = new Archive_Tar('mytar.tar');
$filePath = 'path/to/my/image/image.png';
$contents = $tar->listContent();
$files = array();
foreach ($contents as $entry) {
$files[] = $entry['filename'];
}
$exists = in_array($filePath, $files);
if ($exists) {
$fileContent = $tar->extractInString($filePath);
var_dump($fileContent);
} else {
echo "File $filePath does not exist in archive.\n";
}

Can't copy file due to special characters in filename

I would like to copy a file in Symfony2, but I'm getting an error:
Symfony\Component\Filesystem\Exception\FileNotFoundException: Failed to copy "../../../public_html/uploads/images/2011/03/MG_3839-ba�o.jpg" because file does not exist
$fs = new Filesystem();
$fs->copy('../../../public_html/uploads/images/'.$image, '../../../public_html/uploads/tmp/'.$image, true);
var_dump($image) gives 2011/03/MG_3839-baño.jpg and mb_detect_encoding($image) gives ASCII. Why is Symfony looking for a filename containing the � sign? I can't figure out where that sign is coming from, since var_dump() gives the correct filename.
Try this command :
$fs = new Filesystem();
$image = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $image);
$fs->copy('../../../public_html/uploads/images/'.$image, '../../../public_html/uploads/tmp/'.$image, true);
$file_name = strtr($file_name, "áéíóúâêôàãõçÁÉÍÓÚÂÊÔÀÃÕǺª", "aeiouaeoaaocAEIOUAEOAAOCoa");

unable to read pdf file using imagick

I'm trying to convert a pdf file to a jpeg. But I cant even get the simplest example to work.
<?php
if (!extension_loaded('imagick'))
die('Imagick is not installed');
else
echo 'Imagick installed<hr>';
$inputFile="test.pdf";
if(file_exists($inputFile)){
echo "$inputFile exists.<br>";
}
else{
die("$inputFile doesnt exist.");
}
$imagick = new Imagick();
$imagick->readImage($inputFile);
$imagick = $imagick->flattenImages();
$imagick->writeFile('test.jpg');
?>
The first test says the file exists but imagaick is not able to read the file.
Fatal error: Uncaught exception 'ImagickException' with message
'unable to open image `test.pdf': No such file or directory #
error/blob.c/OpenBlob/2646' in C:\xampp\htdocs\img\index.php:14 Stack trace: #0
C:\xampp\htdocs\img\index.php(14): Imagick->__construct('test.pdf') #1 {main} thrown in
C:\xampp\htdocs\img\index.php on line 14
What am I doing wrong ?
The problem is in your path to pdf file,
simply use $_SERVER['DOCUMENT_ROOT']
$inputFile = $_SERVER['DOCUMENT_ROOT']."/test.pdf";

pdf generation not working in framework Zend

I have a script that generates a PDF in Zend. I copied the script from converting image to pdf to another directory on the server. I now get the error:
Fatal error: Uncaught exception 'Zend_Pdf_Exception' with message 'Cannot create image resource.
File not found.' in /kalendarz/Zend/Pdf/Resource/ImageFactory.php:38
Stack trace:
#0 /kalendarz/Zend/Pdf/Image.php(124): Zend_Pdf_Resource_ImageFactory::factory('data/0116b4/cro...')
#1 /kalendarz/cms.php(56): Zend_Pdf_Image::imageWithPath('data/0116b4/cro...')
#2 {main} thrown in /kalendarz/Zend/Pdf/Resource/ImageFactory.php on line 38
Code of website, example link to image (http://tinyurl.com/8srbfza):
else if($_GET['action']=='generate') {
//1 punkt typograficzny postscriptowy (cyfrowy) = 1/72 cala = 0,3528 mm
function mm_to_pt($size_mm) {
return $size_mm/0.3528;
}
require_once("Zend/Pdf.php");
$pdf = new Zend_Pdf();
$page_w = mm_to_pt(100);
$page_h = mm_to_pt(90);
$page = $pdf->newPage($page_w.':'.$page_h.':');
$pdf->pages[] = $page;
$imagePath= 'data/'.$_GET['id'].'/crop_'.$_GET['id'].'.jpg'; //to nie jest miniaturka
$image = Zend_Pdf_Image::imageWithPath($imagePath);
$left = mm_to_pt(0);
$right = mm_to_pt(100);
$top = mm_to_pt(90);
$bottom = mm_to_pt(0);
$page->drawImage($image, $left, $bottom, $right, $top);
$pdfData = $pdf->render();
header("Content-Disposition: inline; filename=".$_GET['id'].".pdf");
header("Content-type: application/x-pdf");
echo $pdfData;
die();
}
Zend_Pdf_Image::imageWithPath expects a valid file and uses is_file function call to check the file existence.
First of all, use absolute path to the image, instead of using the relative one. You can specify the absolute path by referring to your APPLICATION_PATH. For example,
APPLICATION_PATH . '/../public/data
If APPLICATION_PATH is not already defined in your code, paste this code in your public/index.php
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
Then, check if 'data/'.$GET['id'].'/crop'.$_GET['id'].'.jpg' exists. Also, check if the file has proper permissions to be accessed by PHP.
Note : Use the Zend request object instead of the $_GET.
Use an absolute path:
$imagePath = '/kalendarz/data/'.$_GET['id'].'/crop_'.$_GET['id'].'.jpg';
or:
$imagePath = APPLICATION_PATH.'/../data/'.$_GET['id'].'/crop_'.$_GET['id'].'.jpg';
you might also want to put some validation on $_GET['id'].

Categories