Add remote images to PhpSpreadseet cell - php

There is a simple two-column table on a website: product name and product image. It's very easy to render in HTML.
The task would be creating an Xlsx file with these columns.
The images are not stored locally but all of them are remote images with full URL.
The export contains ~100-200 rows.
I tried to create a resource with imagecreatefromjpeg and adding it with MemoryDrawing but it took a huge amount of resources.
I tried with Html helper's toRichTextObject and a simple tag but got empty result.
How is it possible to add a remote image to a PhpSpreadsheet cell? It doesn't need working offline, it's fine to load the remote images when the file is opened.

As #FabriceFabiyi mentionned in his comment, and after reading:
PhpSpreadseet documentation on drawing.
PHP documentation on file_get_contents.
PHP documentation on file_set_contents.
This worked for me:
$image = file_get_contents('https://website.com/path/to/image');
$imageName = 'a_nice_image_name';
//You can save the image wherever you want
//I would highly recommand using a temporary directory
$temp_image=tempnam(sys_get_temp_dir(), $imageName);
file_put_contents($temp_image, $image);
// And then PhpSpreadsheet acts just like it would do with a local image
$drawing->setPath($temp_image);
$drawing->setHeight(36);
$drawing->setWorksheet($sheet);
$drawing->setCoordinates('B15');
More on temporary directories in the PHP docs:
sys_get_temp_dir()
tempnam()

There is an example how add image to your excel export:
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Paid');
$drawing->setDescription('Paid');
$drawing->setPath('/images/image-1.png'); // put your path and image here
$drawing->setHeight(30);
$drawing->setCoordinates('A5');
$drawing->setOffsetX(110);
$drawing->setRotation(25);
$drawing->getShadow()->setVisible(true);
$drawing->getShadow()->setDirection(45);
$drawing->setWorksheet($spreadsheet->getActiveSheet());

Specifying coordinates for the image might help, as per the examples and the documentation
$objDrawing->setCoordinates('A3');
Note that an image isn't in a cell/column/row, but overlaid over the main sheet at the same position as that cell/column/row

Related

Saving a remote image programmatically with PHP

I am trying to migrate some content from one resources into another and need to save some images (several hundred) located at a remote resource.
Suppose I have only the URL to an image:
https://www.example.com/some_image.jpg
And I would like to save it into the filesystem using PHP.
If I were uploading the image, I essentially would do the following:
<input type="file" name="my_image" />
move_uploaded_file($_FILES['my_image']['tmp_name'], '/my_img_directory');
But since I only have the URL, I would imagine something like:
$img = 'https://www.example.com/some_image.jpg';
$file = readfile($img);
move_uploaded_file($file, '/my_img_directory');
Which of course wouldnt work since move_uploaded_file() doesn't take an output buffer as a first argument.
Essentially, I would need to get $img into the $_FILES[] array under this approach. Or may some other approach?
You can use PHP's copy function to copy remote files to a location on your server:
copy("https://example.com/some_image.jpg", "/path/to/file.jpg");
http://php.net/manual/en/function.copy.php
$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image); //Where to save the image on your server

Qr-Code using Bacon/BaconQrCode need to save to the folder.

I am using Bacon/BaconQrCode library to generate Qr-Code image so how can
save the Qr-code images to the specific folder ?? please help.
My Code:-
$renderer = new \BaconQrCode\Renderer\Image\Png();
$renderer->setHeight(256);
$renderer->setWidth(256);
$writer = new \BaconQrCode\Writer($renderer);
$writer->writeFile('www.google.com', 'qrcode.png');
How can I save this Qr-code image to the folder to show or fetch from other location.
The \BaconQrCode\Writer->writeFile uses file_put_contents method so you can just add an absolute path to your directory like : $writer->writeFile('www.google.com', '../public/qrcodes/qrcode.png');
I haven't tried yet but i hope it works for you.

PDF Image thumbnail preview in laravel 5.1?

I have file module, where I want to list all files,with thumbnail preview.
as like follows,
I am storing files in storage folder,which is not accessible via http.
So How can I provide thumbnail preview for docs especially image and PDF.
Is there any package availabe in laravel 5.1?
The preview image of a PDF file is usually the first page of the PDF file.
You can use ImageMagick to obtain that first page of the PDF file.
<?php
$imagick = new imagick('sample.pdf[0]'); // 0 specifies the first page of the pdf
$imagick->setImageFormat('jpg'); // set the format of the output image
header('Content-Type: image/jpeg'); // set the header for the browser to understand
echo $imagick; // display the image
?>
You can also output (save the contents of the image in a file) and store it under a thumbnail folder with the PDF name as the file name. like ( sample.jpg )
As for a solution based on laravel, I don't think laravel has any package that can do the same
Though the question was posted quite a long ago but I'm answering because it might helps others. There is a package for generating image from pdf. Pdf to Image. You should have Imagick and Ghostscript installed

how to retrieve blob file to image in php?

I am using plupload to upload file in my php based website, with large file uploading the file becomes a file named 'blob' without any suffix. I know this is a binary file that contains the raw data, question is how to retrieve the data and save it back as an image file, say .png/.jpg or etc? I tried:
$imageString = file_get_contents($blogPath);
$image = imagecreatefromstring($imageString);
But it gives me some 'Data is not in recognized format...' error, any thoughts? Thanks in advance.
Your call to imagecreatefromstring() should work just fine if your file_get_contents() is working. Use var_dump($imageString) to verify. Did you mean to name your variable $blobPath instead of $blogPath?
You don't need to load this image though. Just rename the file.
rename($blobPath, 'new/path/here.jpg');
http://php.net/manual/en/function.rename.php
I am storing the uploaded image files for late use, like attaching them to posts or products(my site is e-commerce CMS). I figured that my image file didn't get fully uploaded to the server, the image before upload is 6mb, but the blob file is just 192kb, so my best guess is that what get uploaded is just a chunk instead of the whole package, and yet that brought up another question: how should I take all the pieces and assemble them as one complete image file? As mentioned earlier, I am using plupload for js plugin and php as backend, the backend php code to handle uploading goes like this:
move_uploaded_file($_FILES["file"]["tmp_name"], $uploadFolder . $_FILES["file"]["name"]);
Instead of doing that you should do this to display image to the browser
<img src="data:image/jpeg;base64,'.base64_encode( $row['blob_image'] ).'"/>
I'm not sure what imagecreatefromsting does or how it encodes the image.
I looked at the documentation for that function; you're missing:
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data); <--- this operation

Resize image directly from Rackspace Cloud Files 'object' without downloading?

I have moved my images to Rackspace Cloud Files and am using their PHP API. I am trying to do the following:
Get an image from my "originals" container
Resize it, sharpen it, etc.
Save the resized image to the "thumbs" container
My problem is with #2. I was hoping to resize without having to copy the original to my server first (since the images are large and I'd like to resize dynamically), but can't figure out how. This is what I have so far (not much):
$container = $conn->get_container("originals");
$obj = $container->get_object("example.jpg");
$img = $obj->read();
Part of the problem is I don't fully understand what is being returned by the read() function. I know $img contains the object's "data" (which I was able to print out as gibberish), but it is neither a file nor a url nor an image resource, so I don't know how to deal with it. Is it possible to convert $img into an image resource somehow? I tried imagecreatefromjpeg($img) but that didn't work.
Thanks!
First, you cannot resize an image without loading it into memory. Unless the remote server offers some "resize my image for me, here are the parameters" API, you have to load the image in your script to manipulate it. So you'll have to copy the file from the CloudFiles container to your server, manipulate it, then send it back into storage.
The data you receive from $obj->read() is the image data. That is the file. It doesn't have a file name and it's not saved on the hard disk, but it is the entire file. To load this into gd to manipulate it, you can use imagecreatefromstring. That's analogous to using, for example, imagecreatefrompng, only that imagecreatefrompng wants to read a file from the file system by itself, while imagecreatefromstring just accepts the data that you have already loaded into memory.
You can try to dump the content of the $img variable into a writable file as per the below:
<?php
$filename = 'modifiedImage.jpg';
/*
* 'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate
* the file to zero length. If the file does not exist, attempt to create it.
*/
$handle = fopen($filename, 'w+');
// Write $img to the opened\created file.
if (fwrite($handle, $img) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote to file ($filename)";
fclose($handle);
?>
More details:
http://www.php.net/manual/en/function.fopen.php
http://www.php.net/manual/en/function.fwrite.php
Edit:
You might also want to double check the type of data returned by the read() function, because if the data is not a jpg image, if it's for example a png, the extension of the file needs to be changed accordingly.

Categories