PHP 7 Imagick writeimage() path issue - php

I'm trying to create a simple thumbnail image and upload to server using imagick. The image is being selected via a form and I am able to get the thumb created via Imagick, however it is not saving to the right location.
When I use the below code, the image saves to the same directory as the page the code is on and includes the file path within the image name. For example "\images\myuploaded.jpg" as the file name.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$errors = array();
if(preg_match("!image!", $_FILES['image']['type'])){
$image = $_FILES['image']['tmp_name'];
$imagethumb = new Imagick("$image");
$imagethumb->setImageFormat("jpg");
$imagethumb->thumbnailImage(100, 0);
$imgpath = "\images\\".$_FILES['image']['name'];
$imagethumb->writeImage($imgpath);
$_SESSION['message']=$image;
}else{
$errors['image'] = "You must select a .png, .jpg, or .gif images file.";
$_SESSION['message']=$errors['image'];
}
}
Thanks for any help.
_t

Related

Will this guarantee uploaded file has an image suffix

I am in the process of writing an image upload script. I am adding lots of things e.g. store outside webroot and access through php script etc. One thing I have read to check is that a file is uploaded instead of an image. E.g. stop myimage.php.jpeg
I have written the following code to check it is an image file. Is this the best way to check this file has an image name?
$imagename= $_FILES['myimage']['name'];
//check there is only one fullstop in the imagename
if (substr_count($imagename,".")===1){
$imagesuffix = substr($imagename, strpos($imagename, ".") + 1);
//if image type is not a particular type of image
if($imagesuffix != "jpg"|| $imagesuffix != "png"||$imagesuffix != "jpeg"||$imagesuffix != "gif"){
echo"image filename is valid";
}
else{
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else{
echo"this filename is invalid";
}
If your concern is to only allow uploads of files that are images, then you'll have to look at the file contents.
<?php
$image = 'image_file_to_test.png';
if (($imageInfo = getimagesize($image, $jpegInfo)) === FALSE)
die('Not an image.');
// OR
if (($imageType = exif_imagetype($image)) === FALSE)
die('Not an image');
If so desired, you can inspect either $imageInfo (docs) or $imageType (docs) to determine the image format. Please note that exif_imagetype() is the faster of the two, but it won't tell you as much as getimagesize().

How to compress image size before uploading using php

I already searched lots of stuff, some of them are from stackoverflow. But none of them helped me. What I want to do is reduce the image file size, and after reducing the image will now be uploaded. Here's my current code:
<?php
include 'cloud_functions.php';
// GET THE USER'S ID
$userid = _clean($con, $_POST['userid']);
if(!is_dir("uploads/user/".$userid."/")){
mkdir("uploads/user/".$userid."/", 0755);
}
$temp = explode(".", _clean($con,$_FILES["file"]["name"]));
$targetPath = "uploads/user/".$userid."/";
// RENAME THE IMAGE USING ROUND();
$newFN = round(microtime(true)) . '.' . end($temp);
$targetPath = $targetPath . $newFN;
// GET THE FILE EXTENSION
$type = pathinfo(_clean($con, $_POST['filename']), PATHINFO_EXTENSION);
$all_types = array('jpg', 'png', 'jpeg');
$type = strtolower($type);
if(in_array($type, $all_types)){
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)){
// image uploaded w/o compressing size
echo "1/".$newFN;
}else{
echo $targetPath;
echo "There was an error uploading the file, please try again!";
}
}else{
echo "Please upload a valid image.";
}
?>
In that way I can upload image successfully without compressing its size. Please tell me how to do compress image size before upload. Thanks.
You need to compress image on client side. All the code you posted here is of server side. This code will run after uploading the image to the server.
There are lot of client side libraries for this purpose.
This link will further help. You can choose use any library of your choice.
https://github.com/brunobar79/J-I-C - js library
I think better way - compress image on server after uploading, that to decrease using user memory. It's special important for slow smartphones.

How to convert contents of .tmp file to png

I have a PHP script that, if a user-uploaded image file isn't a .png image, it will use Imagemagick to convert it to .png before saving it to a server. However it can only use the .tmp file from the HTML form, so it has to convert the CONTENTS while keeping the .tmp (and its filename) intact. This is my code so far:
if (exif_imagetype($tmpName) != IMAGETYPE_PNG) {
$uploadOk = 0; // don't upload later
$im = new Imagick("$tmpName");
$im->setImageFormat( "png" );
file_put_contents($tmpName, '');
file_put_contents(file_get_contents($im), $tmpName);
if (exif_imagetype($tmpName) != IMAGETYPE_PNG) { //check again
// try again or throw error somehow?
} else {
$uploadOk = 1;
}
} else {
$uploadOk = 1;
}
How do I properly use Imagick to convert the contents of my temp file into a png version of the original (non png) image?
EDIT: It could also be that the script should work fine, and the problem is something entirely different. Not sure at this point.
if you are to use, IMAGICK library, then you can use something like this:
...need to explain how you get the .tmp file, which I guess by using a form on your site... so...
.. get the post file
// This equals to 'some/server/path/temp/filename.tmp'
$original_image = $_FILE['tmp_name'];
// Lets work on the Imagick...
$img = new Imagick($original_image);
$img->setImageBackgroundColor('white');// red, black..etc
$img = $img->flattenImages(); // Use this instead.
$img->setImageFormat('png');
$new_image_name = 'nice_image_name.png';
$img->writeImage($new_image_name);
See if that works for you...

PHP show thumbnail depending on file type

All the files in a certain directory are scanned using scandir() for example. How then do I go through the files in that directory and create a small image (thumbnail) or whatever so that I can display that next to the name.
I will probably check the files one by one, and lets say it is another directory, the image will be default folder image. For PDF's maybe also. But then for video's and images and anything else like it, the image should be like a preview.
<?php
$data = array();
$files = array();
$allFiles = scandir($_REQUEST['dir_name']);
$files = array_diff($allFiles, array('.', '..'));
foreach($files as $key=>$file){
$data[$key]['name'] = $file;
if(is_dir(_REQUEST['dir_name'].'/'.$file)){
//Get small image of folder here and store that in $data[$key]['preview']
$data[$key]['type'] = 'dir';
}
else{
$extension = substr(strrchr($filename, "."));
$data[$key]['type'] = $extension;
switch ()$extension) {
case 'jpeg' : {
//Get small thumbnail of jpeg image here and store that in $data[$key]['preview'];
}
case 'png' : {
//Get small thumbnail of png image here and store that in $data[$key]['preview'];
}
case 'pdf' : {
//Get small thumbnail of pdf here and store that in $data[$key]['preview'];
}
case 'rar' : {
//Get small thumbnail of default .rar image here and store that in $data[$key]['preview'];
}
}
}
}
echo json_encode($data);
?>
I am prepared to do quite a few extensions, and maybe find a default later on for extensions not explicitly covered. I just need to know some of the different methods on generating a thumbnail from images, videos and documents as I suspect they are completely different.

FPDF error: Image file has no extension and no type was specified

I am getting the error as mentioned on the title when I try to run my php code which will generate a PDF file. This is the current code I am using:
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',12);
foreach($inventories as $key => $inventories) :
$image = $inventories['image'];
$resourceID = $inventories['resourceID'];
$learningcentre = $inventories['learningcentre'];
$title = $inventories['title'];
$quantity = $inventories['quantity'];
$description = $inventories['description'];
$html= 'Resource ID: '. $resourceID. '<br>Title: '.$title.'<br>Learning Centre: '.$learningcentre.'<br>Quantity: '.$quantity.'<br>Description: '.$description.'<br><br>';
$pdf->Image('images/'.$image,10,6,30);
$pdf->WriteHTML($html);
endforeach;
$pdf->Output();
My images are currently stored in the images folder and I have converted the images file type to "File" by using these codes:
$fileTypes = array(
'image/pjpeg',
'image/jpeg',
'image/png',
'image/gif'
);
// default value for unsuccessful move file
$successfullyMoveFile = false;
// the name of the input type
$fileInputName = 'file';
// an array to store all the possible errors related to uploading a file
$fileErrorMessages = array();
//if file is not empty
$uploadFile = !empty($_FILES);
if ($uploadFile)
{
$fileUploaded = $_FILES[$fileInputName];
// if we have errors while uploading!!
if ($fileUploaded['error'] != UPLOAD_ERR_OK)
{
$errorCode = $fileUploaded['error']; // this could be 1, 2, 3, 4, 5, 6, or 7.
$fileErrorMessages['file'] = $uploadErrors[$errorCode];
}
// now we check for file type
$fileTypeUploaded = $fileUploaded['type'];
$fileTypeNotAllowed = !in_array($fileTypeUploaded, $fileTypes);
if ($fileTypeNotAllowed)
{
$fileErrorMessages['file'] = 'You should upload a .jpg, .png or .gif file';
}
// if successful, we want to copy the file to our images folder
if ($fileUploaded['error'] == UPLOAD_ERR_OK)
{
$successfullyMoveFile = move_uploaded_file($fileUploaded["tmp_name"], $imagesDirectory . $newFileName);
}
}
I believed the problem lies with the file type. Is there any way allow FPDF to understand the file type?
The instructions in the error message are quite clear but I'll try to explain them with another words since you're finding some difficulties. The Image() function has a type parameter described this way:
Image format. Possible values are (case insensitive): JPG, JPEG, PNG
and GIF. If not specified, the type is inferred from the file
extension.
For instance, if the picture is a GIF you need to type 'GIF' (don't forget the quotes). The following example is provided:
$pdf->Image('http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World',60,30,90,0,'PNG');
But you call the function this way:
$pdf->Image('images/'.$image,10,6,30);
You've left the type empty, so FPDF (as documented) will try to guess the image type from the file extension. The extension is the trailing part of the file name after the dot. For instance, if the file is called kitten.jpg then the extension is jpg and FPDF will assume it's a JPEG picture. The following example is provided:
$pdf->Image('logo.png',10,10,-300);
Back to your code, I have no way to know what $image or $newFileName contain (you've managed to omit all the relevant code) but, given the error message, I'd say it doesn't end with a file extension that FPDF can recognise; it probably doesn't even have an extension at all. So you need to either append the file extension to the file name or store the file type anywhere else (e.g. a database table). You could also use heuristics to find out the image type but I don't think it's worth the effort.

Categories