using Image Manipulation Class in CodeIgniter 4 without save in a file - php

this is my code
$file = new \CodeIgniter\Files\File($imgUrl);
$fileMime = $file->getMimeType();
if(file_exists("img/us/".$_SESSION["sess_order"]."/".$_SESSION["sess_userimg"])){
if($fileMime == 'image/jpeg'){
$image = \Config\Services::image()
-> withFile($file)
-> fit(100, 100, 'center');
header("Content-type: image/JPEG");
echo $image;
}
}else{
return "img/usr.png";
}
I'll get user's Image and return thumbnail of that image.
with Image Manipulation Class in #CodeIgniter 4 can do it well, but I don't need to save thumbnail file in storage, I just need image as an Object. How can I do it.
I want something like using file_get_contents() function and return it
thanks

Related

Displaying bar Code in PDF file on every page of the PDF, in Laravel

I am Using Imagick to Convert PDF to Images
Uploading PDF to Laravel
public function uploadPdf( Request $request )
{
$model = new Attachment();
if ( $request->hasFile('pdf_file_from_request') ) {
Storage::deleteDirectory('3pagerpdf/pdf');
$pdf = $request->file('pdf_file_from_request');
$fileName = time() . '.' . $pdf->getClientOriginalName();
Storage::putFileAs('3pagerpdf/pdf', $pdf, $fileName);
$model->pdf_file_name_in_datebase = $fileName;
$model->save();
flash()->addSuccess('Pdf Added');
return back();
}
}
Converting that PDF to Images
public function convertpdftoimages()
{
$model = Attachment::first();
set_time_limit(300);
// Get the PDF file from the storage folder
$pdfPath = storage_path('app/3pagerpdf/pdf/'.$model->pdf_file_name_in_datebase);
// Create an Imagick object
$imagick = new Imagick();
// Set the resolution and output format
$imagick->setResolution(300, 300);
$imagick->setFormat('jpeg');
// Read the PDF file into the Imagick object
$imagick->readImage($pdfPath);
// Convert each page of the PDF to an image
foreach ( $imagick as $page ) {
$page->writeImage(public_path("/temp_images/page{$page->getImageIndex()}.jpg"));
}
flash()->addSuccess('Convertion Successfull');
return back();
}
Adding bar code to those images
public function add_bar_code_to_images2()
{
$files = File::files('temp_images');
foreach ( $files as $file ) {
// Generate a barcode image for the file
$barcodeGenerator = new BarcodeGeneratorPNG();
$data = '';
for ($i = 0; $i < 10; $i++) {
$data .= rand(0, 9);
}
$barcodeString = $barcodeGenerator->getBarcode($data, $barcodeGenerator::TYPE_CODE_128);
// Create an image resource from the barcode string
$barcodeImage = imagecreatefromstring($barcodeString);
// Load the original image
$originalImage = imagecreatefromjpeg($file->getPathname());
// Merge the barcode image with the original image
imagecopy($originalImage, $barcodeImage, imagesx($originalImage) - imagesx($barcodeImage) - 10, 10, 0, 0, imagesx($barcodeImage), imagesy($barcodeImage));
// Save the modified image to a new path
imagejpeg($originalImage, 'modified_images/' . $file->getFilename());
}
flash()->addSuccess('Bar Code Added Succesfuully');
return back();
}
Converting those images Back to pdf
public function convertimagestopdf( )
{
// Create a new Imagick object
$imagick = new Imagick();
// Set the resolution of the PDF
$imagick->setResolution(300, 300);
// Iterate over the images in the "modified_images" directory
foreach (glob("modified_images/*.jpg") as $image) {
// Read the image file
$imagick->readImage($image);
}
// Set the format of the PDF to "application/pdf"
$imagick->setImageFormat('pdf');
// Save the PDF to a file
$imagick->writeImages('modified_pdf/document.pdf', true);
flash()->addSuccess('pdf compileed');
return back();
}
What I want is
I want to add bar code to every single page of a pdf but I dont want to use imagick extenstion it needs to be installed on a system to make it work .
I tried the above code
it is taking too long to execute for small pdf's that code it fine but for the pdf with 60 pages and above it starts to give me time out error
Note I am not generating this pdf
the pdf will be uploaded by random user of my application and it will be already a pdf I just need to add barcode to every single page of the pdf .
I will take any alternative solution
in which i dont have to install any application on my computer
like ghostscript

PHP PDF to image crops some files when generating a thumbnail. setIteratorIndex fails as well

I have written a function in PHP 7.4 that generates a thumbnail of the first page of a PDF document. The function works as intended for most PDF files.
However, some PDFs get cropped when I generate the thumbnail. Additionally, sometimes, I don't get the first page.
This PDF triggers both problems:
http://www.teavigoinfo.com/pdf/study-27.pdf
function PDF2Thumbnail($url) {
$image = #file_get_contents($url);
if($image) {
$im = new Imagick();
$im->readImageBlob($image);
$im->setIteratorIndex(0);
$im->thumbnailImage(300, 0);
$im->setImageFormat('png');
$im = $im->flattenImages();
header('Content-Type: image/png');
echo $im;
}
}
Thank you.

PHP trying to understand how to generate thumbnail from directory

This is currently what I have. When I include it in my index.php and then call the function on pageload, I get a blank page. So something is wrong here, but I don't know what. I feel like I'm really close though. I just want to create thumbnails of images in a directory, and then show them in HTML as a list of images you can click that trigger lightboxes.
I'm still really shaky in PHP. I'm trying to wrap my head around editing images in a directory.
<?php
function buildThumbGallery(){
$h = opendir('/Recent_Additions/'); //Open the current directory
while (false !== ($curDir = readdir($h))) {
if (!file_exists('/Recent_Additions/thumbs/')) {
$thumbDir = mkdir('/Recent_Additions/thumbs/', 0777, true);
}else{
$thumbDir = '/Recent_Additions/thumbs/';
}
$width = 200;
$height = 200;
foreach ($curDir as $image) {
$filePath = $curDir."/".$image;
$genThumbImg = $image->scaleImage($width, $height, true);
$newThumb = imagejpeg($genThumbImg, $thumbDir, 100);
echo '<li> <a class="fancybox" data-fancybox-group="'.basename($curDir).'" href="'.$filePath.'" title="'.basename($curDir)." ".strpbrk(basename($filePath, ".jpg"), '-').'"><img src="'.$newThumb.'"/>'.basename($curDir).'</a>';
imagedestroy($newThumb);
}echo '</li>';
}
?>
You are doing several things wrong:
You're not closing the while loop.
Readdir already loops through a directory, your foreach is not doing anything.
You are missing quotes in your echo.
You are calling the method scaleImage on a string, I think you meant to call the function imagescale.
You're missing and misunderstanding a lot of stuff, take a look at how to create a thumbnail here: https://stackoverflow.com/a/11376379/4193448
Also see if you can enable PHP errors, getting a blank page while your code is full of errors is not really helping is it?
::EDIT::
With help from #swordbeta, I got my script working properly. Here is the code for future reference:
<?php
function buildThumbGallery(){
$curDir = "./Recent_Additions/";
$thumbsPath = $curDir."thumbs/";
if (!file_exists($thumbsPath)) {
mkdir($thumbsPath, 0777, true);
}
foreach(scandir($curDir) as $image){
if ($image === '.' || $image === '..' || $image === 'thumbs') continue;
if(!file_exists($thumbsPath.basename($image, ".jpg")."_thumb.jpg")){
// Max vert or horiz resolution
$maxsize=200;
// create new Imagick object
$thumb = new Imagick($curDir.$image); //'input_image_filename_and_location'
$thumb->setImageFormat('jpg');
// Resizes to whichever is larger, width or height
if($thumb->getImageHeight() <= $thumb->getImageWidth()){
// Resize image using the lanczos resampling algorithm based on width
$thumb->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
}else{
// Resize image using the lanczos resampling algorithm based on height
$thumb->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}
// Set to use jpeg compression
$thumb->setImageCompression(Imagick::COMPRESSION_JPEG);
$thumb->setImageCompressionQuality(100);
// Strip out unneeded meta data
$thumb->stripImage();
// Writes resultant image to output directory
$thumb->writeImage($thumbsPath.basename($image, ".jpg")."_thumb.jpg"); //'output_image_filename_and_location'
// Destroys Imagick object, freeing allocated resources in the process
$thumb->destroy();
}else{
echo '<a class="fancybox" data-fancybox-group="'.basename($curDir).'" href="'.$curDir.basename($image, "_thumb.jpg").'" title="Recent Addition - '.basename($image, ".jpg").'"><img src="'.$thumbsPath.basename($image, ".jpg")."_thumb.jpg".'"/></a>';
echo '<figcaption>'.basename($image, ".jpg").'</figcaption>' . "<br/>";
}
}
}
?>
::Original Post::
Ok, after going back and doing some more research and suggestions from #swordbeta, i've got something that works. My only issue now is I can't get the images to show in my index.php. I'll style the output in CSS later, right now I just want to see the thumbnails, and then later build them into lightbox href links:
<?php
function buildThumbGallery(){
$curDir = "./Recent_Additions/";
$thumbsPath = $curDir."/thumbs/";
if (!file_exists($thumbsPath)) {
mkdir($thumbsPath, 0777, true);
}
$width = 200;
foreach(scandir($curDir) as $image){
if ($image === '.' || $image === '..') continue;
if(file_exists($thumbsPath.basename($image)."_thumb.jpg")){
continue;
}else{
// Max vert or horiz resolution
$maxsize=200;
// create new Imagick object
$thumb = new Imagick($curDir.$image); //'input_image_filename_and_location'
// Resizes to whichever is larger, width or height
if($thumb->getImageHeight() <= $thumb->getImageWidth()){
// Resize image using the lanczos resampling algorithm based on width
$thumb->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
}else{
// Resize image using the lanczos resampling algorithm based on height
$thumb->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}
// Set to use jpeg compression
$thumb->setImageCompression(Imagick::COMPRESSION_JPEG);
$thumb->setImageCompressionQuality(100);
// Strip out unneeded meta data
$thumb->stripImage();
// Writes resultant image to output directory
$thumb->writeImage($thumbsPath.basename($image)."_thumb.jpg"); //'output_image_filename_and_location'
// Destroys Imagick object, freeing allocated resources in the process
$thumb->destroy();
}
} echo '<img src="'.$thumbsPath.basename($image)."_thumb.jpg".'" />' . "<br/>";
}
?>
At the moment, the output from the echo isn't showing anything, but the rest of the script is working properly (i.e. generating thumbnail images in a thumbs directory).
I'm guessing i'm not formatting my echo properly. This script is called in my index.php as <?php buildThumbGallery(); ?> inside a styled <div> tag.

cut video thumbnails in php

I have found a code that pull out a thumbnail from a video and its work!
but when I trying to make the php file to print the image with the Content-Type its return an error, when i tried to save it to the server its work fine!
the code:
<?php
function captureVideoPosterImg($movie_file = '')
{
extension_loaded('ffmpeg');
// Instantiates the class ffmpeg_movie so we can get the information you want the video
$movie = new ffmpeg_movie($movie_file);
// Get The duration of the video in seconds
echo $Duration = round($movie->getDuration(), 0);
// Get the number of frames of the video
$TotalFrames = $movie->getFrameCount();
// Get the height in pixels Video
$height = $movie->getFrameHeight();
// Get the width of the video in pixels
$width = $movie->getFrameWidth();
//Receiving the frame from the video and saving
// Need to create a GD image ffmpeg-php to work on it
$image = imagecreatetruecolor($width, $height);
// Create an instance of the frame with the class ffmpeg_frame
$Frame = new ffmpeg_frame($image);
// Choose the frame you want to save as jpeg
$thumbnailOf = (int) round($movie->getFrameCount() / 2.5);
// Receives the frame
$frame = $movie->GetFrame($thumbnailOf);
// Convert to a GD image
$image = $frame->toGDImage();
// Save to disk.
//echo $movie_file.'.jpg';
header('Content-Type: image/jpeg');
imagejpeg($image,null,100);
}
echo captureVideoPosterImg("smovie.mp4");
?>
the file in convert to UTF8 without bom.
thx!

Create Thumbnail of ONLINE PDF for first page only using Imagick

I tried to make a thumbnail of a pdf file which is hosted on another server. My current code is:
<?php
$im = new imagick("http://www.d3publisher.us/Walkthroughs/Naruto_NC_3_DS.pdf");
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>
The problem is that code is only generating thumbnail for LAST PAGE of the pdf file. How can I make a thumbnail for first page only? I tried to add [0] at the imagick line.
$im = new imagick("http://www.d3publisher.us/Walkthroughs/Naruto_NC_3_DS.pdf[0]");
but it didn't work. It only work for local pdf file, i.e:
$im = new imagick("my-pdf-file.pdf[0]");
Please help me solve this problem.. Thanks..
You'll need to reset the active image to the first page. This can be done with Imagick::setIteratorIndex.
<?php
$im = new imagick("http://www.d3publisher.us/Walkthroughs/Naruto_NC_3_DS.pdf");
$im->setIteratorIndex(0);
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>
Try...
$im->setImageIndex(0); //this will return 1th page of the pdf file
$im->setImageFormat('jpg');
"This can be done with Imagick::setIteratorIndex. .."
..or not. Simply has no effect . Setting it to one crashes something, setting it to 0 gets the last page..
function make_thumbnail($filename)
{
try
{
$imagick= new Imagick($filename);
}
catch(ImagickException $e)
{
// failed to make a thimbynail. what now?
// load up our trusty truetype font png instead?
$imagick->destroy();
return "0"; // shove any rubbish in the db - it will just say no image available when asked.
}
$imagick->setIteratorIndex(0);// rewind to first page or image of a multi series
$imagick->setImageFormat("png"); // turn it into a png
$imagick = $imagick->flattenImages(); // remove any transparency
$imagick->scaleImage(300,0); //resize...to less than 300px wide
$d = $imagick->getImageGeometry();
$h = $d['height'];
if($h > 300)
$imagick->scaleImage(0,300);
$imagick->setImageCompression(\Imagick::COMPRESSION_UNDEFINED);
$imagick->setImageCompressionQuality(0);
$imagick->setIteratorIndex(0);
$a = $imagick->getImageBlob(); // output as bytestream
$imagick->destroy();
return $a;
}

Categories