Rotate an image on same page - php

I want to rotate an uploaded and retrieved image from one location. Yes i am almost done. But the problem is, due to header("content-type: image/jpeg") the page redirected to another/or image format. I want to display it in same page as original image in. Here my code..
$imgnames="upload/".$_SESSION["img"];
header("content-type: image/jpeg");
$source=imagecreatefromjpeg($imgnames);
$rotate=imagerotate($source,$degree,0);
imagejpeg($rotate);
i also did with css property.
echo "<img src='$imgnames' style='image-orientation:".$degree."deg;' />";
But anyway my task is to done only with php. Please guide me, or give any reference you have
thanks advance.

<?php
// Okay, so in your upload page
$imgName = "upload/".$_SESSION["img"];
$source=imagecreatefromjpeg($imgName);
$rotate=imagerotate($source, $degree,0);
// you generate a PHP uniqid,
$uniqid = uniqid();
// and use it to store the image
$rotImage = "upload/".$uniqid.".jpg";
// using imagejpeg to save to a file;
imagejpeg($rotate, $rotImage, $quality = 75);
// then just output a html containing ` <img src="UniqueId.000.jpg" />`
// and another img tag with the other file.
print <<<IMAGES
<img src="$imgName" />
<img src="$rotName" />
IMAGES;
// The browser will do the rest.
?>
UPDATE
Actually, while uniqid() usually works, we want to use uniqid() to create a file. That's a specialized usage for which there exists a better function, tempnam().
Yet, tempnam() does not allow a custom extension to be specified, and many browsers would balk at downloading a JPEG file called "foo" instead of "foo.jpg".
To be more sure that there will not be two identical unique names we can use
$uniqid = uniqid('', true);
adding the "true" parameter to have a longer name with more entropy.
Otherwise we need a more flexible function that will check if a unique name already exists and, if so, generate another: instead of
$uniqid = uniqid();
$rotImage = "upload/".$uniqid.".jpg";
we use
$rotImage = uniqueFile("upload/*.jpg");
where uniqueFile() is
function uniqueFile($template, $more = false) {
for ($retries = 0; $retries < 3; $retries++) {
$testfile = preg_replace_callback(
'#\\*#', // replace asterisks
function() use($more) {
return uniqid('', $more); // with unique strings
},
$template // throughout the template
);
if (file_exists($testfile)) {
continue;
}
// We don't want to return a filename if it has few chances of being usable
if (!is_writeable($dir = dirname($testfile))) {
trigger_error("Cannot create unique files in {$dir}", E_USER_ERROR);
}
return $testfile;
}
// If it doesn't work after three retries, something is seriously broken.
trigger_error("Cannot create unique file {$template}", E_USER_ERROR);
}

You need to generate the image separately - something like <img src="path/to/image.php?id=123">. Trying to use it as a variable like that isn't going to work.

Related

How to resolve this Laravel issue - The "/tmp/phpY14gRo" file does not exist or is not readable?

I need to create PDF's thumbnail every time it gets loaded via POST method.
Once I upload the file inside Controller, it runs getThumb function that uses Imagick to create thumbnail. The problem is that everytime I do that, this request breaks and shows this error - The "/tmp/phpY14gRo" file does not exist or is not readable..
Imagick is properly installed. I use php-7.2-apache docker image.
But if I run shell_excec script that does absolutely the same thing, it works! That eliminates all suspicions of the wrong dependency installation
Here's the function from my controller:
public function createThumb($source, $target, $size = 256, $page = 1)
{
if (file_exists($source) && !is_dir($source)): // source path must be available and not be a directory
if (mime_content_type($source) != 'application/pdf'):
return FALSE; // source is not a pdf file returns a failure
endif;
$sepa = '/'; // using '/' as file separation for nfs on linux.
$target = dirname($source) . $sepa . $target;
$size = intval($size); // only use as integer, default is 256
$page = intval($page); // only use as integer, default is 1
$page--; // default page 1, must be treated as 0 hereafter
if ($page < 0) {
$page = 0;
} // we cannot have negative values
//It breaks exactly right here
$img = new Imagick($source . "[$page]"); // [0] = first page, [1] = second page
$imH = $img->getImageHeight();
$imW = $img->getImageWidth();
if ($imH == 0) {
$imH = 1;
} // if the pdf page has no height use 1 instead
if ($imW == 0) {
$imW = 1;
} // if the pdf page has no width use 1 instead
$sizR = round($size * (min($imW, $imH) / max($imW, $imH))); // relative pixels of the shorter side
$img->setImageColorspace(255); // prevent image colors from inverting
$img->setImageBackgroundColor('white'); // set background color and flatten
$img = $img->flattenImages(); // prevents black zones on transparency in pdf
$img->setimageformat('jpeg');
if ($imH == $imW) {
$img->thumbnailimage($size, $size);
} // square page
if ($imH < $imW) {
$img->thumbnailimage($size, $sizR);
} // landscape page orientation
if ($imH > $imW) {
$img->thumbnailimage($sizR, $size);
} // portrait page orientation
if (!is_dir(dirname($target))) {
mkdir(dirname($target), 0777, true);
} // if not there make target directory
$img->writeimage($target);
$img->clear();
$img->destroy();
if (file_exists($target)) {
return $target;
} // return the path to the new file for further processing
endif;
return FALSE; // the source file was not available, or Imagick didn't create a file, so returns a failure
}
I thought that it was permission problems but found out that it's not.
Update:
If I initialize Imagick without parameters it won't throw errors and thus won't create thumbnail as it doesn't get file path. So, whenever I add file path and PHP starts searching for that file, and the error occurs. Inside the log, I noticed that the InvalidArgumentException exception was thrown by a Symfony framework.
Here's an image of the error:
After debugging I found out that Imagick was not imported into the project.
So, I just added use Imagick at the top of my Controller.
In my case i call $validator->fails() two times.
In my case, the first call $validator->fails() in my Controller action, after checking deleted the file. The second call could not find this file.

PHP - Simple script for image compression with pngquant

:) i found this 1 line of code in another post which successfully compresses the image using pngquant. the thing is, it outputs the optimised image with a different name (obviously to preserve the original).
im trying to find a way to:
a) add a minimum quality parameter of 60
b) use an if/else statement to to allow the user to choose to overwrite the existing file or output a new optimised image (of a user specified name)
thank you! ntlri - not to long read it
<?php system('pngquant --quality=85 image.png'); ?>
so what i have tried is the following.. for some reason the single quotes need to be double quotes to parse the variables correctly..
<?php
$min_quality = 60; $max_quality = 85;
$keep_original = 'dont_keep';
if ($keep_original == 'keep') {
$image_name = 'image.png';
$path_to_image = 'images/' . $image_name;
$new_file = 'image2.png';
$path_to_new_image = 'images/' . $new_file;
// don't know how to output to specified $new_file name
system("pngquant --quality=$min_quality-$max_quality $path_to_image");
} else {
$image_name = 'image.png';
$path_to_image = 'images/' . $image_name;
// don't know if you can overwrite file by same name as additional parameter
system("pngquant --quality=$min_quality-$max_quality $path_to_image");
// dont't know how you get the name of the new optimised image
$optimised_image = 'images/' . $whatever_the_optimised_image_is_called;
rename($optimised_image, $image_name);
unlink($optimised_image);
}
?>
from the docs of this program :
The output filename is the same as the input name except that\n\ it
ends in \"-fs8.png\", \"-or8.png\" or your custom extension
so , for this question:
// don't know how to output to specified $new_file name
system("pngquant --quality=$min_quality-$max_quality $path_to_image");
to choose a new name, assume you are compress image name.png :
--ext=_x.png
this will create new image called name_x.png
so , your $new_file would be just a suffix ,
$new_file = '_x.png'; // to choose new file name name_x.png
// don't know if you can overwrite file by same name as additional
parameter
as mentioned in the program docs , the new file name will be suffixed by either -fs8.png or -or8.png , so you may rename the file which will produced with this suffix , OR simply set the --ext option to : .png and this will append to the original file
--ext=.png
for more details, check the repository
i spoke to pornel whos the chappie that developed pngquant. its actually a lot simpler than all that i wrote that before...
! important - it is very important to use escapeshellarg() else people can take over your server by uploading a file with a special filename apparently.
$image_name = 'image.png';
$target_file = 'images/' . $image_name;
$existing_image = 'image.png'; // image already on server if applicable
$keep = 'keep';
$target_escaped = escapeshellarg($target_file);
if ($keep == 'keep') {
// process/change output file to image_compressed.png keeping both images
system("pngquant --force --quality=70 $target_escaped --ext=_compressed.png");
$remove_ext = substr($newFileName, 0 , (strrpos($newFileName, ".")));
// $new_image is just the name (image_compressed.png) if you need it
$new_image = $remove_ext . '_compressed.png';
// remove old file if different name
if ($existing_image != $newFileName) {
$removeOld = '../images/' . $existing_image;
unlink($removeOld);
} // comment out if you want to keep existing file
} else {
// overwrite if file has the same name
system("pngquant --force --quality=70 $target_escaped --ext=.png");
// remove old file if different name
if ($existing_image != $newFileName) {
$removeOld = '../images/' . $existing_image;
unlink($removeOld);
}
$new_image = $newFileName;
}
to override same name use this command
pngquant.exe --ext=.png --force input.png
so the output name will remain input.png

get random background image using php

I want to get a random background image using php. Thats done easy (Source):
<?php
$bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' );
$i = rand(0, count($bg)-1);
$selectedBg = "$bg[$i]";
?>
Lets optimize it to choose all background-images possible inside a folder:
function randImage($path)
{
if (is_dir($path))
{
$folder = glob($path); // will grab every files in the current directory
$arrayImage = array(); // create an empty array
// read throught all files
foreach ($folder as $img)
{
// check file mime type like (jpeg,jpg,gif,png), you can limit or allow certain file type
if (preg_match('/[.](jpeg|jpg|gif|png)$/i', basename($img))) { $arrayImage[] = $img; }
}
return($arrayImage); // return every images back as an array
}
else
{
return('Undefine folder.');
}
}
$bkgd = randImage('image/');
$i = rand(0, count($bkgd)-1); // while generate a random array
$myRandBkgd = "$bkgd[$i]"; // set variable equal to which random filename was chosen
As I am using this inside a wordpress theme, I need to set the $bkgd = randImage('image/'); relative to my theme folder. I thought, I could do that using:
$bgfolder = get_template_directory_uri() . '/images/backgrounds/';
bkgd = randImage($bgfolder);
When I test $bgfolder, which seems to be the most important part, using var_dump() I receive a not working path:
http://yw.hiamovi-client.com/wp-content/themes/youthwork string(19) "/images/backgrounds"
Somehow there is a space before the /images/backgrounds/. I have no idea where this comes from! …?
You'll want to change
$myRandBkgd = "$bkgd[$i]";
to
$myRandBkgd = $bkgd[$i];
If that doesn't help, use var_dump() instead of echo() to dump some of your variables along the way and check if the output corresponds to your expectations.

Replace default image with random image from same folder

I'm just learning php and am stuck on a basic problem. I'd like my site to display one of ten random images (1.png ... 10.png) if a user doesn't choose an image. Currently it just displays a single image by default. There is a thumbnail and full size version of this image.
I've found the file where this is controlled is:
<?php
class Sabai_Helper_NoImageUrl extends Sabai_Helper
{
public function help(Sabai $application, $small = false)
{
$file = $small ? 'no_image_small.png' : 'no_image.png';
return $application->getPlatform()->getAssetsUrl() . '/images/' . $file;
}
}
I've tried to replace 'no_image_small.png' with the names of my images typed out in quotes ('1.png', '2.png',...). Other answers I've seen on stackoverflow are a little too advanced for me to apply as I don't know where to add arrays for both the 'no_image_small.png' and 'no_image.png'.
Thanks very much
I'm not sure what framework you are using, what classes are extended, but try this:
class Sabai_Helper_NoImageUrl extends Sabai_Helper
{
public function help(Sabai $application, $small = false)
{
$random = rand(1, 10);
$file = $small ? $random.'_small.png' : $random.'.png';
return $application->getPlatform()->getAssetsUrl() . '/images/' . $file;
}
}
This assumes, that the images "1.png".."10.png" and "1_small.png".."10_small.png" are located in the same directory, where no_image_small.png and no_image.png are stored.
For example:
$random = rand(1, 10); // generating random number and saving to $random variable
echo $random.'.png'; // concatenating random number to .png extension
Outputs:
8.png
or any other from 1 to 10
This should set $file variable with the correct image.
Reference: rand
Try using php rand()
You can use rand(1,10) this means echo out a random numbers from 1 to 10.
like for example: echo rand(1,10)."jpg";

Exempting pdf, doc, and xls from screen grab utility

I'm using the following code and an open service provided by wordpress to grab a screenshot thumbnail of a number of webpages on the fly
<img alt="<?php the_title(); ?>" src="http://s.wordpress.com/mshots/v1/<?php echo urlencode( get_post_meta(get_the_ID(), 'mjwlink-url', true )); ?>?w=300">
Problem is some of the links go to PDF, DOC or XLS files, in those cases I'd like to display a single alternative image.
I have absolutely no idea how to go about using the url in this way + given the fact I'm using urlencode I'm not sure it's even possible - any tips/advice/code appreciated.
Example outputs:
http://s.wordpress.com/mshots/v1/http%3A%2F%2Fwww.reform.co.uk%2Fportals%2F0%2Fdocuments%2Fitcanbedonesingle.pdf?w=300
http://s.wordpress.com/mshots/v1/http%3A%2F%2Fwww.outoftrouble.org.uk%2F?w=300
The thing to do would be to check the file type, even by simply checking what comes after the dot.
You can check this before your statement like this:
$types = array('.pdf', '.doc', '.xls');
if(0 < count(array_intersect(array_map('strtolower', $filename, $types)))) {
//go get the image
} else {
//do whatever else you want to
}
where $types can include any types that you want to process differently, and $filename is the name of the file, obviously.
Taken from here, but slightly modified in your case.
$types = array('pdf', 'doc', 'xls');
$path_parts = pathinfo($filename);
if(!in_array($path_parts['extension'], $types)) {
//go get the image
} else {
//do whatever else you want to
}

Categories