How to use PHP to rotate PNG images - php

So right now I am using PHP to add rotate functionality to images. Currently right now it is set up to only work for JPEGs, but I need to allow it to work with the image file types PNG and GIF. PNG is more the more important of the two. So currently my code is:
<?php
include_once('../classes/sitewide-functions.php');
$server_root = $_SERVER['DOCUMENT_ROOT'];
$auction = $_GET['auction'];
$item = $_GET['item'];
$dir = $_GET['dir'];
$img = urldecode($_GET['img']);
$image = explode('/',$img);
//parse out the file name
$folder = '/'.$image[3].'/';
$file = $image[4];
$image = $folder.$file;
$imagePath = $server_root.$image;
//set the correct direction
if ($dir == 'ccw') {
$degrees = 90;
} else {
$degrees = '270';
}
$source = imagecreatefromjpeg($imagePath);
$rotate = imagerotate($source, $degrees, 0);
//delete the old file
unlink($imagePath);
$newFile = 'img_'.$item.'_'.time().'.jpg';
$imageStatus = imagejpeg($rotate, $imagePath);
$typeString = null;
$typeInt = exif_imagetype($imagePath);
switch($typeInt) {
case IMAGETYPE_GIF:
$typeString = 'image/gif';
break;
case IMAGETYPE_JPEG:
$typeString = 'image/jpeg';
break;
case IMAGETYPE_PNG:
$typeString = 'image/png';
break;
default:
$typeString = 'unknown';
}
$imageSize = getimagesize($imagePath);
$imageFileSize = filesize($imagePath);
imagedestroy($source);
imagedestroy($rotate);
$newImage = array(
"name" => array(
0 => $file,
),
"type" => array(
0 => $typeString,
),
"tmp_name" => array(
0 => $imagePath,
),
"error" => array(
0 => $imageStatus,
),
"size" => array(
0 => $imageFileSize,
)
);
processImageSizes($imagePath); ?>
So that is was I have right now and it is working for JPEG images. I tried adding a switch case for the PHP functions imagecreatefromjpeg and imagejpeg, but when I added those it made the page go dead. So wasn't sure the next step to take to make this code snippet work for pngs and gifs.
EDIT: The error I am receiving on the dead page is: HTTP ERROR 500

Related

why imagecreatefromjpeg() function is not opening the file from the folder

I want to resize the image file after upload with the help of imagecreatefromjpeg function but this function is unable to access the file from the folder as it's throwing the error i.e., **
imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable
error: in D:\xampp\htdocs\resize\index.php
** but file is uploaded & I wrote the following code.
<form method="post" enctype="multipart/form-data">
<input type="file" name="f1">
<input type="submit" name="btn" value="Upload">
</form>
<?php
ini_set("memory_limit","256M");
if(isset($_POST['btn']))
{
if(move_uploaded_file($_FILES['f1']['tmp_name'], "images/".$_FILES['f1']['name']))
{
$filename = "images/".$_FILES['f1']['name'];
$original_info = getimagesize($filename);
$original_w = $original_info[0];
$original_h = $original_info[1];
echo "<img src =$filename>";
if( ini_get('allow_url_fopen') ) {
// it's enabled, so do something
$original_img = imagecreatefromjpeg($filename);
$thumb_w = 100;
$thumb_h = 60;
$thumb_img = imagecreatetruecolor($thumb_w, $thumb_h);
$thumb_filename = "new.jpg";
imagecopyresampled($thumb_img, $original_img,
0, 0,
0, 0,
$thumb_w, $thumb_h,
$original_w, $original_h);
imagejpeg($thumb_img, $thumb_filename);
imagedestroy($thumb_img);
imagedestroy($original_img);
}
}
}
?>
You must make sure of the type of file.
<?php
$type = exif_imagetype($filename);
// types 1=>gif, 2=>jpg, 3=>png, 6=>bmp
switch ($type) {
case 1 : $img = imageCreateFromGif ( $src );break;
case 2 : $img = imageCreateFromJpeg( $src );break;
case 3 : $img = imageCreateFromPng ( $src );break;
case 6 : $img = imageCreateFromBmp ( $src );break;
}
// or if you cannot use exif_imagetype
// you can use getImageSize
$type = getImageSize($filename);
switch ($type) {
case 'image/gif' : $img = imageCreateFromGif ( $filename ); break;
case 'image/jpeg' : $img = imageCreateFromJpeg( $filename ); break;
case 'image/png' : $img = imageCreateFromPng ( $filename ); break;
case 'image/bmp' : $img = imageCreateFromBmp ( $filename ); break;
}
//// than you can create new file with resize or crop...
?>

imagecreatefromjpeg makes same files (multiple images)

I'm trying to send a formData object from jquery (ajax) to php. The formData contains image files. I need them to be uploaded and resized (which both used to work). Now the problem is, when I create a imagecreatefromjpeg object in php, it seems like he only takes the 1st image and uses this for the amount of images in the formdata.
foreach($_FILES as $file)
{
$ImageName = $file['name'];
$ImageSize = $file['size'];
$TempSrc = $file['tmp_name'];
$ImageType = $file['type'];
$DestinationDirectory .= $CategoryName . "/";
if (is_array($ImageName))
{
$c = count($ImageName);
for ($i=0; $i < $c; $i++)
{
$processImage = true;
$RandomNumber = rand(0, 9999999999); // We need same random name for both files.
if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>'; //output error
}
else
{
//Validate file + create image from uploaded file.
switch(strtolower($ImageType[$i]))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($TempSrc[$i]);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($TempSrc[$i]);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
break;
default:
$processImage = false; //image format is not supported!
} //get Image Size
/*
$outputArr[] = array('image' => $ImageName[$i]);
header('Content-Type: application/json');
echo json_encode($outputArr);
*/
echo $ImageName[$i];
}
}
}
}
So this echoes $i times the same image. Once I remove the switch case, it echoes the correct images...

Creating thumbnail from an uploaded image in Joomla 2.5

I'm really new to joomla, I don't have idea what should I do to make it done. I just have this kind of code in administrator table, it refers to uploading files.
//Support for file field: cover
if(isset($_FILES['jform']['name']['cover'])):
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.file');
$file = $_FILES['jform'];
//Check if the server found any error.
$fileError = $file['error']['cover'];
$message = '';
if($fileError > 0 && $fileError != 4) {
switch ($fileError) :
case 1:
$message = JText::_( 'File size exceeds allowed by the server');
break;
case 2:
$message = JText::_( 'File size exceeds allowed by the html form');
break;
case 3:
$message = JText::_( 'Partial upload error');
break;
endswitch;
if($message != '') :
JError::raiseWarning(500,$message);
return false;
endif;
}
else if($fileError == 4){
if(isset($array['cover_hidden'])):;
$array['cover'] = $array['cover_hidden'];
endif;
}
else{
//Check for filesize
$fileSize = $file['size']['cover'];
if($fileSize > 10485760):
JError::raiseWarning(500, 'File bigger than 10MB' );
return false;
endif;
//Replace any special characters in the filename
$filename = explode('.',$file['name']['cover']);
$filename[0] = preg_replace("/[^A-Za-z0-9]/i", "-", $filename[0]);
//Add Timestamp MD5 to avoid overwriting
$filename = md5(time()) . '-' . implode('.',$filename);
$uploadPath = JPATH_ADMINISTRATOR.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_comic'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.$filename;
$fileTemp = $file['tmp_name']['cover'];
if(!JFile::exists($uploadPath)):
if (!JFile::upload($fileTemp, $uploadPath)):
JError::raiseWarning(500,'Error moving file');
return false;
endif;
endif;
$array['cover'] = $filename;
}
endif;
I could upload the file (in this case, an image) from the codes above, but what I'll do next is creating a thumbnail for the uploaded image. I searched for the php codes through the internet but it doesn't seem to work since I can't synchronize it into joomla codes. Umm.. I've made a folder named thumbnail in images folder. So what should I do next?
I'll be so happy and grateful if any of you could help me with this. Thanks.
Well i can share technique I'm using, i hope it will help:
In table's method check after the all validation is done (at the end of the method, just before returning true) i add the following code:
$input = JFactory::getApplication()->input;
$files = $input->files->get('jform');
if (!is_null($files) && isset($files['image']))
$this->image = $this->storeImage($files['image']);
The i create a new method called storeImage() :
protected $_thumb = array('max_w' => 200, 'max_h' => 200);
private function storeImage($file) {
jimport('joomla.filesystem.file');
$filename = JFile::makeSafe($file['name']);
$imageSrc = $file['tmp_name'];
$extension = strtolower(JFile::getExt($filename));
// You can add custom images path here
$imagesPath = JPATH_ROOT . '/media/';
if (in_array($extension, array('jpg', 'jpeg', 'png', 'gif'))) {
// Generate random filename
$noExt = rand(1000, 9999) . time() . rand(1000, 9999);
$newFilename = $noExt . '.' . $extension;
$imageDest = $imagesPath . $newFilename;
if (JFile::upload($imageSrc, $imageDest)) {
// Get image size
list($w, $h, $type) = GetImageSize($imageDest);
switch ($extension) {
case 'jpg':
case 'jpeg':
$srcRes = imagecreatefromjpeg($imageDest);
break;
case 'png':
$srcRes = imagecreatefrompng($imageDest);
break;
case 'gif':
$srcRes = imagecreatefromgif($imageDest);
break;
}
// Calculating thumb size
if($w > $h) {
$width_ratio = $this->_thumb['max_w'] / $w;
$new_width = $this->_thumb['max_w'];
$new_height = $h * $width_ratio;
} else {
$height_ratio = $this->_thumb['max_w'] / $h;
$new_width = $w * $height_ratio;
$new_height = $this->_thumb['max_w'];
}
$destRes = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($destRes, $srcRes, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
// Creating resized thumbnail
switch ($extension) {
case 'jpg':
case 'jpeg':
imagejpeg($destRes, $imagesPath . 'thumb_' . $newFilename, 100);
break;
case 'png':
imagepng($destRes, $imagesPath . 'thumb_' . $newFilename, 1);
break;
case 'gif':
imagegif($destRes, $imagesPath . 'thumb_' . $newFilename, 100);
break;
}
imagedestroy($destRes);
// Delete old image if it was set before
if (($this->image != "") && JFile::exists($imagesPath . $this->image)) {
JFile::delete($imagesPath . $this->image);
JFile::delete($imagesPath . 'thumb_' . $this->image);
}
return $newFilename;
}
}
}
}
return null;
}
This method returns uploaded file filename, which table stores in 'image' column. It creates two files, one original image and resized thumb with file prefix '_thumb'.
I hope it helps :)
I used Jimage : https://api.joomla.org/cms-3/classes/JImage.html
$JImage = new JImage($img_path);
$size_thumb = '150x150';
$JImage->createThumbs($size_thumb,1,$path.'/thumb');
Short, simple and efficient.

PHP & Jquery FileAPI - shared PHP server configuration

I'm letting my users crop & upload their image with jQuery FileAPI. I'm calling this PHP file with jQuery from another page.
Everything works good on my local server, but when uploading it to my production (shared - cPanel) server, it does not create the file.
Do you know if there is something that I need to change on my cPanel or call my hosting company for?
I tried tweeking with header access but nothing works.
Here is the PHP file:
<?php include 'init.php'; ?>
<?php
if(logged_in() === false) {
header('Location: login.php');
exit();
} ?>
<?php
/**
* FileAPI upload controller (example)
*/
include 'FileAPI.class.php';
if( $_SERVER['REQUEST_METHOD'] == 'OPTIONS' ){
exit;
}
if( strtoupper($_SERVER['REQUEST_METHOD']) == 'POST' ){
$files = FileAPI::getFiles(); // Retrieve File List
$images = array();
// Fetch all image-info from files list
fetchImages($files, $images);
// JSONP callback name
$jsonp = isset($_REQUEST['callback']) ? trim($_REQUEST['callback']) : null;
// JSON-data for server response
$json = array(
'images' => $images
, 'data' => array('_REQUEST' => $_REQUEST, '_FILES' => $files)
);
// Server response: "HTTP/1.1 200 OK"
FileAPI::makeResponse(array(
'status' => FileAPI::OK
, 'statusText' => 'OK'
, 'body' => $json
), $jsonp);
exit;
}
function fetchImages($files, &$images, $name = 'file'){
if( isset($files['tmp_name']) ){
$filename = $files['tmp_name'];
list($mime) = explode(';', #mime_content_type($filename));
if( strpos($mime, 'image') !== false ){
$size = getimagesize($filename);
$base64 = base64_encode(file_get_contents($filename));
$images[$name] = array(
'width' => $size[0]
, 'height' => $size[1]
, 'mime' => $mime
, 'size' => filesize($filename)
, 'dataURL' => 'data:'. $mime .';base64,'. $base64
);
$iWidth = $iHeight = 330; // desired image result dimensions
$iJpgQuality = 100;
// new unique filename
$sTempFileName = 'userpics/' . md5(time().rand());
// move uploaded file into cache folder
move_uploaded_file($filename, $sTempFileName);
// change file permission to 644
#chmod($sTempFileName, 0644);
if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
$aSize = getimagesize($sTempFileName); // try to obtain image info
if (!$aSize) {
#unlink($sTempFileName);
return;
}
// check for image type
switch($aSize[2]) {
case IMAGETYPE_JPEG:
$sExt = '.jpg';
// create a new image from file
$vImg = #imagecreatefromjpeg($sTempFileName);
break;
case IMAGETYPE_GIF:
$sExt = '.gif';
// create a new image from file
$vImg = #imagecreatefromgif($sTempFileName);
break;
case IMAGETYPE_PNG:
$sExt = '.png';
// create a new image from file
$vImg = #imagecreatefrompng($sTempFileName);
break;
default:
#unlink($sTempFileName);
return;
}
$data = getimagesize($sTempFileName);
$width = $data[0];
$height = $data[1];
// create a new true color image
$vDstImg = #imagecreatetruecolor( $iWidth, $iHeight );
// copy and resize part of an image with resampling
imagecopyresampled($vDstImg, $vImg, 0, 0, 0, 0, $iWidth, $iHeight, $width, $height);
// define a result image filename
$sResultFileName = $sTempFileName . $sExt;
// output image to file
imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
#unlink($sTempFileName);
$user_id = $_SESSION['user_id'];
add_guest_picture($user_id, $sResultFileName);
// return $sResultFileName;
}
}
}
else {
foreach( $files as $name => $file ){
fetchImages($file, $images, $name);
}
}
}
?>
Ok issue resolved!
Apparently mime_content_type was not support by my host. after removing error suppression recommended by Musa I could catch the error.
I asked for my host to enable my mime php handling and now everything works.
Cheers.

How can insert 4 fileupload in one form

I need to know if is possible have in one form 4 fileupload, each one to save in different folder when a user want affiliate to our service.. like per example in first upload the Curriculum, next the photo and for the last two the diploma's..
Here is the form URL I am using right now and in "documentos" tab are all the input type file
here is my script
<?php
//----------------------------------------- start edit here ---------------------------------------------//
$script_location = "http://www.proderma.org/"; // location of the script
$maxlimit = 8388608; // maxim image limit
$folder = "uploads/foto_doc"; // folder where to save images
// requirements
$minwidth = 200; // minim width
$minheight = 200; // minim height
$maxwidth = 4608; // maxim width
$maxheight = 3456; // maxim height
$thumb3 = 1; // allow to create thumb n.3
// allowed extensions
$extensions = array('.png', '.gif', '.jpg', '.jpeg','.PNG', '.GIF', '.JPG', '.JPEG', '.docx');
//----------------------------------------- end edit here ---------------------------------------------//
// check that we have a file
if((!empty($_FILES["uploadfile"])) && ($_FILES['uploadfile']['error'] == 0)) {
// check extension
$extension = strrchr($_FILES['uploadfile']['name'], '.');
if (!in_array($extension, $extensions)) {
echo 'wrong file format, alowed only .png , .gif, .jpg, .jpeg
<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
} else {
// get file size
$filesize = $_FILES['uploadfile']['size'];
// check filesize
if($filesize > $maxlimit){
echo "File size is too big.";
} else if($filesize < 1){
echo "File size is empty.";
} else {
// temporary file
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
// capture the original size of the uploaded image
list($width,$height) = getimagesize($uploadedfile);
// check if image size is lower
if($width < $minwidth || $height < $minheight){
echo 'Image is to small. Required minimum '.$minwidth.'x'.$minheight.'
<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
} else if($width > $maxwidth || $height > $maxheight){
echo 'Image is to big. Required maximum '.$maxwidth.'x'.$maxheight.'
<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
} else {
// all characters lowercase
$filename = strtolower($_FILES['uploadfile']['name']);
// replace all spaces with _
$filename = preg_replace('/\s/', '_', $filename);
// extract filename and extension
$pos = strrpos($filename, '.');
$basename = substr($filename, 0, $pos);
$ext = substr($filename, $pos+1);
// get random number
$rand = time();
// image name
$image = $basename .'-'. $rand . "." . $ext;
// check if file exists
$check = $folder . '/' . $image;
if (file_exists($check)) {
echo 'Image already exists';
} else {
// check if it's animate gif
$frames = exec("identify -format '%n' ". $uploadedfile ."");
if ($frames > 1) {
// yes it's animate image
// copy original image
copy($_FILES['uploadfile']['tmp_name'], $folder . '/' . $image);
} else {
// create an image from it so we can do the resize
switch($ext){
case "gif":
$src = imagecreatefromgif($uploadedfile);
break;
case "jpg":
$src = imagecreatefromjpeg($uploadedfile);
break;
case "jpeg":
$src = imagecreatefromjpeg($uploadedfile);
break;
case "png":
$src = imagecreatefrompng($uploadedfile);
break;
}
if ($thumb3 == 1){
// create third thumbnail image - resize original to 125 width x 125 height pixels
$newheight = ($height/$width)*600;
$newwidth = 600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagealphablending($tmp, false);
imagesavealpha($tmp,true);
$transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
// write thumbnail to disk
$write_thumb3image = $folder .'/thumb3-'. $image;
switch($ext){
case "gif":
imagegif($tmp,$write_thumb3image);
break;
case "jpg":
imagejpeg($tmp,$write_thumb3image,100);
break;
case "jpeg":
imagejpeg($tmp,$write_thumb3image,100);
break;
case "png":
imagepng($tmp,$write_thumb3image);
break;
}
}
// all is done. clean temporary files
imagedestroy($src);
imagedestroy($tmp);
echo "<script language='javascript' type='text/javascript'>window.top.window.formEnable();</script>
<div class='clear'></div>";
}
}
}
}
// database connection
include('include/config.php');
$stmt = $conn->prepare('INSERT INTO INGRESOS (nombre,dui,nit,direccion,curriculum,pais,departamento,ciudad,telefono,email,universidad,diploma,jvpm,especializacion,diploma_esp,foto,website,contacto)
VALUES (:nombre,:dui,:nit,:direccion,:curriculum,:pais,:departamento,:ciudad,:telefono,:email,:universidad,:diploma,:jvpm,:especializacion,:diploma_esp,:foto,:website,:contacto)');
$stmt->execute(array(':nombre' => $nombre,':nit' => $nit,':direccion' => $direccion,':curriculum' => $path,':pais' => $pais,':departamento' => $departamento,':ciudad' => $ciudad,':departamento' => $departamento,':ciudad' => $ciudad,':telefono' => $telefono,':email' => $email,':universidad' => $universidad,':diploma' => $path1,':jvpm' => $jvpm,':especializacion' => $especializacion,':diploma_esp' => $path2,':foto' => $write_thumb3image,':website' => $website,':contacto' => $contacto));
echo 'Afiliación ingresada correctamente.';
$dbh = null;
}
// error all fileds must be filled
} else {
echo '<div class="wrong">You must to fill all fields!</div>'; }
?>
the files I need save only the path, so I have this:
:curriculum' => $path
:diploma' => $path1
:diploma_esp' => $path2
:foto' => $write_thumb3image
I don´t know if is possible these...I hope it can be.
Best Regards!
Include multiple file fields
<input type="file" name="file[0]" />
<input type="file" name="file[1]" />
<input type="file" name="file[2]" />
<input type="file" name="file[3]" />
Wrap a foreach around your save script
// set up your paths
$paths=array($path, $path1, $path2, $write_thumb3image);
// 0 1 2 3
// use them as your loop
foreach ($paths as $i=>$path){ // <- use an index $i
// *** save to $path.'/'.$your_image_name.$image_ext
// as Phillip rightly pointed out, $_FILES is different
// so using your index, pick out the bits from the $_FILES arary
$name=$_FILES['file']['name'][$i];
$type=$_FILES['file']['type'][$i];
$tmp_name=$_FILES['file']['tmp_name'][$i];
$size=$_FILES['file']['size'][$i];
$error=$_FILES['file']['error'][$i];
$extension = strrchr($name, '.'); // NB the file name does not mean that's the true extension
....
}
Untested

Categories