I have a script for capture a video with your webcam, and convert this video to a .gif.
I have this script for resize and save the file with PHP in .gif :
$image = new Imagick();
$decoded = base64_decode($gif);
$image->readimageblob($decoded);
$image = $image->coalesceImages();
foreach ($image as $frame) {
$frame->cropImage($w, $h, $x, $y);
$frame->thumbnailImage(117, 135);
$frame->setImagePage(117, 135, 0, 0);
}
$image_name = uniqid(rand()).'.gif';
$image = $image->deconstructImages();
$image->writeImages('uploads/profiles/'.$image_name, true);
return $image_name;
So, with this script, i retrieve .gif with a sizez of 400-500ko, i think it's very big for a simply gif of 117px/135px...
How can i optimize this gif for reduce the size ? Thanks !
It's very large because it is an animated GIF, which has multiple frames. One option is to use Imagick::optimizeImageLayers() to optimize the layers of the image.
Here's an example (from PHP documentation):
<?php
/* create new imagick object */
$im = new Imagick("test.gif");
/* optimize the image layers */
$im->optimizeImageLayers();
/* write the image back */
$im->writeImages("test_optimized.gif", true);
?>
you can skip some frames to make it smaller
// Use every other frame only
foreach ($image as $k => $frame) {
if ($k%2) { // Use last frame if odd
$frame = $lastFrame;
} else {
$frame->cropImage($w, $h, $x, $y);
$frame->thumbnailImage(117, 135);
$frame->setImagePage(117, 135, 0, 0);
}
$lastFrame = $frame;
}
you can use ob_gzhandler in php
for more detail look this
http://php.net/manual/en/function.ob-gzhandler.php
or
this sample maybe help you
http://www.devirtuoso.com/2009/07/how-to-compress-cssjavascript-files-with-php/
if none did not help ,you can use system function and use terminal or command line command
for compress you result file with os commands
be successfull
Related
I followed this example to embed text in image while uploading it but it's not working.
This is my code:
header('Content-type: image/jpeg');
$img = $_FILES['mainImage']['name'];
list($txt, $ext) = explode(".", $img);
$imgName = "ac_".time().".".$ext;
$tmp = $_FILES['mainImage']['tmp_name'];
$textToImage = imagecreatefromjpeg($tmp);
// Allocate A Color For The Text
$white = imagecolorallocate($textToImage, 255, 255, 255);
// Set Path to Font File
$font_path = '../assets/fonts/font.ttf';
// Set Text to Be Printed On Image
$text = "Test text";
// Print Text On Image
imagettftext($textToImage, 25, 0, 75, 300, $white, $font_path, $text);
$imageUploaded = move_uploaded_file($tmp, 'images_path/'.$imgName);
if(!$imageUploaded){
die('Error upload image!');
}
The image is uploaded but wihout text in it !
For this we are working with GD library.
"PHP is not limited to creating just HTML output. It can also be used
to create and manipulate image files in a variety of different image
formats, including GIF, PNG, JPEG, WBMP, and XPM. Even more
convenient, PHP can output image streams directly to a browser. You
will need to compile PHP with the GD library of image functions for
this to work. GD and PHP may also require other libraries, depending
on which image formats you want to work with."
You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.
The following code sample demonstrates the use of GD library to watermark images on the fly. The method demonstrated here to watermark an uploaded image is to overlay the original image with another image, preferably a transparent PNG image.
PHP provides a rich set of functions to create and alter images on the fly. These functions require the GD library, which is bundled with PHP since version 4.3.
The HTML form needs a file upload element: <input type="file">. You must also specify the correct encoding type: enctype="multipart/form-data" for the form.
/ link to the font file no the server
$fontname = 'font/Capriola-Regular.ttf';
// controls the spacing between text
$i=30;
//JPG image quality 0-100
$quality = 85;
function create_image($user){
global $fontname;
global $quality;
$file = "covers/".md5($user[0]['name'].$user[1]['name'].$user[2]['name']).".jpg";
// if the file already exists dont create it again just serve up the original
if (!file_exists($file)) {
// define the base image that we lay our text on
$im = imagecreatefromjpeg("pass.jpg");
// setup the text colours
$color['grey'] = imagecolorallocate($im, 54, 56, 60);
$color['green'] = imagecolorallocate($im, 55, 189, 102);
// this defines the starting height for the text block
$y = imagesy($im) - $height - 365;
// loop through the array and write the text
foreach ($user as $value){
// center the text in our image - returns the x value
$x = center_text($value['name'], $value['font-size']);
imagettftext($im, $value['font-size'], 0, $x, $y+$i, $color[$value['color']], $fontname,$value['name']);
// add 32px to the line height for the next text block
$i = $i+32;
}
// create the image
imagejpeg($im, $file, $quality);
}
return $file;
}
function center_text($string, $font_size){
global $fontname;
$image_width = 800;
$dimensions = imagettfbbox($font_size, 0, $fontname, $string);
return ceil(($image_width - $dimensions[4]) / 2);
}
$user = array(
array(
'name'=> 'Slimen Tunis',
'font-size'=>'25',
'color'=>'black'),
array(
'name'=> 'Web developer',
'font-size'=>'16',
'color'=>'grey'),
array(
'name'=> 'SlimenTunis#webdeveloper.com',
'font-size'=>'13',
'color'=>'green'
)
);
// run the script to create the image
$filename = create_image($user);
here we have two functions to make it as simple as possible. To run the code simply pass the $user array data to the function and it’ll save the new image in the folder ‘covers’ on your server. The function returns the file url so you just need to echo it into an image tag as shown below. Check out the demo where you can create your own.
$filename = create_image($user);
<img src="<?=$filename;?>" width="800" height="600"/>
You can try using the Intervention library. I use it for doing what you're asking about. It is quite simple to understand and the documentation is is well-written.
So, i have a script for resize, save a gif and save a preview image of this gif on my server.
This is my script :
public function createImageGif($gif, $x, $y, $w, $h)
{
$image = new Imagick();
$decoded = base64_decode($gif);
$image->readimageblob($decoded);
$image = $image->coalesceImages();
$image_name = uniqid(rand()).'.gif';
foreach ($image as $frame) { //gif creation
$frame->cropImage($w, $h, $x, $y);
$frame->thumbnailImage(117, 135);
$frame->setImagePage(117, 135, 0, 0);
}
$image = $image->deconstructImages();
$image->writeImages('uploads/profiles/'.$image_name, true);
//preview creation
$im = imagecreatefromstring($decoded);
if ($im !== false) {
header('Content-Type: image/gif');
$newimage = imagecreatetruecolor(117, 135);
imagecopyresampled($newimage, $im, 0, 0, $x, $y, 117, 135, $w, $h);
imagegif($newimage, 'uploads/profiles-preview/'.$image_name.'', 100);
imagedestroy($newimage);
imagedestroy($im);
}
return $image_name;
}
So, $gif is at first a long string blob (about 2 000 000 characters). At the end, gif size on my server is approximatly 300ko.
This script take more of 20s to execute. I have a good connexion and a good server.
How can i optimize this script ? Any ideas ?
Edit : this is my script for the creation of my data in javascript :
var base64data;
var img = document.createElement('img');
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
img.src = base64data;
}
Why your script uses a blob binary64 encoded as input? There are many sound reasons to do this thing, but are you sure it's necessary? Can't you just load the image from PHP temp's folder?
Maybe, you're uploading an image from a javascript function, through ajax, base-64 encoding an image (created on the fly from canvas?) and sending it as a string in a POST parameter
Also, I see that you first save your image, then re-open it for sending back the reply to the client. Why don't you send back the image you just resized (the one contained in the $image variable)
I have a problem here when I need create a image with transparent background. I still don´t know if the problem is with fabricjs or with php. Everything works fine when I sent a image with colored background. The problem occurs when I send a image with transparent background.
The generated image is created with black background.
So, let me explain better:
When the user click in save button, I´m sending the string representation of the canvas to php in the server-side, to be generated the image of the canvas. So I´m using the follow function to sending the string representation of the canvas by Ajax (POST function of jQuery):
function sendStringRepresentation(){
var strDataURI = canvas.toDataURL();
strDataURI = strDataURI.substr(22, strDataURI.length);
$.post("action/createImage.php",
{
str: strDataURI
},
function(data){
if(data == "OK"){
$("#msg").html("Image created.");
}
else{
$("#msg").html("Image not created.");
}
});
}
In PHP file I´m using the follow code to generate the image:
// createImage.php
$data = base64_decode($_POST["str"]);
$urlUploadImages = "../uploads/img/";
$nameImage = "test.png";
$img = imagecreatefromstring($data);
if($img) {
imagepng($img, $urlUploadImages.$nameImage, 0);
imagedestroy($img);
// [database code]
echo "OK";
}
else {
echo 'ERROR';
}
Again, the problem is just with background transparent canvas. With colored background everything works fine.
The last step is quite the opposite:
imagecopyresampled( $img, $alpha_image, 0, 0, 0, 0, $w, $h, $w, $h );
And voila! The image is transparent!
Why did you use GD for this? You can use file_put_contents for save png file from your canvas.
// createImage.php
$data = base64_decode($_POST["str"]);
$urlUploadImages = "../uploads/img/test.png";
file_put_contents($urlUploadImages, $data);
I don't know if this is exactly the problem you're experiencing, but some of the GD library's imagecreate* functions create images without the alpha channel.
The workaround I've found is to create an image using imagecreatetruecolor and copy your transparent image onto it.
Try a process like this:
$img = imagecreatefromstring($data);
$w = imagesx($img);
$h = imagesy($img);
$alpha_image = imagecreatetruecolor( $w, $h );
imagecopyresampled( $alpha_image, $img, 0, 0, 0, 0, $w, $h, $w, $h );
That should ensure that you end up with a "true color" image with the proper alpha channel.
JPG toDataURL transforms transparent background to black.
I had the exact same problem and added this
imageAlphaBlending($img, true);
imageSaveAlpha($img, true);
to rodrigopandini's code and it works perfect now.:)
// createImage.php
$data = base64_decode($_POST["str"]);
$urlUploadImages = "../uploads/img/";
$nameImage = "test.png";
$img = imagecreatefromstring($data);
imageAlphaBlending($img, true);
imageSaveAlpha($img, true);
if($img) {
imagepng($img, $urlUploadImages.$nameImage, 0);
imagedestroy($img);
// [database code]
echo "OK";
}
else {
echo 'ERROR';
}
Hello I am trying to combine two transparent png-24 images, both size 400width, 150height.
A background: ["http://www.fenixflame.net/Background-Zanaris-24.png"][1]
And the image I want to overlay adobe the background:
["http://www.fenixflame.net/Bandos-Slayer-24.png"][2]
I've tryed overlaying transparent images using php but only png-8 images. Can't use png-8 beacause the images just don't render correctly.
Edit: Code I've tryed:
$image = imagecreatefrompng("http://www.fenixflame.net/Background-Zanaris-24.png");
$frame = imagecreatefrompng("http://www.fenixflame.net/Bandos-Slayer-24.png");
//
//imagealphablending($frame,true);
//
$insert_x = imagesx($frame);
$insert_y = imagesy($frame);
imagecopymerge($image,$frame,0,0,0,0,$insert_x,$insert_y,100);
//
//# Save the image to a file imagepng($image, '/path/to/save/image.png');
imagepng($image, "/home1/fenixfla/public_html/Images/Signatures/NewImageBG.png");
//
//# Output straight to the browser.
imagepng($image);
//
I have write a small example to merge two transparent image in this link scitam.com
try this code it works fine.
$width = 200;
$height = 200;
$base_image = imagecreatefromjpeg("base.jpg");
$top_image = imagecreatefrompng("top.png");
$merged_image = "merged.png";
imagesavealpha($top_image, true);
imagealphablending($top_image, true);
imagecopy($base_image, $top_image, 0, 0, 0, 0, $width, $height);
imagepng($base_image, $merged_image);
Use GD Library to render the image and output it in php.
http://www.php.net/manual/en/ref.image.php
It gets pretty hairy after that. You have to use start doing things like
imagealphablending($image, false);
imagesavealpha($image, true);
and so on to make sure transparency is correct.
you can see an example of what I did for a client way back on their front page here. It was super tedious and a huge pain. Have fun
How about using lib ImageMagick composite (http://www.imagemagick.org/script/composite.php)
function composite() {
$command = "/usr/local/bin/composite [... your properties...]";
exec($command, $output, $result);
return ($result == 0 && $output[0] == "");
}
You might want to check this out: http://php.net/manual/en/function.imagecopymerge.php
The imagecopymerge function is part of the PHP GD library.
I was trying to crop the animated gif and in the output i'm getting the same sized image, but cropped.
A lot of empty space is filled with canvas.
For example i had animated gif 600x100, but have requested 100x100 crop, on the output i'm getting 600x100 image with cropped image and empty space.
Someone knows the solution for this issue?
$gif = new Imagick($s['src']);
foreach($gif as $frame){
$frame->cropImage($s['params']['w'], $s['params']['h'], $s['params']['x'], $s['params']['y']);
}
$gif->writeImages($s['dest_path'] .'/'. $fullname,true);
I've been having the same problem as you, and I found the solution was using the coalesceimages function.
Here's a working example for crop and resize an animated gif in php with Imagick:
<?php
// $width and $height are the "big image"'s proportions
if($width > $height) {
$x = ceil(($width - $height) / 2 );
$width = $height;
} elseif($height > $width) {
$y = ceil(($height - $width) / 2);
$height = $width;
}
$image = new Imagick(HERE_YOU_PUT_BIG_IMAGE_PATH);
$image = $image->coalesceImages(); // the trick!
foreach ($image as $frame) {
$frame->cropImage($width, $height, $x, $y); // You crop the big image first
$frame->setImagePage(0, 0, 0, 0); // Remove canvas
}
$image = $image->coalesceImages(); // We do coalesceimages again because now we need to resize
foreach ($image as $frame) {
$frame->resizeImage($newWidth, $newHeight,Imagick::FILTER_LANCZOS,1); // $newWidth and $newHeight are the proportions for the new image
}
$image->writeImages(CROPPED_AND_RESIZED_IMAGE_PATH_HERE, true);
?>
Code above is being used for generating thumbnails with same with and height.
You might change it the way you want.
Notice that when using $frame->cropImage($width, $height, $x, $y); you should put there the values you might need.
IE $frame->cropImage($s['params']['w'], $s['params']['h'], $s['params']['x'], $s['params']['y']);
Of course that if you just want to crop instead of croping and resizing, just can do this:
$image = new Imagick(HERE_YOU_PUT_BIG_IMAGE_PATH);
$image = $image->coalesceImages(); // the trick!
foreach ($image as $frame) {
$frame->cropImage($s['params']['w'], $s['params']['h'], $s['params']['x'], $s['params']['y']);
$frame->setImagePage(0, 0, 0, 0); // Remove canvas
}
Hope it helps!
Ps: sorry for my english :)
Often ImageMagick has a 'page' or working area, something like a background layer. It sounds like this is remaining after cropping the image (I had a confusing time working out some compositing and resizing behavior with the command line tool before...).
Checking out the PHP manual page for cropImage, I saw this comment:
Christian Dehning - 09-Apr-2010 10:57
When cropping gif-images (I had no problems with jpg and png images), the canvas is not removed. Please run the following command on the cropped gif, to remove the blank space:
$im->setImagePage(0, 0, 0, 0);