Ajax XMLhttprequest Post to PHP script and Rotate Image - php

I know where I have big problems but I can't seem to solve them. I am trying to rotate an image using PHP via Ajax. I just wand to rotate the image 90 degrees with each button press. Can someone please help. I know I am telling my PHP script to retrieve the $_POST['image'] variable but I'm not sending one which is why I am getting php errors. I know the php script works. I don't know if I can use the xhttp.open("GET") or not in my script either. I know there are other problems with my html and reloading the image in the tag, too. Any help greatly appreciated.
Here is my JS:
<script>
function rotateImage(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("rotate").innerHTML = this.responseText;
}
};
xhttp.open("POST", "rotate.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhttp.send("<?php echo $fileName; ?>");
}
</script>
Here is my PHP:
<?php
$image = $_POST['image'];
$degree = 90;
$source = imagecreatefromjpeg($image);
// Rotate
$rotate = imagerotate($source, $degree, 0);
$image = imagejpeg($rotate, realpath($image), 100);
//echo $image;
imagedestroy($source);
imagedestroy($rotate);
?>
And my HTML:
<div class="row justify-content-center mb-3">
<div class="col-lg col-auto">
<?php list($width, $height) = getimagesize($fileName); ?>
<div class="mb-1" id="rotate"><img class="rounded img-fluid" src="<?php echo $fileName; ?>" alt="Your Profile Photo" width="<?php echo $width; ?>" height="<?php echo $height; ?>" /></div>
<div class="text-center"><button onClick="rotateImage()" class="btn btn-outline-primary btn-sm"><i class="fas fa-sync-alt"></i> Rotate</button></div>
</div>

in the question it is unknown where and how the initially declared $filename is derived or what the particular folder structure / server configuration is so the following perhaps need tweaks to suit your environment as my test site uses aliased folders outwith the site root... Anyway - the sending of a filename/filepath to PHP using Ajax( or the Fetch api as here ) is easy enough. The PHP script does what it is supposed to except that it does not return a value but the trick to forcing the browser to "reload" the image when the ajax request finishes is to append a cache busting timestamp.
Reputedly the cache:'reload' property that can be set on a Fetch request will ensure the image is not cached but I found this had no effect in this situation.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['filename'],
$_POST['path'],
$_POST['dir']
)){
####################
# emulate rotate.php
####################
ob_clean();
$image = sprintf('%s/%s', $_POST['path'], basename( $_POST['filename'] ) );
$angle = $_POST['dir']=='clockwise' ? -90 : 90;
$source = imagecreatefromjpeg( $image );
imagesetinterpolation( $source, IMG_MITCHELL );
$rotate = imagerotate( $source, $angle, 0 );
imagejpeg( $rotate, realpath( $image ), 100 );
imagedestroy( $source );
imagedestroy( $rotate );
list( $width, $height, $type, $attr ) = getimagesize( $image );
$args=array(
'filename' => $_POST['filename'],
'width' => $width,
'height' => $height
);
header('Content-Type: application/json');
exit( json_encode( $args ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<div class='row justify-content-center mb-3'>
<div class='col-lg col-auto'>
<?php
/*
$path here will be the full path and $filename
contains the web accessible path. As mentioned
my setup is complicated and relies upon aliased
folders outside site root.
*/
$path=realpath( sprintf('%s/images/uploads', getcwd() ) );
$filename='images/uploads/abronsius.jpg';
?>
<div class='mb-1' id='rotate'>
<img class='rounded img-fluid' data-path='<?php echo $path;?>' src='<?php echo $filename; ?>' alt='Your Profile Photo' />
</div>
<div class='text-center'>
<button class='btn btn-outline-primary btn-sm' data-dir='clockwise'>
<i class='fas fa-sync-alt'></i>Rotate Clockwise
</button>
<button class='btn btn-outline-primary btn-sm' data-dir='anticlockwise'>
<i class='fas fa-sync-alt'></i>Rotate Anti-Clockwise
</button>
</div>
</div>
</div>
<script>
(function(){
const d=document;
const q=(e,n=d)=>n.querySelector(e);
const qa=(e,n=d)=>n.querySelectorAll(e);
qa('button.btn').forEach( bttn=>bttn.addEventListener('click',e=>{
let img=q('img.img-fluid');
/* set the payload to send in the request */
let fd=new FormData();
fd.set('filename', img.src.split('?')[0] );
fd.set('path', img.dataset.path );
fd.set('dir', e.target.dataset.dir );
let url=location.href; //rotate.php
/* set the request parameters */
let args={
body:fd,
mode:'same-origin',
method:'post',
cache:'reload', //no discernible effect
credentials:'same-origin'
};
/* create the request */
let oReq=new Request( url, args );
/* send the request and process the response by reloading the image */
fetch( oReq )
.then( r=>r.json() )
.then( json=>{
img.src=json.filename +'?t='+( new Date() ).getTime();
img.width=json.width;
img.height=json.height;
})
.catch( err=>console.log(err) );
}));
})();
</script>
</body>
</html>

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;
}

Change font size of text image converted from text to image function dynamically

Working stencil art.Here i have converted text to image this is working good i have 3 text box every text box generating separate line of image on browser.The problem is that i have three another text box for to change the font size of that each converted text.I am not getting any idea how to 3 different font size variable to converted text to change font size because.
Demo Link:- Click Here
Bellow is snap shot what i exactly want.Here you can see that every line of text font size you can change through font size text (Line Height).
My index.php sample code
<?php
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/*
$( "#target" ).change(function() {
// alert( "Handler for .change() called." );
var fontname = this.value;
//alert(fontname);
var img_text = $('input[name="stencil-text"]').map(function(){
return $(this).val();
}).get();
var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontname='+fontname).load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#stencil-main").html(img);
}
});
});
*/
$('input[name="stencil-text"]').keyup(function(){
var img_text = $('input[name="stencil-text"]').map(function(){
return $(this).val();
}).get();
var fontsize = $('input[name="stencil-text-size"]').map(function(){
return $(this).val();
}).get();
// var img = $("<img />").attr('src', 'some.php?img=' + img_text).load(function() {
var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize).load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#stencil-main").html(img);
}
});
});
});
</script>
</head>
<body>
<div id ="all">
<div id="box" style="margin-left: 394px;">
<span class="line" style="margin-left: 578px;">FONT SIZE LINE1 -</span>
<input type="text" name="stencil-text-size" value="20" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 1-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
<br>
<span class="line" style="margin-left: 578px;">FONT SIZE LINE 2 -</span>
<input type="text" name="stencil-text-size2" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 2-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
<br>
<span class="line" style="margin-left: 578px;">FONT SIZE LINE 3 -</span>
<input type="text" name="stencil-text-size3" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 3-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
</div>
<div id="stencil-main" style="margin-top: -652px;"></div>
</div>
<!-- <select id="target">
<option value="ByzantineEmpire" selected="selected">Byzan</option>
<option value="arial">Arial</option>
</select> -->
</body>
</html>
My some.php sample code to convert text to image
<?php
header("Content-type: image/png");
$cid = str_replace(',', "\n", $_GET['img']);
//$cid = array('s1=> ','s2=> ' ,'s3=> ').str_replace(',', "\n", $_GET['img']);
//$fsize="20";
$fontname=$_GET['fontname'] ;
$fontsize=$_GET['fontsize'] ;
####################### BEGIN USER EDITS #######################
//$imagewidth = 500;
//$imageheight = 250;
$imagewidth = 800;
$imageheight = 1000;
//$fontsize = "20";
$fontsize = $fontsize;
$fontangle = "0";
$font = "ByzantineEmpire.ttf";
//$font = $fontname.'.ttf';
$text = $cid ;
$text2="sanjay";
$backgroundcolor = "FFFFFF";
$textcolor = "#000000";
######################## END USER EDITS ########################
### Convert HTML backgound color to RGB
if( #eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $backgroundcolor, $bgrgb ) )
{$bgred = hexdec( $bgrgb[1] ); $bggreen = hexdec( $bgrgb[2] ); $bgblue = hexdec( $bgrgb[3] );}
### Convert HTML text color to RGB
if( #eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $textcolor, $textrgb ) )
{$textred = hexdec( $textrgb[1] ); $textgreen = hexdec( $textrgb[2] ); $textblue = hexdec( $textrgb[3] );}
### Create image
$im = imagecreate( $imagewidth, $imageheight );
### Declare image's background color
$bgcolor = imagecolorallocate($im, $bgred,$bggreen,$bgblue);
### Declare image's text color
$fontcolor = imagecolorallocate($im, $textred,$textgreen,$textblue);
### Get exact dimensions of text string
$box = imageTTFBbox($fontsize,$fontangle,$font,$text);
### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);
### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);
### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth/2)-($textwidth/2)-2;
### Get y-coordinate of centered text vertically using height of the image and height of the text
$ycord = ($imageheight/2)+($textheight/2);
### Declare completed image with colors, font, text, and text location
imagettftext ( $im, $fontsize, $fontangle, $xcord, $ycord, $fontcolor, $font, $text );
### Display completed image as PNG
$html=imagepng($im);
### Close the image
imagedestroy($im);
?>
I did this really quickly to show you how to change the font-size of each of the boxes using jQuery - http://jsfiddle.net/jayblanchard/FB5fL/
$('#set').click(function(e) {
e.preventDefault();
$('.stencil-text').each(function(index) { // loop through each text box
var fontSize = $(this).prevAll('.stencil-text-size').val(); // get the font-size for the current text box
var fontText = $(this).val(); // get the text
console.log(fontSize +' '+ fontText); // just for testing
var newSpan = '<span>' + fontText + '</span><br />'; // set up a new span with the text
$('#stencil-main').append(newSpan); // append the new span
$('#stencil-main span:last').css({ // modify the new span's CSS
"font-size": fontSize + 'px',
"color": "red"
});
});
});
I added classes to the inputs so that they could be re-used instead of doing a function for each individual input by name. Perhaps you can modify this to use with your code.
After some struggle i have made this answer get the text and font size variable and explode it as an array like bellow.
Demo Link:- Click Here
$myArray = explode(',', $_GET['img']);
$fontarray = explode(',' , $_GET['fontsize']);
Use the for loop to looping array
for($i=0;$i<$count;$i++)
{
$newcount=count($fontarray);
for($j=0;$j<$newcount;$j++)
{
if($j==$i)
{
$xcord=$xcord+2;
$ycord=$ycord+100;
imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );
}
}
}
And pass that explode array in image text function like bellow.
imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );
Full solution to convert text image and change the font of text line by line
1) Create index.php with bellow code
<?php
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[name="stencil-text"]').keyup(function(){
var img_text = $('input[name="stencil-text"]').map(function(){
return $(this).val();
}).get();
var fontsize = $('input[name="stencil-text-size"]').map(function(){
return $(this).val();
}).get();
var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize).load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
//alert(fontsize);
$("#stencil-main").html(img);
}
});
});
$('input[name="stencil-text-size"]').keyup(function(){
var img_text = $('input[name="stencil-text"]').map(function(){
return $(this).val();
}).get();
var fontsize = $('input[name="stencil-text-size"]').map(function(){
return $(this).val();
}).get();
var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize).load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
//alert(fontsize);
$("#stencil-main").html(img);
}
});
});
});
</script>
</head>
<body>
<div id ="all">
<div id="box" style="margin-left: 360px;">
<span class="line" style="margin-left: 578px;">FONT SIZE LINE1 -</span>
<input type="text" name="stencil-text-size" value="100" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 1-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
<br>
<span class="line" style="margin-left: 578px;">FONT SIZE LINE2 -</span>
<input type="text" name="stencil-text-size" value="50" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 2-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
<br>
<span class="line" style="margin-left: 578px;">FONT SIZE LINE3 -</span>
<input type="text" name="stencil-text-size" value="20" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 3-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
</div>
<div id="stencil-main" style="margin-top: -652px;margin-left:-297px"></div>
</div>
</body>
</html>
2) Create some.php with bellow code
<?php
header("Content-type: image/png");
$myArray = explode(',', $_GET['img']);
$fontarray = explode(',' , $_GET['fontsize']);
####################### BEGIN USER EDITS #######################
$imagewidth = 1000;
$imageheight = 1000;
$fontangle = "0";
$font = "ByzantineEmpire.ttf";
$backgroundcolor = "FFFFFF";
$textcolor = "#000000";
######################## END USER EDITS ########################
### Convert HTML backgound color to RGB
if( #eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $backgroundcolor, $bgrgb ) )
{$bgred = hexdec( $bgrgb[1] ); $bggreen = hexdec( $bgrgb[2] ); $bgblue = hexdec( $bgrgb[3] );}
### Convert HTML text color to RGB
if( #eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $textcolor, $textrgb ) )
{$textred = hexdec( $textrgb[1] ); $textgreen = hexdec( $textrgb[2] ); $textblue = hexdec( $textrgb[3] );}
### Create image
$im = imagecreate( $imagewidth, $imageheight );
### Declare image's background color
$bgcolor = imagecolorallocate($im, $bgred,$bggreen,$bgblue);
### Declare image's text color
$fontcolor = imagecolorallocate($im, $textred,$textgreen,$textblue);
### Get exact dimensions of text string
### Declare completed image with colors, font, text, and text location
$count=count($myArray);
$box = imageTTFBbox(50,$fontangle,$font,'test');
### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);
### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);
### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth/2)-($textwidth/2)-2;
### Get y-coordinate of centered text vertically using height of the image and height of the text
$ycord = ($imageheight/2)+($textheight/2);
for($i=0;$i<$count;$i++)
{
$newcount=count($fontarray);
for($j=0;$j<$newcount;$j++)
{
if($j==$i)
{
$xcord=$xcord+2;
$ycord=$ycord+100;
imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );
}
}
}
$html=imagepng($im);
### Close the image
imagedestroy($im);
?>
You will get like bellow snap shot sample out put after run the code

how to refresh files/image gallery after delete with xmlhttp/ajax without reloading whole page?

sorry for the lengthy question. i'll try to explain.
i have created a list of images that are visible when you hover over an element (using css)
each image is also a radio button to be chosen and used as part of a form.
All the images are basically all the images in a certain directory that you can also upload to.
I've managed to add a 'delete' button next to each image which will trigger a function that calls a php script to delete that particular image without reloading page. using xmlhttp.which works fine.
But the list of images doesn't refresh itself. As in the image i just deleted is still visible when i hover over the element until i refresh the page then it refreshes the list.
obviously i don't want to refresh the page, that was the whole point of using ajax. so any ideas what i can do? code is below:
<script>
function deleteImage(){
var answer = confirm('Are you SURE you wish to delete this?')
if (answer) {
var image = document.getElementById('filepath').value;
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("uploadmsg").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","delete.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("image="+image);
}
}
then the php/html to call it all.
<?php
$dir = "../images/";
$dh = opendir( $dir );
while( $filename = readdir( $dh ) ) {
$filepath = $dir.$filename;
$gallery[] = $filepath;
$list[] = $filename;
}
sort( $gallery );
sort( $list);
$num_pics = count($gallery);
?>
<div id='chooseimg' ><input type="text" value="Choose Image"><span><ul>
<?php
$a = 2;
while($num_pics > $a)
{
?>
<li>
<input type='radio' name='image' value='<?php echo $list[$a]; ?>'>
<?php echo $list[$a]; ?>
<div id='imglist'><img src='<?php echo$gallery[$a]; ?>' /></div>
<button type='button' onclick="deleteImage()">Delete</button>
<input type="hidden" id="filepath" value="<?php print $gallery[$a]; ?>"/> </li>
<?php
$a ++; }
?>
</ul></span></div>
<div id="uploadmsg"> </div>
the file delete.php contains:
<?php
$image = $_POST['image'];
if (!empty($image)){
unlink($image);
echo "<b>Image deleted<b>";
}
?>
and the css to make the hover over thing work is basically a span inside a div #chooseimage that is set to left:99999px; but when hover over chooseimg it moves to left:0px;
i don't think anyone needs any more info on that but let me know if you do.
as a side note i'm not sure if this actualy ajax? maybe someone can clarify for me.
if you could help i'd be very grateful. i've googled for hours but can't find anything.
ok so for anyone who has the same problem i figured it out.
the code to display all the images along with their radio and delete buttons are stored in a separate php file:
<?php
$dir = "../images/";
$dh = opendir( $dir );
while( $filename = readdir( $dh ) ) {
$filepath = $dir.$filename;
$gallery[] = $filepath;
$list[] = $filename;
}
sort( $gallery );
sort( $list);
$num_pics = count($gallery);
?>
<div id="choose"><div id="echo">
<div style="background-color: #F04D8E; color: #ffffff;">Choose Image</div></div>
<span><ul>
<?php
$a = 3;
while($num_pics > $a)
{
$image = $gallery[$a];
?>
<li>
//the radio button triggers an event which then showsthe image selected
<input id="radio" type='radio' name='image' onchange="thumb('<?php echo $image; ?>')"
value='<?php echo $list[$a]; ?>'><?php echo $list[$a]; ?>
<div id='gallery'>
// the delete button sends the images 'id' in its parameter
<button style="float:right;" type='button'
onclick="deleteImage('<?php echo $image; ?>', '<?php echo $list[$a]; ?>' )">
Delete</button>
<img src='<?php echo $image; ?>' /></div>
</li>
<?php
$a ++;
}
?>
</ul></span></div><br>
in the main page i call this script into a div straight away and also refresh it after the deleteImage function has been requested:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
window.onload = function(){
$('#result').load('show.php');
}
function deleteImage(id, name){
var answer = confirm('Are you SURE you wish to delete ' + name + ' ?')
if (answer) {
$.post("delete.php", { image: id })
.done(function(){
$('#uploadmsg').html("<b>" + name + " deleted </b>");
$('#result').ready(function(){
$('#result').load('show.php');
});
});
}}
function thumb(image){
$('#echo').html("<img src='"+image+"'>");
}
then all i need in the page is a div with id as result
oh and the delete.php page is still:
<?php
$image = $_POST['image'];
if (!empty($image)){
unlink($image);
}
?>
someone said this is dangerous? but i can't see why.
and questions feel free to ask
thanx

clear Canvas and save Canvas

I am just finishing web application for picture analysis and inpainting. And I need help with canvas. This is what I do:
EDIT:
<img id="imgEdit" src="<?php echo $imagename; ?>" border="0">
<canvas id="canvasPaint"
width="<?php echo $width; ?>"
height="<?php echo $height; ?>">
</canvas>
<input type="button" value="Clear" onClick="clearCanvas();" class="button">
<input type="button" value="Save" onClick="saveViaAJAX();" class="button">
<div id="debugFilenameConsole">Wait for a while after clicking the button and the filename of the image will be shown to you. </div>
But now I have problem with clearCanvas function. Because browsers cannot read property 'width'. This is my full source code. How, please can someone tell my what I doing wrong.
EDIT:
function clearCanvas()
{
var theCanvas = document.getElementById("canvasPaint");
if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {
ctx.clearRect(0, 0, <?php echo $width; ?>, <?php echo $height; ?>);
var srcImg = document.getElementById("imgEdit");
ctx.drawImage(srcImg, 0,0);
clickX = new Array();
clickY = new Array();
clickDrag = new Array();
}}}
function saveViaAJAX()
{
var theCanvas = document.getElementById("canvasPaint");
var canvasData = theCanvas.toDataURL("image/jpg");
var postData = "canvasData="+canvasData;
var ajax = new XMLHttpRequest();
ajax.open("POST",'canvasSave.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.send(postData);
}
I need to save canvas as jpeg image on local disk after user click 'save image'. That's mean, areas which are transparent in canvas become black background.
I need something like this:
http://i48.tinypic.com/2w5vhpv.jpg
You can save the canvas to an image file with the canvas.toDataUrl('image/jpg').
Regarding the first question: normally you clear the canvas with context.clearRect(0, 0, canvas.width, canvas.height) method. That being said, your code should work as expected if the canvas and context declarations have been made correctly.

Categories