I am using a php script to convert PDF files into images when users upload supporting documentation. It is working great, however ocasionaly it creates 2 near identical files and appends "-0" and "-1". This is throwing me for a loop because my script does not know when this happens and then points to the wrong file name. Any idea what causes this and how to correct would be greatly appreciated.
This is the code:
$filename = $_FILES['file']['name'];
$filename1 = $upload_dir.$_FILES['file']['name'];
rename($_FILES['file']['tmp_name'], $upload_dir.$_FILES['file']['name']);
chmod($filename, 0777);
//If the file is a pdf change it to a jpg.
$file_array = explode(".", strtolower($filename));
$file_jpg = $file_array[0];
$file_jpg = $upload_dir.$file_jpg . ".jpg";
$file_extn = end(explode(".", strtolower($filename)));
if($file_extn == 'pdf'){
$filename3 = substr($filename1, 0, -3);
$filename3 = $filename3 . "jpg";
$createjpgpath = $filename3;
$basefile_jpg = substr($filename, 0, -3) . "jpg";
exec('convert -geometry 1600x1600 -density 130x130 -quality 20 "'.$filename1.'" "'.$filename3.'"');
unlink($filename1);
}
Else{
$filename3 = $upload_dir.$_FILES['file']['name'];
$basefile_jpg = $filename;
}
This is what I use:
exec('convert "'.$targetFile.'[0]" -flatten -geometry 1600x1600 -density 130x130 -quality 20 "'.$previewTargetFile.'"');
The "[0]" and "-flatten" will flatten the file and output only one image. Some PDF's have multiple pages.
Related
i am trying to convert ico format file to png format
$media_url ="https://static.licdn.com/scds/common/u/images/logos/favicons/v1/favicon.ico"
$filePath = public_path('media_downloads').'/pnff.png';
file_put_contents($filePath, file_get_contents($media_url));
$s3 = \Storage::disk('s3');
$res = $s3->put($filePath, file_get_contents($img), 'public');
$downloadUrl = \Storage::disk('s3')->url($filePath);
i got s3 url but the file is not opening i think it is corrupted how can i change the image content type while saving to a folder also in s3
i have done ico to png convertion by using Imagick Thanks #aynber #Chris Haas for the guidance
use Imagick;
$file = $media_url;
$extension = pathinfo(parse_url($file, PHP_URL_PATH), PATHINFO_EXTENSION);
$filename = 'linkedin_thumbnail' . time() . '.' . $extension;
$local_file_path = public_path('media_downloads') . '/' . $filename;
$contents = file_get_contents($file);
file_put_contents($local_file_path, $contents);
$image = new Imagick();
$image->readImage($local_file_path);
$image->cropThumbnailImage(100,100);
$image->setImageFormat("png");
header("Content-type: image/png");
$filePath2 = public_path('media_downloads').'/'.date('ymdhis').'.png';
$image->writeImage( $filePath2 );
$media_url = $filePath2;
unlink($local_file_path);
unlink($filePath2);
I use for my site OneFileManager and I wish to modify a file to keep transparency on PNG files.
This modification must apparently be done on the file Console.php and would aim to keep the transparency of PNG images or possibly replace it with white (the images being posted on instagram and instagram automatically replace transparency with white)
And the portion of the code to modify appears line 644. The dev currently transforms PNG into JPG but the problem is that the background is duplicated thanks to the colors of the non-transparent part
I changed from line 644 all values in PNG as below
Old code :
if ($ext == "png") {
$image = new \claviska\SimpleImage;
try {
$new_filename = uniqid(readableRandomString(8)."-") . ".jpg";
$image->fromFile($this->manager->getOption("path") . $filename)
->toFile($this->manager->getOption("path") . $new_filename, "image/jpeg");
#unlink($this->manager->getOption("path") . $filename);
$ext = "jpg";
$filename = $new_filename;
} catch (\Exception $e) {
return Common::error($e->getMessage());
}
}
With editing jpg to png
if ($ext == "png") {
$image = new \claviska\SimpleImage;
try {
$new_filename = uniqid(readableRandomString(8)."-") . ".png";
$image->fromFile($this->manager->getOption("path") . $filename)
->toFile($this->manager->getOption("path") . $new_filename, "image/png");
#unlink($this->manager->getOption("path") . $filename);
$ext = "png";
$filename = $new_filename;
} catch (\Exception $e) {
return Common::error($e->getMessage());
}
}
But this just made the transparent content no longer duplicated, but it keeps in the image the squares signifying the transparency of the image.
And i tried to use imagealphablending or imagesavealpha but no one work with OneFileManager or i dunno where to put this ^^'
If anyone can help me, thank you in advance ^^
i used from function crop_compress() to crop and compress image and then upload them
function crop_compress($source_url,$target_file,$qual) {
$image = imagecreatefromjpeg($source_url);
$width = imagesx($image);
$height = imagesy($image);
$thumb_width = $width;
$thumb_height = (9/16)*$width;
.
.
.
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
imagejpeg($thumb , $target_file,$qual);
return $target_file;}
$filename= 'crop_compress($_FILES["fileToUpload"]["tmp_name"][$key],$target_fileL,90)'
and it work fine.
now i want to upload this image with ftp and use ftp_put:
ftp_put($connecti,$target_file, $filename, FTP_BINARY);
and it work fine too, but it upload 2 times that i dont want.
one image in my directory and one with ftp
my question is how to avoid upload in my directory?
i know that ftp_put() and crop_compress() upload separately but i dont know which one should come first and how create a tmp_file to source in another or something else to avoid this problem?!
more info:
$target_dirL = "user"; #in the main host
$tempL=explode(".", $_FILES["fileToUpload"]["name"][$key]);
$target_fileL = $target_dir .$username1. '.' . end($tempL);
$target_dir = "user/$username/"; #another host
$temp=explode(".", $_FILES["fileToUpload"]["name"][$key]);
$target_file = $target_dir .$username1. '.' . end($temp);
$connecti = ftp_connect($anotherHost) or die('Couldn\'t connect to ftp server');
Use unlink( $filename ); after ftp_put($connecti,$target_file, $filename, FTP_BINARY);
This will delete the file after it had been uploaded via FTP.
I'm trying to create a pdf thumbnail with Imagick and save it on the server in the same location as the pdf. The code below works fine as is. The problem is that I don't want to echo the image. But if I remove the echo statement, the resulting jpg file contains errors and is unreadable. How can I create the thumbnail and write to a file without sending it to the browser?
$pdfThumb = new \imagick();
$pdfThumb->setResolution(10, 10);
$pdfThumb->readImage($filePath . $fileName . $fileExt . '[0]');
$pdfThumb->setImageFormat('jpg');
header("Content-Type: image/jpeg");
echo $pdfThumb;
$fp = fopen($filePath . $fileName . '.jpg', "x");
$pdfThumb->writeImageFile($fp);
fclose($fp);
DaGhostman Dimitrov provided some helpful code on #16606642, but it doesn't work for me for some reason.
I would try:
$pdfThumb = new imagick();
$pdfThumb->setResolution(10, 10);
$pdfThumb->readImage($filePath . $fileName . $fileExt . '[0]');
$pdfThumb->setImageFormat('jpg');
$fp = $filePath . $fileName . '.jpg';
$pdfThumb->writeImage($fp);
Bonzo's answer requires imagick on the webserver. If imagick is not on the webserver you can try to execute imagemagick from the commandline by php command exec():
exec('convert -thumbnail "178^>" -background white -alpha remove -crop 178x178+0+0 my_pdf.pdf[0] my_pdf.png')
And if you like to convert all pdfs in one step from same folder where your script is located try this:
exec('for f in *.pdf; do convert -thumbnail "178^>" -background white -alpha remove -crop 178x178+0+0 "$f"[0] "${f%.pdf}.png"; done');
In this examples I create a png thumbnail 178x178 pixel from the first page (my_pdf.pdf[0] the 0 means first pdf page).
I want to convert a uploaded image to its original format, (jpg, jpeg rpng, etc.) but I need to re-size these images to be 150px width and 210px height. Is it possible to change the size while copying, or do I have to convert it?
This was unsucessful:
$uploaddir1 = "/home/myweb/public_html/temp/sfds454.png";
$uploaddir2 = "/home/myweb/public_html/images/sfds454.png";
$cmd = "/usr/bin/ffmpeg -i $uploaddir1 -vframes 1 -s 150x210 -r 1 -f mjpeg $uploaddir2";
#exec($cmd);
You can use gd instead of ffmpeg. To convert or resize an image, see this example: http://ryanfait.com/resources/php-image-resize/resize.txt
Php lib for gd:
http://php.net/manual/en/function.imagecopyresampled.php
There is also some samples of resizing scripts in that page.
I recently had to solve just this problem, and implemented this simple caching solution:
<?php
function send($name, $ext) {
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/$ext");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
fpassthru($fp);
exit;
}
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (isset($_REQUEST['fp'])) {
$ext = pathinfo($_REQUEST['fp'], PATHINFO_EXTENSION);
$allowedExt = array('png', 'jpg', 'jpeg');
if (!in_array($ext, $allowedExt)) {
echo 'fail';
}
if (!isset($_REQUEST['w']) && !isset($_REQUEST['h'])) {
send($_REQUEST['fp']);
}
else {
$w = $_REQUEST['w'];
$h = $_REQUEST['h'];
//use height, width, modification time and path to generate a hash
//that will become the file name
$filePath = realpath($_REQUEST['fp']);
$cachePath = md5($filePath.filemtime($filePath).$h.$w);
if (!file_exists("tmp/$cachePath")) {
exec("gm convert -quality 80% -colorspace RGB -resize " .$w .'x' . $h . " $filePath tmp/$cachePath");
}
send("tmp/$cachePath", $ext);
}
}
?>
Some things that I noticed:
Graphicsmagick converted much faster than imagemagick, although I did not test conversion with cuda processing.
For the final product I re-implemented this code in ASP using the language's native graphics library. This was much faster again but would break if out-of-memory errors occurred (worked fine on my workstation, but wouldn't work on 4GB RAM server).