how to prevent imagecreatefrom from creating a static gif - PHP - php

I have a script that sends an image it is saved as a .gif as declared in the movie.php file that will be listed below.
However, as I understand it, it creates an image from the gif making it useless for display because it simply becomes a static image .gif.
Anyway
I wanted to know how I can upload this file and ignore this function (imagecreatefromgif) I tried to change it in several ways and when I remove it I get an error, someone could help me work around this so that the gif will be sent and not be converted to a gif file static. basically I wanted that the way I sent the gif it would only be renamed with function imageGenerateName () but that it would keep all its size and property.
Every help is welcome.
Thanks in advance
.
Movie.php code:
<?php
class Movie {
public function imageGenerateName() {
return bin2hex(random_bytes(60)) . ".gif";
}
}
movie-process.php code
<?php
// Upload img
if(isset($_FILES["image"]) && !empty($_FILES["image"]["tmp_name"])) {
$image = $_FILES["image"];
$imageTypes = ["image/gif"];
$jpgArray = ["image/gif"];
// Check img type
if(in_array($image["type"], $imageTypes)) {
// Check img type
if(in_array($image["type"], $jpgArray)) {
$imageFile = imagecreatefromgif($image["tmp_name"]);
} else {
$imageFile = imagecreatefromgif($image["tmp_name"]);
}
// image name
$imageName = $movie->imageGenerateName();
imagegif($imageFile, "./img/movies/" . $imageName, 100);
$movie->image = $imageName;
}
}
// Upload img
if(isset($_FILES["image"]) && !empty($_FILES["image"]["tmp_name"])) {
$image = $_FILES["image"];
$imageTypes = ["image/gif"];
$jpgArray = ["image/gif"];
// Check img type
if(in_array($image["type"], $imageTypes)) {
// check type is gif
if(in_array($image["type"], $jpgArray)) {
$imageFile = imagecreatefromgif($image["tmp_name"]);
}
// generete img name
$movie = new Movie();
$imageName = $movie->imageGenerateName();
imagegif($imageFile, "./img/movies/" . $imageName, 100);
$movieData->image = $imageName;
}
}

Unfortunately, the imagecreatefromgif function will only read the first image of the gif as the PHP manual says.
I tried before to solve this, but there is no turnaround other than uploading the image without touching it. PHP uses the GD library and this library doesn't have the proper functionality to deal with gif images other than just saving the image with the *.gif extension.
So, this is my suggested solution:
// generete img name
$movie = new Movie();
$imageName = $movie->imageGenerateName();
move_uploaded_file($_FILES["image"]["tmp_name"],"./img/movies/" . $imageName);
$movieData->image = $imageName;

I think since you say you just want to save it as it is, with the same size and its all properties, you can use below code
<?php
$allowed = array('gif');
$filename = $_FILES["image"]['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($ext, $allowed)) {
// generete img name
$movie = new Movie();
$imageName = $movie->imageGenerateName();
$uploadResult = move_uploaded_file($_FILES['image']['tmp_name'], dirname( dirname( __FILE__ ) ).'/img/movies/'. $imageName );
if($uploadResult === true ){
$movie->image = $imageName;
}else{
throw new \Exception('Unable to copy file to the given path');
}
}
Or if you have access to the Imagick lib php extension refer to below link on how to install this php-extension
https://www.php.net/manual/en/imagick.setup.php
then using the functions in that library you can do
<?php
$allowed = array('gif');
$filename = $_FILES["image"]['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($ext, $allowed)) {
$image = new Imagick();
$image->readImage($_FILES["image"]["tmp_name"]);
$image = $image->coalesceImages();
foreach ($image as $frame) {
$frame->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
$frame->thumbnailImage($size_w, $size_h);
$frame->setImagePage($size_w, $size_h, 0, 0);
}
$image = $image->deconstructImages();
$image->writeImages(dirname( dirname( __FILE__ ) ).'/img/movies/'. $imageName, true);
}
?>

Related

Compress image with PHP not reducing image size

I'm trying to compress and upload an image to the server with PHP. The upload are working correctly (without any errors), however the image size remains the same after the upload has completed. Could someone please advise what I could possibly be doing wrong?
Please find the code below:
public function addcoverimageAction()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Sanitize POST array
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$userid = $this->route_params['userid'];
$thisuser = $userid;
$postid = $this->route_params['postid'];
$path_parts = pathinfo($_FILES['file']['name']);
$filename = $path_parts['filename'] . '_' . microtime(true) . '.' . $path_parts['extension'];
$directoryName = dirname(__DIR__) . "/images/$thisuser/listings/$postid/coverimage/";
// Check if directory exist
if (!is_dir($directoryName)) {
//If directory does net exist - create directory
mkdir($directoryName, 0777, true);
}
// Compress image
function compressImage($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
}
compressImage($_FILES['file']['tmp_name'], $directoryName . $filename, 60);
// Upload image
move_uploaded_file($_FILES['file']['tmp_name'], $directoryName . $filename);
}
$this->post = Post::findByID($postid);
Post::updateCoverimage($filename, $postid);
}
If it is working, then you're immediately overwriting the compressed file with the original, via the move_uploaded_file command, because you're sending it to the same destination as the compressed file, which was an earlier step.
The move_uploaded_file command is unnecessary in this case - you can remove it

Failed to rename image and upload using storeAs in Laravel

I created a form to store article with an image , and generate a resized version as thumbnail from it.
I want the image to be renamed after the article slug and stored in the "public/img/articles-images " directory but i keep receiving : "Image source not readable" error
This is the image upload handler function in my controller :
private function handleRequest($request)
{
$data = $request->all();
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $request->slug;
$successUploaded = $image->storeAs('img/articles-images', $fileName);
if($successUploaded) {
$width = config('cms.image.thumbnail.width');
$height = config('cms.image.thumbnail.height');
$extension = $image->getClientOriginalExtension();
$thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $fileName);
Image::make('img/articles-images' . '/' . $fileName)
->resize($width, $height)
->save('img/articles-images' . '/' . $thumbnail);
}
$data['image'] = $fileName;
}
return $data;
}
storeAs() method, which receives the path, the file name, and the (optional) disk as its arguments :
$successUploaded = $request->file('image')->storeAs(
'images', $fileName
);
I solved it ! Apparently there was no need to storeAs() method at all , the new code is like below :
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $request->slug.'.' .$image->getClientOriginalExtension();
$destination = $this->uploadPath;
$successUploaded = $image->move($destination, $fileName);
// //

Upload image with different name but keep file extension

When i save image with my form i change the file name. Everything works nice except file extension. When i change file name the extension is missing and file is saved without it. Please help me to solve my problem i want to store also image extension.
This is my code where i update image name.
$image = $request->file('image');
if ($image) {
$imgPath = 'public/post-image/';
$imgName = uniqid('img_');
$store = $request->file('image')->storeAs(
$imgPath, $imgName
);
$post->image = $imgName;
}
Try this:
$image = $request->file('image');
if ($image) {
$imgPath = 'public/post-image/';
$imgName = uniqid('img_') . '.' . $image->extension();
$store = $image->storeAs($imgPath, $imgName);
$post->image = $imgName;
}

How to change image name to current time stamp php?

I want to change image name with current time stamp in php.
My code are below :
$logo = basename($_FILES['file']['name']);
$logo = image1.jpg
move_uploaded_file($_FILES['file']['tmp_name'], '../timeTableImg/' . $_FILES['file']['name']);
i get image name in $logo. But Actually i want
$logo = 1484900616.jpg
move_uploaded_file($_FILES['file']['tmp_name'], '../timeTableImg/' . $_FILES['file']['name']);
file name may be dynamic. its may be jpg , png, jpeg. Also want to move file with new name.
Use move_uploaded_file function.
Example:
$file_path = "uploads/";
$newfile = date('m-d-Y_H:i:s')'.jpg';
$filename = $file_path.$newfile;
if(!file_exists($filename))
{
if(move_uploaded_file($_FILES['file']['tmp_name'],$filename))
{
// Other codes
}
}
else
{
echo 'file already exists';
}
Try this.
$path = $_FILES['file']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
$logo = time().'.'.$ext;
And to use the new name. put this.
move_uploaded_file($_FILES['file']['tmp_name'], '../timeTableImg/' . $logo);

PHP upload image different directory

i have a problem with uploading images into different directory.
$path = "../uploads/";
$path2 = "../uploads2/";
$imagename = $_FILES['photoimg']['name'];
$actual_image_name = $imagename;
$uploadedfile = $_FILES['photoimg']['tmp_name'];
$widthArray = array(600,240); //resize width.
foreach($widthArray as $newwidth)
{
$filename = $uploadedfile,$path,$actual_image_name,$newwidth;
//Original Image
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{}
if(move_uploaded_file($uploadedfile, $path2.$actual_image_name))
{}
i want to upload image into uploads and uploads2 folders also?
for example width width = 600px into uploads, width = 240px into folder upload2.
what's wrong with my code?
After moving the file with move_uploaded_file it isn't available in the location stored in $uploadedfile anymore. For the second file you have to use copy function.
Please try the following:
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{}
if(copy($path.$actual_image_name, $path2.$actual_image_name))
{}
Remove this line. I don't know for what purpose it's there.
$filename = $uploadedfile,$path,$actual_image_name,$newwidth;
To resize the uploaded image use any library to resize it then pass it.
But here is the full code to upload in different directory. But you will have to resize these two $file1 & $file2 to your expected resize file and replace the same in $file1 & $file2
To resize you can use any code suggested here
$path1 = "../uploads/";
$path2 = "../uploads2/";
$file1= $_FILES['photoimg'];
$file2= $_FILES['photoimg'];
$file1_imagename = $file1['name'];
$file2_imagename = $file2['name'];
$file1_actual_image_name = $file1_imagename;
$file2_actual_image_name = $file2_imagename;
$file1_uploadedfile = $file1['tmp_name'];
$file2_uploadedfile = $file2['tmp_name'];
$widthArray = array(600, 240); //resize width.
if (move_uploaded_file($file1_uploadedfile, $path1 . $file1_actual_image_name)) {
echo "Uploaded Successfully!";
}
if (move_uploaded_file($file2_uploadedfile, $path2 . $file2_actual_image_name)) {
echo "Uploaded Successfully!";
}

Categories