T
T
turbomen242020-10-13 17:18:25
PHP
turbomen24, 2020-10-13 17:18:25

How to get links to images converted by Imagick from pdf to img?

My function will convert all pdf pages to images:

$url = 'files/myfile.pdf';
$imagick = new Imagick();
$imagick->setResolution(150, 150);
$imagick->readImage($url);
$imagick->writeImages('files/myfile.jpg', false);
$imagick->destroy();


How can I get links to these images in the output? If I need to get one page, it's not a problem, because I write images to a certain folder and I know the file name, but what if there are several pages? It is possible to get the number of pages through $imagick->getNumberImages();, then assign and calculate all my new images through the increment and decrement operators, but maybe there is an easier way?

UPD here is the solution
I also use a random number to avoid overwriting existing files (if suddenly a pdf with the same name already exists, the images will overwrite existing ones accordingly), and I also create a folder via mkdir for them, because imagick can't do that. In my case, these pictures are temporary files, only then they will be moved to another directory and entered into the database, so at the end of all the manipulations, my created folder with all the files will be deleted, and I only need links for further processing.

$attachment_url = 'test/myfile.pdf';   // Мой файл
$attachment_title = *имя файла*;   // В моём случае я получаю это через фукнцию вызова названия записи
$imagick = new Imagick();	//запускаем imagick
$imagick->setResolution(150, 150);
$imagick->readImage($attachment_url);
$rand = mt_rand(100000, 999999);       //Рандомное число
$new_name = $rand.'-'.$attachment_title;      //Новое имя для файла и папки с рандомным числом
mkdir("test/$new_name", 0755);  //   новая папка
$imagick->writeImages("test/$new_name/$new_name%03d.jpg", false);
$files = scandir("test/$new_name");  //сканируем папку
foreach($files as $f) {
      echo '<a href="http://testsite.com/test/'.$new_name.'/'.$f.'">'.$f.'</a><br />'; }     //получаем ссылки на изображения

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nokimaro, 2020-10-13
@turbomen24

The easiest way to know everything is to control what and where you record and with what name.
getNumberImages() is a normal option, as it allows you to find out the number of pages in pdf and, accordingly, save each page as a separate image.
That is, you do it in 2 steps
1. find out the number of pages in pdf
2. call imagick($pdf_file[0]) for each page where [0] is the page number and save the result with the desired name.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question