Suppose a user uploads a .txt or .php file, and I want to generate a .png thumbnail for it. Is there a simple way of doing it, that doesn't require me to open the file and write its contents into a new .png? I have ImageMagick and FFmpeg available, there must be a way to take advantage of that, but I've been looking a lot and no luck yet.
Thanks in advance.
You can use ffmpeg:
ffmpeg -video_size 640x480 -chars_per_frame 60000 -i in.txt -frames:v 1 out.png
However, it has some caveats:
By default it renders 6000 characters per frame, so it may not draw all of your text. You can change this with the -chars_per_frame and/or -framerate input options. Default frame rate is 25.
The text will not be automatically word wrapped so you will have to add line breaks for the text to fit your output video size.
You could always use php's imagettftext function.
It would give you a representation of what is in the text file.
http://php.net/manual/en/function.imagettftext.php
You can use PHP's class imagick to convert the file to image.
It will work for a txt file nicely.
try
{
$im = new imagick("inputfile.txt[0]");
if ($im)
{
$im->setImageAlphaChannel(imagick::ALPHACHANNEL_DEACTIVATE);
$im->setImageFormat('jpg');
$im->setImageCompressionQuality(85);
file_put_contents("outfile.jpg",$im->getImageBlob());
}
} catch(Exception $e)
{
echo "cannot process";
}
// When imagick is unable to read the file, it may wrongly
// set internal server error 500 status code.
// I do not understand why that happens, because the script
// continues normally. Anyway, lets overwrite it here for all cases.
header("HTTP/1.1 200 OK");
$image = new Imagick();
$image->readImage("text:" . $filename . "[0]");
$image->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1);
$image->setImageFormat('png');
$image->writeImage($linkImage);
Related
I have the following code in PHP to take the screenshot of first page of the PDF.
$name = getcwd()."\\testfile";
$img = new imagick();
$img->setResolution(200,200);
$img->readImage($name.'.pdf[0]');
$img->setImageResolution(100,100);
$img->resampleImage(100,100,imagick::FILTER_LANCZOS,1);
$img->setImageCompression(\Imagick::COMPRESSION_ZIP );
$img->setImageCompressionQuality('0');
$img->setImageFormat('png8');
$img->writeImage($name.".png");
header("Content-type : image/png");
echo $img;
This code produces the PNG of 62kb only in the Google Chrome's Resource monitor tab. But the image which is written by Imagick() is above 114kb. Just to make sure image isn't compressed and or any other issues i have used a online service called TinyPNG and they compressed the image shrinking it to exactly 62kb i get in browser...
What could be wrong in this code? Also i am using PNG8 format because thats more efficient.
Best
Ahsan
I think this is caused by your writeImage statement. If you write a PNG image without specifying png8: specifically in the filename your image will not be stored in that format. In essence setImageFormat will only affect when you retrieve the image as a string (echo $img).
If you do the following:
$img->writeImage ('png8:' . $name . ".png");
it should be stored as a png8. You can verify this with identify -verbose and checking the Depth / Channel Depth.
These are the default compression methods used for the following common image formats:
PNG: Imagick::COMPRESSION_ZIP
JPEG: Imagick::COMPRESSION_JPEG
GIF: Imagick::COMPRESSION_LZW
I want to be able to generate image thumbnails without saving them to the server. So far, I've come up with this code, but I'm not sure what to do with $code.
$code = system("convert galleries/13_0.jpg -resize 400x270 /dev/stdout");
How would I go about plugging $code into the PHP/HTML to get the raw image code to display as a jpg?
I would advise you not to do this from the system as you have described.
PHP has libraries for doing this sort of thing.
http://www.php.net/manual/en/ref.image.php.
http://php.net/manual/en/book.imagick.php.
And there are libraries the wrap these native functions for manipulating images. https://imagine.readthedocs.org/en/latest/
That way all your code is in PHP and you are not relying on the system to do anything (providing PHP has been compiled with the libraries as described. They are standard libraries available in most PHP builds and you can enable them if they are not included).
Edit: I'm advocating that you.
Open the source image.
Convert the source image
Return the source image
with imagine you would do it thus:
$imagine = new Imagine\Gd\Imagine();
$size = new Imagine\Image\Box(400, 270);
$imagine->open('/path/to/large_image.jpg')
->resize($size)
->show('jpg');
If the $code is the raw data, could you have another file getimage.php which would write the data out but set the header content type to image/JPEG? So your img src would be getimage.php?image=13_0.jpg for example?
I would save it to memory, then read it, then delete it. /dev/shm is a ramdrive on most Linux systems.
$tmp = '/dev/shm/'.uniqid('',true).'.jpg';
system("convert galleries/13_0.jpg -resize 400x270 $tmp");
header("Content-Type: image/jpeg");
header('Content-Length: '.filesize($tmp));
readfile($tmp);
unlink($tmp);
I'm using a generic PHP based CMS, i wanted to create a script which read the pdf created a thumbnail and cached it. There were lots of different answers, and i did have a fair few problems with different versions of imagick, but this is script which worked for me.
some people might find it useful and maybe someone could advice me if it is optimised?
<?php
$loc = *the file location*;
$pdf = *the file name*;
$format = "jpg";
$dest = "$loc$pdf.$format";
if (file_exists($dest))
{
$im = new imagick();
$im->readImage($dest);
header( "Content-Type: image/jpg" );
echo $im;
exit;
}
else
{
$im = new imagick($loc.$pdf.'[0]');
$im->setImageFormat($format);
$width = $im->getImageheight();
$im->cropImage($width, $width, 0, 0);
$im->scaleImage(110, 167, true);
$im->writeImage($dest);
header( "Content-Type: image/jpg" );
echo $im;
exit;
}
?>
Leverage PHP and ImageMagick to create PDF thumbnails
http://stormwarestudios.com/articles/leverage-php-imagemagick-create-pdf-thumbnails/
In this article, we discuss using PHP and ImageMagick to generate thumbnails from a given PDF, storing them in a temporary (or “cache”) directory, and serving them up to the web.
One of our more recent clients made a request to display PDF thumbnails published through the Joomla CMS that we’d deployed for them.
The requirement was fairly simple, but the execution was a little more involved. After installing ImageMagick, ImageMagick PHP bindings (which incidentally aren’t working, and a workaround was devised), and sleuthing some code, the following solution was determined:
<?php
function thumbPdf($pdf, $width)
{
try
{
$tmp = 'tmp';
$format = "png";
$source = $pdf.'[0]';
$dest = "$tmp/$pdf.$format";
if (!file_exists($dest))
{
$exec = "convert -scale $width $source $dest";
exec($exec);
}
$im = new Imagick($dest);
header("Content-Type:".$im->getFormat());
echo $im;
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
$file = $_GET['pdf'];
$size = $_GET['size'];
if ($file && $size)
{
thumbPdf($file, $size);
}
?>
The above code assumes that you’ve provided appropriate permissions to the temporary directory (usually chmod 755 or chmod 777, depending on your level of courage), that you’ve saved the above code snippet in a file called thumbPdf.php, and placed this somewhere visible on your web server.
After obtaining parameters from GET, the code checks the destination temporary directory, and if the desired image is not present, it uses ImageMagick’s convert program to generate the PDF thumbnail, sized down to the appropriate proportion, and saves the image in the temporary directory. Finally, it reloads the thumbnail into an ImageMagick PHP object, and outputs the content to the browser.
Invoking the above code is done fairly easily; simply call the PHP script from inside an image tag, like so:
<img src="/path/to/thumbPdf.php?pdf=your.pdf&size=200" />
The above code would generate a thumbnail from the first page of “your.pdf”, sized 200 pixels wide by an appropriately-proportioned height.
Good luck, and happy webmastering!
I know it's been discussed here:
Should I use a PHP extension for ImageMagick or just use PHP's Exec() function to run the terminal commands?
And to quote drew101:
You would benefit a lot using the PHP extensions instead of using exec
or similar functions. Built in extensions will be faster and use less
memory as you will not have to spawn new processes and read the output
back. The image objects will be directly available in PHP instead of
having to read file output, which should make the images easier to
work with.
If you have a busy site, creating lots of processes to edit images may
start to slow things down and consume additional memory.
If you have not installed the Imagick php library for some reason you may use the ghost script and generate thumbnail of an pdf using the below example :
exec('gs -dSAFER -dBATCH -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r300 -sOutputFile=xyz.jpg xyz.pdf');
<?php
if(isset($_GET['img']) && is_numeric($_GET['img'])){
$img = $_GET['img'];
$imgarray = array (
'1' => 'http://www.path/to/image1.png',
'2' => 'http://www.path/to/image2.png',
'3' => 'http://www.path/to/image3.png'
);
$src = $imgarray[$img];
header('Content-type: image/png');
echo file_get_contents($src);
}
else
{
header('Content-type: image/png');
echo 'Image could not be loaded';
}
?>
Hello again stackoverflow!
Im having multiple problems.
1: When the $_GET['img'] is set and its numeric, the image will be displayed right, but i want to add text in the upper-right corner of the image... How can i do that? I've looked through multiple GD tutorials and examples but i can't find my answer.
2: When $_GET['img'] isn't set i want to display the text: Image could not be loaded. How cna i do that? Because this doesn't seem to work...
Greetings
What you'll have to do is use GD. Load up the requested image into PHP with imagecreatefrompng(), since you have listed pngs in your array, you'd have to use imagecreatefromjpeg() or whatever depending on their format. Then use one of the text writers like imagestring() to write the text to the location in the image resource returned by imagecreatefrompng(), then return the image resource to the browser.
Can also use one of the functions that uses an external font, like imagettftext(), but would need to have the appropriate font to use on the server.
For the error, if you want it to be an image, you'll need to use imagecreatetruecolor() to make a new image, then use imagecolorallocate() to assign a color palette to it, then use imagestring() to write the error message to the image and return it. Of course, probably be easier just to make an error image in GIMP or something and return it, rather than going through the trouble of generating a new error image each time.
Just remove the line that says header('Content-type: image/png'); in your else{} block
That will do the trick. At the moment your are telling the user's browser to treat that text as an image, of course that can't work. If you want an image with the text "Image could not be loaded", it's more complicated than that...
I have a database that stores images in a MySQL BLOB field. I setup a script that selects and displays the images based on an ID in the URL, and I also made it so if you append ?resize=800x600, it would resize the image (in this case, to 800x600).
The host that I use doesn't have Imagemagick installed and won't let me do it myself, so I need to use PHP's GD library to resize the image.
But I've yet to find a function like Imagick's readImageBlob(), so I can't edit the binary string that I get from the database without first creating a temporary file, editing it, getting the binary string from it, sending it to the browser, and then deleting it (which is waaaay too many steps, especially since this will be getting a few thousand hits when it goes into production).
So my question is, is there any way to replicate readImageBlob with PHP's GD without going through the temporary file solution?
imagecreatefromstring() should do the trick. I think the function example in the manual is almost exactly what you need:
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
Where $data is your binary data string from the database.