clear Canvas and save Canvas - php

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.

Related

Ajax XMLhttprequest Post to PHP script and Rotate Image

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>

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

How do i implement a proper show hide /slideToggle functionality in this function

I have a function in jquery which displays images on link click and also has to hide the image when the link is clicked again.
This is the code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j('.links').click( function(){
var linkclicked = this.id;
var url = $j(this).attr('href'),
image = new Image();
image.src = url;
image.onload = function () {
$j('#image-holder'+linkclicked).empty().append(image);
/* The above line shows the image on first click.
Adding slideToggle hides the image again */
};
image.onerror = function () {
$j('#image-holder'+linkclicked).empty()
.html('That image is not available.');
}
$j('#image-holder'+linkclicked).empty().html('Loading...');
return false;
});
});
function loadnow() {
}
</script>
</head>
<body>
<?php $topicid=1; ?>
<a href="myimages/red-brick-wall-texture.jpg" class="links" id="<?php echo $topicid; ?>" >Show image</a>
<div id="<?php echo 'image-holder'.$topicid; ?>"></div>
<?php $topicid=2; ?>
<br><a href="/myimages/gymicon.JPG" class="links" id="<?php echo $topicid; ?>" >Show image</a>
<div id="<?php echo 'image-holder'.$topicid; ?>"></div>
</body>
</html>
Please let me know where to write slideToggle as to enable show/hide function properly. There are two links here which show separate images. They are shown when clicked but the problem is to hide them on next click and make them
visible when clicked again and so on.
The way you have your code here is not really quite right for .slideToggle. You should not put the URL for the image in the href attribute of an <a> element because the link will try to go there on click.
The way .slideToggle works is well documented on the docs page. All you have to do is use the HTML <img> tag, which is made to hold images. Then you $().hide(); them when the page loads so they aren't shown. All you have to do them is call the .slideToggle() function on the link click event.
See the working example with some misc pictures in this fiddle: http://jsfiddle.net/8xcZT/5/.
Or here is a working version of your code: http://jsfiddle.net/JMXba/9/. I can see this may be desirable to wait for the click to load the image.
Good Luck!

Selecting elements in a div and send data to database

i have the following form which populates a div element, more specifically a Bootstrap's modal form by a user's twitter's followers profile image.
This is the form : http://d.pr/i/ZJMk
This is the code that does the work.
<div class="modal-body">
<?php
$follower_url = "http://api.twitter.com/1/statuses/followers/Mozammil_K.xml";
$twFriends = curl_init();
curl_setopt($twFriends, CURLOPT_URL, $follower_url);
curl_setopt($twFriends, CURLOPT_RETURNTRANSFER, TRUE);
$twiFriends = curl_exec($twFriends);
$response = new SimpleXMLElement($twiFriends);
foreach($response->user as $friends){
$thumb = $friends->profile_image_url;
$url = $friends->screen_name;
$name = $friends->name;
?>
<a title="<?php echo $url;?>" href="#"><img class="photo-img" src="<?php echo $thumb?>" border="2" alt="" width="40" onClick="highlight(this)" /></a>
<?php
}
?>
</div>
I want to give the user's the option to click on the photos and selecting the elements. They can also click on the photos again and deselect it. This has been achieved by the following javascript.
<script>
function highlight(elem) {
if(elem.style.border == '2px solid blue') {
elem.style.border = '';
}
else{
elem.style.border = '2px solid blue';
}
}
</script>
On clicking the create button, the form should get the title of the highlighted elements and send the elements' title to the database. I have not found any way of doing this besides saving elements into an array and send data through JSON. I am not really familiar with JSON. Is there any other way (simpler) to do it? Perhaps JQuery?
Regards.
I think this would be the solution for your problem,
I added these three attribute to <a class='a-img'> tag
"rel=<?echo $thumb?>"
"id=<?echo $name?>"
"title=<? echo $url;?>" //these will be the diffrent attr to be send on the database
and these 3 attribute must be pass to a hidden input if you click the "a.a-img"
must add 3 hidden fields:
<input type="hidden" id="sname"/>
<input type="hidden" id="fname"/>
<input type="hidden" id="thumb"/>
<a title="<?php echo $url;? class='a-img'>" href="#">
<img class="photo-img" src="<?php echo $thumb?>" border="2" alt="" width="40"
onClick="highlight(this)" /></a>
$(document).ready(function(){
$("#create").click(function(){
//get the value of the 3 hidden fields
var sname = $("#sname").val(sname);
var fname = $("#fname").val(fname);
var thumb = $("#thumb").val(thumb);
$.ajax({
type:"POST",
url:"//your savetodb.php"
data:{'sname':sname, 'fname':fname, 'thumb':thumb},
success: function(data){
//do success message
}
});
});
$("a.a-img").click(function(){
var sname = $(this).attt('title');
var fname = $(this).attr('id');
var thumb = $(this).attr('rel');
//these 3 attrbute will pass to a hidden input
$("#sname").val(sname);
$("#fname").val(fname);
$("#thumb").val(thumb);
});
});
Hope this will help you.

Change image when page reload in jquery?

I am working in php on when user click image when it will redirect to another link then i need change image here is my code
<script type="text/javascript">
$(document).ready(function() {
$("#cards").click(function() {
d = new Date();
$("#cards").attr("src","http://ifliptips.com/admin/VueGuides/images/ifliptips_hover.jpg?timestamp=" + new Date().getTime());
$("#tips").attr("src","http://ifliptips.com/admin/VueGuides/images/iflipcards.jpg");
$("#registeruser").attr("src","http://ifliptips.com/admin/VueGuides/images/reg_users.jpg");
});
});
</script>
<?php
$redirect=REDIRECT;
$path=$redirect."/images/iflipcards.jpg";
?>
<li class="active">
<a href="quizcatagory.php" id="quizcatagory">
<img id="cards" style="padding-top:15px" width=70 height=18 src=<?php echo $path; ?> />
</a>
</li>
How can I change image after page reload?
Thanks in advance.
url = "cardcatagory.php";
$(location).attr('href', url);
The code above redirect your page to another link. Try below.
$(document).ready(function () {
$("#quizcatagory").click(function () {
d = new Date();
$("#cards").attr("src", "http://ifliptips.com/admin/VueGuides/images/ifliptips_hover.jpg?timestamp=" + new Date().getTime());
$("#tips").attr("src", "http://ifliptips.com/admin/VueGuides/images/iflipcards.jpg");
$("#registeruser").attr("src", "http://ifliptips.com/admin/VueGuides/images/reg_users.jpg");
return false;
});
});
You are already setting the image with a PHP variable
<img id="cards" style="padding-top:15px" width=70 height=18 src=<?php echo $path; ?> />
Just change the image on the server side. Unless you are speaking of the image urls in the JavaScript, then you can either make their values PHP variables and set that from the server or you can create a PHP file that returns an image and put all the necessary logic to determine what image to display from there. (http://php.net/manual/en/function.imagejpeg.php)

Categories