I couldn't find the answer for this anywhere on google. I'm uploading an excel sheet via PHP using the PHPExcel_Worksheet_MemoryDrawing class however it seems to be uploading the images in a random order.
Is there anyway to specify which order it uploads in such as row $n. Currently I'm uploading the file and pushing each image to an array using $i as the value but it seems to be selecting images at random. In the excel file I have also renamed images 001, 002 etc but it's still seems to be random once it uploads.
$i=0;
foreach ($objPHPExcel->getSheetByName("Sheet1")->getDrawingCollection() as $drawing) {
if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
$extension = 'jpg';
$myFileName = $dir_to_create.'/'.date('Ymjis').rand().'.'.$extension;
array_push($td, $myFileName);
file_put_contents($myFileName,$imageContents);
$images_data[$i] = $myFileName;
$i++;
}
}
A workaround I'm using is to call the coordinates and use that as my array key then use asort on the array to sort it. Although this method works I would like to know if there's an alternative method to upload in order.
$row = $drawing->getCoordinates();
$images_data[$row] = $myFileName;
asort($images_data);
Related
I want to split slides of one pptx file into seperated pptx files, containing one slide each. The content/text is copied but the layout & styling is not copied. Here is the code.
Can anyone please help ?
<?php
use PhpOffice\PhpPresentation\PhpPresentation;
use PhpOffice\PhpPresentation\IOFactory;
use PhpOffice\PhpPresentation\Style\Color;
use PhpOffice\PhpPresentation\Style\Alignment;
use PhpOffice\PhpPresentation\Slide\SlideLayout;
$objReader = \PhpOffice\PhpPresentation\IOFactory::createReader('PowerPoint2007');
$objPHPPowerPoint = $objReader->load('a.pptx');
$totalSlides = $objPHPPowerPoint->getSlideCount();
$oMasterSlide = $objPHPPowerPoint->getAllMasterSlides()[0];
$documentProperties = $objPHPPowerPoint->getDocumentProperties();
for ( $count = 0; $count < $totalSlides; $count++ ) {
$objPHPPresentation = new PhpPresentation();
$slide = $objPHPPowerPoint->getSlide( $count );
$background = $slide->getBackground();
$newSlide = $objPHPPresentation->addSlide( $slide );
$newSlide->setBackground ( $background );
$objPHPPresentation->setAllMasterSlides( $oMasterSlide );
$objPHPPresentation->removeSlideByIndex(0);
$oWriterPPTX = \PhpOffice\PhpPresentation\IOFactory::createWriter($objPHPPresentation, 'PowerPoint2007');
$oWriterPPTX->save($count.'.pptx');
}
I don't think it's an issue with your code - more an issue with the underlying libraries - as mentioned here: PhpPresentation imagecreatefromstring(): Data is not in a recognized format - PHP7.2
It ran a test to see if it was something I could replicate - and I was able to. The key difference in my test was in one presentation I had a simple background, and in the other it was a gradient.
This slide caused problems:
But this one was copied over fine:
With the more complex background I got errors like:
PHP Warning: imagecreatefromstring(): Data is not in a recognized format
My code is even less complicated than yours, I just clone the original slideshow and remove all except a single slide before saving it:
for ( $count = 0; $count < $totalSlides; $count++ ) {
$copyVersion = clone $objPHPPowerPoint;
foreach ($copyVersion->getAllSlides() as $index => $slide) {
if ($index !== $count) {
$copyVersion->removeSlideByIndex($index);
}
}
$oWriterPPTX = \PhpOffice\PhpPresentation\IOFactory::createWriter($copyVersion, 'PowerPoint2007');
$oWriterPPTX->save($count.'.pptx');
}
Sorry if this doesn't exactly solve your problem, but hopefully it can help identify why it's happening. The other answer I linked to has more information about finding unsupported images types in your slides.
You can try using Aspose.Slides Cloud SDK for PHP to split a presentation into separate slides and save them to many formats. You can evaluate this REST-based API making 150 free API calls per month for API learning and presentation processing. The following code example shows you how to split a presentation and save slides to PPTX format using Aspose.Slides Cloud:
use Aspose\Slides\Cloud\Sdk\Api\Configuration;
use Aspose\Slides\Cloud\Sdk\Api\SlidesApi;
use Aspose\Slides\Cloud\Sdk\Model;
$configuration = new Configuration();
$configuration->setAppSid("my_client_id");
$configuration->setAppKey("my_client_key");
$slidesApi = new SlidesApi(null, $configuration);
$filePath = "example.pptx";
// Upload the file to the default storage.
$fileStream = fopen($filePath, 'r');
$slidesApi->uploadFile($filePath, $fileStream);
// Split the file and save the slides in PPTX format in the same folder.
$response = $slidesApi->split($filePath, null, Model\SlideExportFormat::PPTX);
// Download files of the slides.
foreach($response->getSlides() as $slide) {
$slideFilePath = pathinfo($slide->getHref())["basename"];
$slideFile = $slidesApi->downloadFile($slideFilePath);
echo $slideFile->getRealPath(), "\r\n";
}
Sometimes it is necessary to split a presentation without using any code. In this case, you can use Online PowerPoint Splitter.
I work as a Support Developer at Aspose.
I have my folder /images (with ~ 95.000 files), and i check every file if is in the database.
Table : images
Row : hash
The folder containt all my image with sha1 name.
I use shuffle($images); to make sure the verification is random, otherwise it only verifies the first 35,000 images.
If I go over 35,000 checks, the script puts a timeout and the page blocks it.
Example name of an image : d0a0bb3149bea2335e8784812fef706ad0a13156.jpg
My Script :
I select the images in the database
I'm putting it in a array
I make the array random (to avoid always checking the first 35,000
images)
I create a array of images file in the folder /images
I check for missing database files using the array created by the
opendir(); function
I display the answer
<?php
set_time_limit(0);
$images = [];
$q = $mysqli->query('SELECT hash FROM images');
while($r = $q->fetch_assoc())
{
$images[] = $r['hash'].'.jpg';
}
shuffle($images);
$i_hors_bdd = 0;
$images_existent_hors_bdd = [];
if($dh = opendir($_SERVER['DOCUMENT_ROOT'].'/images'))
{
while(($file = readdir($dh)) !== false)
{
if(!in_array($file, $fichiers_a_exclures))
{
if(!is_sha1($file) OR !in_array($file, $images))
$images_existent_hors_bdd[] = '<p>Name of File: '.$file.'</p>';
}
if($i_hors_bdd > 35000)
{
break;
}
$i_hors_bdd++;
}
}
closedir($dh);
if(count($images_existent_hors_bdd) > 0)
{
echo '<p>Image exist, but not in the databse.</p>';
sort($images_existent_hors_bdd);
foreach($images_existent_hors_bdd as $image_existe_hors_bdd)
echo $image_existe_hors_bdd;
}
else
echo '<p>All images are in datase.</p>';
echo '<p>'.$i_hors_bdd.' images checked.</p>';
So my question is: How can I optimize this script to improve the speed of the script to allow checking more images without blocking the script? Knowing that my VPS is not very powerful and I don't have SSD.
Here are some things to consider or try:
Concatenate '.jpg' to hash in the sql, then use fetch_all into a numeric array.
use scandir to build an array of files in the directory
use array_diff to remove $fichiers_a_exclures and $images
iterate over this smallest array to do the sha1 test
I am a newbie at PHP and I'm learning.
I've made a basic script where you can upload an image to a director on the server. I want the image names to get a number at the end so that the name won't be duplicated.
This is my script to add 1 to the name (I'm really bad at "for loops"):
for(x=0; $imageName => 50000; x++){
$imageFolderName = $imageName.$x;
}
Please tell me if I'm doing this totally wrong.
Adding to Niet's answer, you can do a foreach loop on all the files in your folder and prepend a number to the file name like so:
<?
$directory = 'directory_name';
$files = array_diff(scandir($directory), array('.', '..'));
$count = 0;
foreach($files as $file)
{
$count++;
rename($file, $count.'-'.$file);
}
?>
Alternatively you could rename the file to the timestamp of when it was uploaded and prepend some random characters to the file with the rand() function:
<?
$uploaded_name = 'generic-image.jpeg';
$new_name = time().rand(0, 999).$uploaded_name;
?>
You'll need to handle and move the uploaded files before and after the rename, but you get the general gist of how this would work.
Here's a potential trick to avoid looping:
$existingfiles = count(glob("files/*"));
// this assumes you are saving in a directory called files!
$finalName = $imageName.$existingfiles;
I have an excel document with multiple records which contains both the text content and images.
I have to save the images according to the record basis. A record has either an image or multiple images or no image. So If I retrieve an image means then I have to name it.
Therefore, I need to find the image's cell name. So that I can easily name it and save it.
But I have no solution to do this. Can we retrieve the cell information using
$worksheet->getDrawingCollection()
Please suggest me how to do this.
$objPHPExcel = PHPExcel_IOFactory::load("MyExcelFile.xls");
foreach ($objPHPExcel->getSheetByName("My Sheet")->getDrawingCollection() as $drawing) {
if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
$cellID = $drawing->getCoordinates();
// .... do your save here
}
}
I'm having a problem getting my images to display after extracting them from a database.
I have 2 separate tables, one for the meta data and another to hold the actual blob data. that table is a regular BLOB and i only store 60k chunks of data in each row. I recompile the image when i want to render it.
i keep getting this error though:
the image "http://imgStore.localhost/ImageBuilder/index/id/11" cannot be displayed because it contains errors.
here is how the flow works however.
/Images/image/id/11 will have an image inside of it like this
<img src="http://imgStore.localhost/ImageBuilder/index/id/11" />
the Images controller handles insertions and edits as well as listing the images
while ImageBuilder is only concerned with displaying a given image
here is the table structure:
images ------
image_id INT
image_name VARCHAR
image_type VARCHAR
image_size INT
loaded_date DATETIME
image_data --
image_data_id INT
image_id INT
data BLOB
here is how i save the file into the database:
( NOTE: i'm using the latest Zend Framework )
( insertion action ) ------------------
$image = new ImgStore_Model_Images($form->getValues());
$image->setImage_size(((int) substr($form->image_file->getFileSize(), 0, -2) * 1024));
$image->setImage_type($form->image_file->getMimeType());
$image->setLoaded_date(time());
$image->setLoaded_by($user->get('contacts_id'));
$mapper = new ImgStore_Model_ImagesMapper();
$image_id = $mapper->save($image);
// open the uploaded file to read binary data
$fp = fopen($form->image_file->getFileName(), "r");
$dataMapper = new ImgStore_Model_ImageDataMapper();
// loop through the file and push the contents into
// image data entries
while( !feof($fp) ){
// Make the data mysql insert safe
$binary_data = addslashes(fread($fp, 60000));
$data_entry = new ImgStore_Model_ImageData();
$data_entry->setImage_id($image_id);
$data_entry->setImage_data($binary_data);
$dataMapper->save($data_entry);
}
fclose($fp);
and here is how it is extracted:
(action) ------------------
$this->_helper->_layout->disableLayout();
// get the image meta data
$image_id = $this->_request->getParam('id', '0');
$mapper = new ImgStore_Model_ImagesMapper();
$info = $mapper->getInfo($image_id);
// build the image and push it to the view
$mapper = new ImgStore_Model_ImageDataMapper();
$this->view->image = $mapper->buildImage($image_id);
$this->view->name = $info->getImage_name();
$this->view->type = $info->getImage_type();
$this->view->size = $info->getImage_size();
(model) ------------------
public function buildImage($image_id)
{
// get the image data
$sql = "SELECT image_data
FROM image_data
WHERE image_id='$image_id'
ORDER BY image_data_id ASC";
$results = $this->_adapter->fetchAll($sql);
// piece together the image and return it
$image = NULL;
foreach( $results as $row ){
$image .= $row['image_data'];
}
return $image;
} #end buildImage function
(view) ------------------
<?php
header( "Content-Type: " . $this->type );
header('Content-Disposition: inline; filename="'.$this->name.'"');
echo $this->image;
?>
i have tried to use an image that was small enough to take up only one row in the image_data table as well, so i don't believe it has anything to do with the recompilation of the image_data rows.
any help would be appreciated, i truly have no idea what is wrong with this.
edited some formatting for display purposes.
I recently did something like this but used a different approach for the rendering. Zend won't fire up the app if the request URI to an actual file, so I created a render action in my file controller that created a copy of the image on the drive. This makes scaling and management much easier since the files are all in one central db, but also gives the performance benefits of reading from the disk. Here's my open action:
public function openAction() {
$file = // find the file in the db
if(! $file) {
throw new Zend_Exception('File not found', 404);
}
$path = // get the filepath
if(! file_exists($path) || $this->_request->getParam('reload') == true) {
file_put_contents($path, $file->image_data);
}
$this->_redirect('document root relative path');
}
there's no real value in cluttering up the database with image data. (Fetching the data from the database will also be significantly slower than simply loading it off disk)
I suggest that you just store the images on the file system, and store the path to the image in the database alongside the meta data.