php image rotation not working - php

I have a script that creates thumbnails based on an image (using crop_image), which is working CORRECTLY. However, the script should also rotate the image correctly depending on the EXIF information and for some reason it always FAILS when I add that part and I'm not sure why. The code and file paths is exactly the same as the resizing part.
//THE FUNCTION USED BELOW
function correctImageOrientation($rotatedfile) {
if (function_exists('exif_read_data')) {
$exif = exif_read_data($rotatedfile);
if($exif && isset($exif['Orientation'])) {
$orientation = $exif['Orientation'];
if($orientation != 1){
$img = imagecreatefromjpeg($rotatedfile);
$deg = 0;
switch ($orientation) {
case 3:
$deg = 180;
break;
case 6:
$deg = 270;
break;
case 8:
$deg = 90;
break;
}
if ($deg) {
$img = imagerotate($img, $deg, 0);
}
// then rewrite the rotated image back to the disk as $rotatedfile
imagejpeg($img, $rotatedfile, 100);
}
}
}
}
//THIS PART DOES -NOT- WORK
$adirname = session::value('userid');
$rotatedfile = '/home/path/www/uploads/'.$adirname.'/'.$file_name;
correctImageOrientation($rotatedfile);
copy($rotatedfile, '/home/path/www/uploads/'.$adirname.'/'.$file_name);
//THIS PART WORKS -OK-
if(!file_exists('/home/path/www/uplimg/'.$adirname.'/500_resized_'.$file_name)){
$adirname = session::value('userid');
list($width, $height, $type, $attr) = getimagesize('/home/path/www/uploads/'.$adirname.'/'.$file_name);
$prop = $width / $height;
$newheight = round(500 / $prop);
crop_image('/home/path/www/uploads/'.$adirname.'/'.$file_name,'/home/path/www/uploads/'.$adirname.'/500_resized'.$file_name,500,$newheight);
}

<link rel="stylesheet" type="text/css" href="bootstrap-3.2.0-dist/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="bootstrap-3.2.0-dist/css/bootstrap.min.css">
<script src="js/bootstrap.js"></script>
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="rotate" value="rotate" />
</form>
<?php
if(isset($_POST['rotate']))
{
$image=$_FILES['image']['name'];
$tmp_name=$_FILES["image"]["tmp_name"];
$location='image/';
echo $image;
move_uploaded_file($tmp_name,$location.$image);
$imagename = "image/".$image;
$source= imagecreatefromjpeg($imagename);
$rotate=imagerotate($source,75,0);
imagejpeg($rotate,"rotated/$image");
}
if(isset($_FILES['image']['name']))
{
?>
<html>
<table>
<tr><td>UploadImage</td>
<td height="500px" width="500px" align="center">
<img src="image/<?php echo $image;?>" width="300px" height="300px" />
</td>
<td>RotateImage</td>
<td headers="500px" width="500px" align="center"><img src="rotated/<?php echo $image?>" width="300px" height="300px" /></td></tr>
</table>
</html>
<?php
}
?>

Related

decode base64 image on php get blank image

I'm trying to decode base64 image on php but i get blank image with black screen showing that windows doesn't support this type of file.
Here is my code
public function uploadfoto(){
$img = $_POST['foto'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$filedir = "./assets/upload/presensi/mx_" . mktime() . ".jpg";
$filename = "mx_".mktime().".jpg";
$result = file_put_contents($filedir, $data);
}
I get the image from my webcam and here is my view
<form id ="inputfoto">
<div id="my_camera" style="width: 320px; height: 240px;" class="center"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="<?php echo base_url();?>assets/dist/js/webcamjs/webcam.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 100
});
Webcam.attach( '#my_camera' );
</script>
<div id="results" align = "middle" >Hasil akan tampil di sini</div>
<input type="button" value="Take Snapshot" onclick="take_snapshot()" class="center" style="margin-bottom: 5px;">
<input type="button" value="Submit" onClick="saveSnap()" class="center">
</form>
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>HASIL</h2>' +
'<img id="foto" src="'+data_uri+'"/>';
} );
}
function saveSnap(){
var file = document.getElementById("foto").src;
var formdata = new FormData();
formdata.append("foto", file);
var ajax = new XMLHttpRequest();
ajax.open("POST", "<?php echo base_url();?>asisten/presensi/uploadfoto");
ajax.send(formdata);
}
</script>
And here is the
Blank Image
What's wrong with my code? Thank you very much for your respond.
This code works for me.Please check it
$image = $this->generateImage($_POST['foto']);
public function generateImage($img)
{
$folderPath = "uploads/";
$image_parts = explode(";base64,", $img);
$image_type_aux = explode("uploads/", $image_parts[0]);
$image_base64 = base64_decode($image_parts[1]);
$name = uniqid() . '.png';
$file = $folderPath . $name;
file_put_contents($file, $image_base64);
return $name;
}

how to jquery plugin in ajax call

I have one query in my php website.
I want to display image on button click.
Right now image is open in different webpage, but i need to open it in same webpage with some effect like imageViewer.
code snippet appreciated.
thanks
<script type="text/javascript">
$(document).ready(function () {
$("#selectedAlbumList").change(function () {
$("#loading1").after('<div id="loader1"><img src="img/loading.gif" width="20px" height="20px" alt="loading division" /></div>');
$.get('albumimageGet.php?albumid=' + $("#selectedAlbumList").val() + ' ', function (data) {
$("#galleryData").html(data);
$('#loader1').slideUp(200, function ()
{
alert(data);
$(this).remove();
});
});
});
});
</script>
//albumimageGet.php
<div class="gallery" data-toggle="lightbox-gallery">
<div class="row">
<?php
while ($row = mysql_fetch_array($query)) {
?>
<div class="col-sm-4 gallery-image">
<img src="json/uploads/<?php echo $username; ?>/<?php echo $albumname; ?>/<?php echo $row['imagename']; ?>" alt="image" height="200" width="350">
<div class="gallery-image-options text-center">
<div class="btn-group btn-group-sm">
View
<i class="fa fa-trash-o"></i>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
If you have still have confusion in upper code then this will definitely worked.
mark explain so good in this example.
https://stackoverflow.com/a/21493814/4852079
You can try this function to zoom or resize the image... try it.... hope this will work
/*creates thumbnail of required dimensions*/
function createThumbnailofSize($sourcefilepath,$destdir,$reqwidth,$reqheight,$aspectratio=false)
{
/*
* $sourcefilepath = absolute source file path of jpeg
* $destdir = absolute path of destination directory of thumbnail ending with "/"
*/
$thumbWidth = $reqwidth; /*pixels*/
$filename = split("[/\\]",$sourcefilepath);
$filename = $filename[count($filename)-1];
$thumbnail_path = $destdir.$filename;
$image_file = $sourcefilepath;
$img = imagecreatefromjpeg($image_file);
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
if($aspectratio==true)
{
$new_height = floor( $height * ( $thumbWidth / $width ) );
}
else
{
$new_height = $reqheight;
}
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
$returnvalue = imagejpeg($tmp_img,$thumbnail_path);
imagedestroy($img);
return $returnvalue;
}

How to call a function onClick of a directory

i'm trying to make a file browser and i'm trying to find how to call a function when the user clicks on a directory. For starting i tried to use onClick inside a href on the class part (right before FUNCTION folderSize) having us a goal to open the path inside testDir if i click on any of the files or directories on the list but it does nothing. I'm searching for some hours now it but i can't find the solution. If someone could help i would be greatfull.
Here is the index.php:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/css/myCSSfile.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="/images/dit.ico"><link rel="stylesheet" href="/css/search.css">
<link rel="stylesheet" href="/css/button.css">
<link rel="stylesheet" href="/css/button2.css">
<script type="text/javascript" src="/js/resolutionfinder.js"></script>
<script type="text/javascript" src="/js/changeInputValue.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="/js/ajaxcalls.js"></script>
<body onload='ShowDivInCenter();' onresize='ShowDivInCenter();'>
<div class="cont">
<div id="main">
</script>
<div id="container">
<h1> UOP Directory Contents</h1>
<img class="logo" src="/images/logo.jpg" title="uop search engine" width="450" height="240" />
<form action=''>
<input type='search' id="search" name='s' autocomplete="off">
<input type='button' id="button" value='Search' class="button1" >
</form>
<div class="tfclear"></div>
</div>
<table class="sortable">
<thead>
<tr>
<th>Filename</th>
<th>Type</th>
<th>Size <small>(KB)</small></th>
<th>Date Modified</th>
</tr>
</thead>
<tbody>
<?php
// Opens directory
$rootDirectory=opendir(".");
starter($rootDirectory);
Function starter($myDirectory)
{
$testDir = 'C:\webdev\apache\htdocs\allo1';
// Gets each entry
while($entryName=readdir($myDirectory))
{
$dirArray[]=$entryName;
}
// Finds extensions of files
function findexts ($filename)
{
$filename=strtolower($filename);
$exts=split("[/\\.]", $filename);
$n=count($exts)-1;
$exts=$exts[$n];
return $exts;
}
// Closes directory
closedir($myDirectory);
// Counts elements in array
$indexCount=count($dirArray);
// Sorts files
sort($dirArray);
// Loops through the array of files
for($index=0; $index < $indexCount; $index++)
{
// Allows ./?hidden to show hidden files
if($_SERVER['QUERY_STRING']=="hidden")
{$hide="";
$ahref="./";
$atext="Hide";}
else
{$hide=".";
$ahref="./?hidden";
$atext="Show";}
if(substr("$dirArray[$index]", 0, 1) != $hide) {
// Gets File Names
$name=$dirArray[$index];
$namehref=$dirArray[$index];
// Gets Extensions
$extn=findexts($dirArray[$index]);
// Gets file size
$size=number_format(filesize($dirArray[$index])/1024,2). ' KB';
// Gets Date Modified Data
$modtime=date("M j Y g:i A", filemtime($dirArray[$index]));
$timekey=date("YmdHis", filemtime($dirArray[$index]));
// Prettifies File Types, add more to suit your needs.
switch ($extn){
case "png": $extn="PNG Image"; break;
case "jpg": $extn="JPEG Image"; break;
case "svg": $extn="SVG Image"; break;
case "gif": $extn="GIF Image"; break;
case "ico": $extn="Windows Icon"; break;
case "txt": $extn="Text File"; break;
case "log": $extn="Log File"; break;
case "htm": $extn="HTML File"; break;
case "php": $extn="PHP Script"; break;
case "js": $extn="Javascript"; break;
case "css": $extn="Stylesheet"; break;
case "pdf": $extn="PDF Document"; break;
case "zip": $extn="ZIP Archive"; break;
case "bak": $extn="Backup File"; break;
default: $extn=strtoupper($extn)." File"; break;
}
// Separates directories
if(is_dir($dirArray[$index])) {
$extn="<Directory>";
$size=folderSize($dirArray[$index]);
$size=number_format($size/1024,2). ' KB';
$class="dir";
} else {
$class="file";
}
// Cleans up . and .. directories
if($name=="."){$name=". (Current Directory)"; $extn="<System Dir>";}
if($name==".."){$name=".. (Parent Directory)"; $extn="<System Dir>";}
// Print 'em
print("
<tr class='$class'>
<td>$name</td>
<td>$extn</td>
<td>$size</td>
<td sorttable_customkey='$timekey'>$modtime</td>
</tr>");
}
}
}
FUNCTION call_php_function(directory)
{
$.post("index.php", ("dir": directory), function(data){
alert(data); // Will output, whatever your starter-functions outputs
});
}
FUNCTION folderSize($dir)
{
$count_size = 0;
$count = 0;
$dir_array = scandir($dir);
foreach($dir_array as $key=>$filename){
if($filename!=".." && $filename!="."){
if(is_dir($dir."/".$filename)){
$new_foldersize = foldersize($dir."/".$filename);
$count_size = $count_size+ $new_foldersize;
}else if(is_file($dir."/".$filename)){
$count_size = $count_size + filesize($dir."/".$filename);
$count++;
}
}
}
return $count_size;
}
?>
<div id="ajaxresults" class="ajaxresults"></div>
<br />
<br />
<hr class="style-seven">
<br />
<br />
<div id="showing"></div>
<div id="results" class="results"></div>
</tbody>
</table>
<form><input type='button' id="button" value='DownLoadAll' class="button2"onClick="window.location.href='downloadZip.php?directtozip=$myDirectory&zipaki'"></form>
</div>
</div>
</body>
Please Notice, that this code is not suitable for public productive use. It's good enough to learn with it.
The HTML-Part:
Directory-Name
The jQuery (Js) Part:
function call_php_function(php_function, anyattribut) {
$.post("functions.php", ("call_function": php_function, "attribute_name": anyattribut), function (data) {
// Data is what you get from the echo in the PHP-Script below
alert(data); // Outputs "hello"
}
}
The PHP-Part:
function any_php_function($attribut) {
echo "hello";
}
$allowed_funcs = array("any_php_function", "any_other_function");
if (in_array($_POST["call_function"], $allowed_funcs))
call_user_func($_POST["attribute_name"]);
This code is enough for your purposes:
HTML-Part:
directory-name
jQuery-Part:
function call_php_function(directory) {
$.post("your_file.php", ("dir": directory), function(data){
alert(data); // Will output, whatever your starter-functions outputs
});
}
PHP-Part
if (isset($_POST["dir"]) && !empty($_POST["dir"])) {
starter($_POST["dir"]);
}

JQuery Ajax data sent time 500 Internal Server Error

index.php
<?php
$path = "uploads/";
$image = "";
?>
<html>
<head>
<title></title>
</head>
<link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.imgareaselect.pack.js"></script>
<script type="text/javascript">
function getCropImage(im,obj)
{
var x_axis = obj.x1;
var x2_axis = obj.x2;
var y_axis = obj.y1;
var y2_axis = obj.y2;
var thumb_width = obj.width;
var thumb_height = obj.height;
$.ajax({
type:"GET",
url:"flipimage.php?t=ajax&img="+$("#image_name").val()+"&w="+thumb_width+"&h="+thumb_height+"&x1="+x_axis+"&y1="+y_axis,
cache:false,
success:function(response)
{
//$("#cropimage").hide();
$("#thumbs").html("");
$("#thumbs").html("<img src='uploads/"+response+"' width='700px' height='400px'/>");
}
});
}
$(document).ready(function () {
$('img#photo').imgAreaSelect({
maxWidth: 1,
// maxHeight: 1,
onSelectEnd: getCropImage
});
});
</script>
<?php
$valid_formats = array("jpg", "jpeg", "png", "gif", "bmp","JPG", "PNG", "GIF", "BMP", "JPEG");
$maxImgSize = 5*1024*1024;
$randomName = md5(uniqid().date("Y-m-d H:i:s"));
if(isset($_POST['submit']))
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats) && $size < $maxImgSize)
{
$randomImageName = $randomName.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$randomImageName))
{
$image="<div>Please select the portion</div><img src='uploads/".$randomImageName."' id=\"photo\" >";
}
else {
if ($_FILES["photoimg"]["error"] > 0)
{
echo "Error: " . $_FILES["photoimg"]["error"] . "<br>";
}
}
}
else
{
if($_FILES["photoimg"]["size"] > $maxImgSize)
echo "Maximum file size exceeded";
else
echo "Invalid file";
}
}
else
echo "Please select a image";
}
?>
<body>
<div>
<div>
<form id="cropimage" method="post" enctype="multipart/form-data">
Upload your image
<input type="file" name="photoimg" id="photoimg" />
<input type="hidden" name="image_name" id="image_name" value="<?php echo($randomImageName)?>" />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
<div>
<div>
<?php if($image != ''){ echo $image; }?>
</div>
<div id="thumbs" style="margin-top:40px;"></div>
<div>
</div>
</body>
</html>
flipimage.php
<?php
$path = "uploads/";
function flip($image,$h=1,$v=0,$wid)
{
$width = imagesx($image);
$height = imagesy($image);
$temp = imagecreatetruecolor($width,$height);
imagecopy($temp,$image,0,0,0,0,$width,$height);
$image1 = imagecreatetruecolor($width,$height);
imagecopy($image1,$image,0,0,0,0,$width,$height);
$leftwidth = 2*$wid;
$totWid = (2*$width);
$finalImage = imagecreatetruecolor($totWid,$height);
if ($h==1) {
for ($x=0 ; $x<$width ; $x++)
{
imagecopy($image1, $temp, $width-($x)-1, 0, $x, 0, 1, $height);
}
}
for ($x=0 ; $x<=$wid ; $x++)
{
imagecopy($finalImage, $image, $x, 0, $x, 0, 1, $height);
imagecopy($finalImage, $image1, $leftwidth-($x), 0, $width-($x), 0, 1, $height);
}
$rightWidth = $totWid-$leftwidth;
for ($x=0; $x<=$width-$wid; $x++)
{
imagecopy($finalImage, $image, $totWid-$x, 0, $width-$x, 0, 1, $height);
imagecopy($finalImage, $image1, $leftwidth+$x, 0, $x, 0, 1, $height);
}
return $finalImage;
}
if(isset($_GET['t']) and $_GET['t'] == "ajax")
{
extract($_GET);
$extension = strtolower(strrchr($img, '.'));
$file = $path.$img;
switch ($extension) {
case '.jpg':
$image = imagecreatefromjpeg($file);
break;
case '.gif':
$image = imagecreatefromgif($file);
break;
case '.png':
$image = imagecreatefrompng($file);
break;
default:
$image = false;
break;
}
$new_name = "flip".$img;
$image = flip($image,1,0,$x1);
header("Content-type: image/jpeg");
imagejpeg($image,$path.$new_name,90);
echo $new_name.'?'.time();
exit;
}
?>
I am trying to perform this AJAX post but for some reason I am getting a server 500 error. So the problem seems to be on the calltime. but it's working fine in localhost. but in live error occur.

clickable grid on image

I have a map for an RPG that I'm building. The map is overlaid with a grid of cells, each cell 50px x 50px. each cell should be clickable, but with so many clickable cells on an 800px by 800px map, my script uses up the allocated memory no matter how high i set it (last attempt was 250M). as you can see in the code below, I'm using the base64 encoding and then putting the image into the tag. I believe this may be part of the issue, but i don't want users being able to see the information in the map. how can i accomplish this and stay under the memory limit?
<?php
define("IN_GAME", true);
ini_set("memory_limit","500M");
function imagegrid($image, $w, $h, $s, $color)
{
for($iw = 1; $iw < $w/$s; $iw++)
{
imageline($image, $iw*$s, 0, $iw*$s, $w, $color);
}
for($ih = 1; $ih < $h/$s; $ih++)
{
imageline($image, 0, $ih*$s, $w, $ih*$s, $color);
}
}
$width = 800;
$height = 800;
$block_size = 50;
$image = "images/maps/world.png";
$img = imagecreatefrompng($image);
$grid = imagecolorallocate($img, 0, 0, 0);
imagesetstyle($img, $grid);
imagegrid($img, $width, $height, $block_size, IMG_COLOR_STYLED);
ob_start();
imagepng($img);
$contents = ob_get_contents();
ob_end_clean();
$img_STR = "data:image/png;base64,".base64_encode($contents);
imagedestroy($img);
$split = $width/$block_size;
$c = 1;
while($c < $split)
{
if($c = 1)
{
$x1 = $c;
}
else
{
$x1 = $c*$block_size;
}
if($c = 1)
{
$y1 = $c;
}
else
{
$y1 = $c*$block_size;
}
$x2 = $x1*$block_size;
$y2 = $y1*$block_size;
if(sizeof($coords))
{
array_push($coords, $x1);
array_push($coords, $y1);
array_push($coords, $x2);
array_push($coords, $y2);
}
else
{
echo $x1.','.$x2.','.$y1.','.$y2;
$coords = array($x1, $y1, $x2, $y2);
}
}
if (isset($ts_x) || ($_SERVER['QUERY_STRING'] != ""))
{
if (isset($ts_x))
{
$clickedX = $ts_x;
$clickedY = $ts_y;
}
else
{
list($clickedX, $clickedY) = split(",", $_SERVER['QUERY_STRING'], 2);
}
require 'inc.php';
$allowed = false;
$allowed = inCoord('circ',$coords, $clickedX, $clickedY);
if($allowed)
{
?>
<html>
<head>
<title>PHP Image Map</title>
</head>
<body bgcolor="#00FFC8">
<p align="center">
<b> Aye Eye you got in!</b>
<br>
Click Here to Go to main
</p>
</body>
</html>
<?php
}
else
{
//include 'miss_it.inc';
?>
<html>
<head>
<title>PHP Image Map</title>
</head>
<body bgcolor="#8BCBF8">
<form METHOD="POST" action="">
<p align="center">
<span style="cursor:default;">
<input type="image" src="<?php echo $img_STR; ?>" name="ts">
</span>
</p>
</form>
</body>
</html>
<?php
}
}
else
{
?>
<html>
<head>
<title>PHP Image Map</title>
</head>
<body bgcolor="#8BCBF8">
<form METHOD="POST" action="">
<p align="center">
<span style="cursor:default;">
<input type="image" src="<?php echo $img_STR; ?>" name="ts">
</span>
</p>
</form>
</body>
</html>
<?php
}
?>

Categories