Refresh image after its been replacedWith image using jQuery PHP - javascript

I am using simpleImage, a php image manipulation library.. I am trying to rotate the image externally using ajax and replaceWith. It replaces the image and everything but it wont refresh when rotated..
index.php -
//Submit Form
function subForm() {
event.preventDefault();
var name = $('#target').val();
console.log(name);
$.post("rotate.php", {name: name},
function(data) {
$("#preview").replaceWith( '<img id="replace" src="'+data+'"/>' );
});
}
<img src="'.$target.'" id="preview"/>
<form method="post" action='' id="rotateForm" data-ajax="false">
<input type="submit" id="rotate" onclick="subForm();" value="rotate">
</form>
** UPDATED**
rotate.php -
$time = time();
$newImg = $_POST['name'];
$img = new abeautifulsite\SimpleImage($newImg);
$img->rotate(90)->best_fit(500, 500)->save();
echo $newImg.'?'.$time;
The image rotates but doesn't update on the page with out the page being reloaded.. Am I using the wrong approach here?

Images do usually get cached by the browser.
The problem:
you show some image with a specific src like someimage.jpg
You rotate that image and provide it with the same src someimage.jpg
the browser will load the old one from the cache!
To prevent that you could simply request a brand new one using a timestamp like
someimage.jpg?t=1476400456961
and the browser will load a clean someimage.jpg from the server.
A JS solution is:
function subForm() {
event.preventDefault();
var name = $('#target').val();
console.log(name);
$.post("rotate.php", {name: name}, function(data) {
var tStamp = +new Date(); // Generate always a new timestamp milliseconds value
$("#preview").replaceWith( '<img id="replace" src="'+ data+"?t="+ tStamp +'"/>' );
});
}

You have rewrite the src attribute of your tag so that the image loads again.

Related

A script to automatically rename a file after it's saved to the local computer?

I want the user of my page to :
browse a movie file from his local computer
get an image from the movie he just input it in step 1
name the image file exactly the same with the movie file name
upload to the server this image file
Thanks to the link from codepen here, I can pass step 1 and step 2 above.
(Please have a look to the link above for the complete codes), The HTML :
<p><strong>Select a video or image file</strong><br /><br />Supported browsers (tested): Chrome, Firefox, Safari, Opera, IE10, IE11, Android (Chrome), iOS Safari (10+)</p>
<div></div>
So, I copy/paste the codes to my page. After this I can just go to the next steps "manually" by telling the user to
(3a) right click the image and choose "Save image as..."
(3b) rename the file in the "Save image as" dialog box exactly the
same with the movie file name and put a .jpg extension instead of the
default one which is .png
(3c) from the form I provide, browse his local computer and select
this jpg file
(4) push the "Submit" button to upload the jpg file to the server
Suppose I'm the user, I click the "Browse" button and select SinCity.mp4 movie. Then I saw the page showing a still image from the movie. Without doing 3a, 3b and 3c, I just click another button - which is the "Submit" button to upload SinCity.jpg
My question is : will it be possible to "auto" step 3 so the user doesn't have to do 3a, 3b and 3c ?. I mean the process of 3a 3b 3c are taken over by a script. If possible, would somebody help me for the script ?
FYI, my page is in .php extension file.
Thank you in advanced.
=====================================================================
EDIT : I found the answer.
Thank you to all user who submit a codes in the internet and thank you also to Douwe de Haan who help me on how to do it. I'm sorry since I can not put more than two links in my post, I will just copy/paste the codes which come from 3 different sources, in case there is someone who face the same case with me.
First, the CSS :
div {
line-height: 200px;
}
img {
padding: 5px;
vertical-align: middle;
text-align: center;
}
#supports (object-fit: cover) {
img {
object-fit: cover;
}
}
The css above I got it from anon/pen in codepen.
The HTML :
<input type="file" accept=".jpg,.jpeg.,.gif,.png,.mov,.mp4" onchange="document.getElementById('file').value =
this.value.split('\\').pop().split('/').pop()" />
<p><strong>Select a video or image file</strong><br /><br />Supported browsers (tested): Chrome, Firefox, Safari, Opera, IE10, IE11, Android (Chrome), iOS Safari (10+)</p>
<div></div>
<input type="button" onclick="uploadEx()" value="Upload" />
<form method="post" accept-charset="utf-8" name="form1">
<input name="hidden_data" id='hidden_data' />
<input type="text" name="file" id='file' type="hidden"/>
</form>
The html above is a combination which I got from
anon/pen in codepen
the onchange="document.getElementById('file').value I got it from
shijin/4EnRQ/ in jsfiddle and
the onclick="uploadEx()" I got it from
"upload-html-canvas-data-to-php-server" in codepool.
The SCRIPT :
<script>
document.getElementsByTagName('input')[0].addEventListener('change', function(event) {
var file = event.target.files[0];
var fileReader = new FileReader();
if (file.type.match('image')) {
fileReader.onload = function() {
var img = document.createElement('img');
img.src = fileReader.result;
document.getElementsByTagName('div')[0].appendChild(img);
};
fileReader.readAsDataURL(file);
} else {
fileReader.onload = function() {
var blob = new Blob([fileReader.result], {type: file.type});
var url = URL.createObjectURL(blob);
var video = document.createElement('video');
var timeupdate = function() {
if (snapImage()) {
video.removeEventListener('timeupdate', timeupdate);
video.pause();
}
};
video.addEventListener('loadeddata', function() {
if (snapImage()) {
video.removeEventListener('timeupdate', timeupdate);
}
});
var snapImage = function() {
var canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
var image = canvas.toDataURL();
var success = image.length > 100000;
if (success) {
var img = document.createElement('img');
img.src = image;
document.getElementsByTagName('div')[0].appendChild(img);
URL.revokeObjectURL(url);
}
return success;
};
video.addEventListener('timeupdate', timeupdate);
video.preload = 'metadata';
video.src = url;
// Load video in Safari / IE11
video.muted = true;
video.playsInline = true;
video.play();
};
fileReader.readAsArrayBuffer(file);
}
});
function uploadEx() {
var dataURL = document.images[0].src;
document.getElementById('hidden_data').value = dataURL;
var fd = new FormData(document.forms["form1"]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload_data.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
alert('Succesfully uploaded');
}
};
xhr.onload = function() {
};
xhr.send(fd);
};
</script>
The script above I got it from anon in codepen, the last function uploadEX() I got it from "upload-html-canvas-data-to-php-server" in codepool and the document.images[0].src;I got it from W3School.
Finally the upload_data.php
<?php
$upload_dir = "uploads/";
$img = $_POST['hidden_data'];
$file_name = substr($_POST['file'],0,-4);
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . $file_name . ".jpg";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
The php above I got it from "upload-html-canvas-data-to-php-server" in codepool.
Thank you very much, All.
If you'll accept that the user doesn't download anything and the flow is changed to this:
User selects a movie
Script gets a still to upload
User presses upload button and still is uploaded
Then yes, it just takes a few steps:
Create a hidden input in the form named something like snapshot_base64
<input type="hidden" name="snapshot_base64" id="snapshot_base64">
Next, in the codepen you provided is a line that says var image = canvas.toDataUrl(). After that line, put the following code:
snapshot_input = document.getElementById('snapshot_base64');
snapshot_input.setAttribute('value', image);
This loads the base64 data into the hidden input.
What you still need to to yourself is grabbing the name of the uploaded movie and add that to a hidden input as well, so you'll know what name to give to the file.
After this you'll need to submit the form and read the base64 in the php files you are using.
Converting base64 to an image is described here.

When button is clicked, need to download canvas and increment sql integer by 1

I have been able to get my button to download the file (html canvas), but I need it to also increment a SQL field by one.
I am not sure how much code you will need, so I will begin by giving you the parts I am trying to get to talk to each other.
PHP:
$insert = mysql_query("update UserName set logins = logins+1 where password='$password' AND username='$username'", $connection);
HTML Button:
<div>
<a id="dload" download="YourFileName.png">Download as image</a>
</div>
JAVA (On the same page as button)
function download() {
var dt = c5.toDataURL("image/png", 1.0);
this.href = dt;
};
function insert(){
var insert = <?php $insert; ?>;
};
dload.addEventListener('click', download, false);
dload.addEventListener('click', insert, false);
The PHP code lives on a file called login.php as a variable. Login.php is included on the file that contains the HTML button and Java above.
The download part works. The SQL query is correct and works when run on the database. But I am just not sure how to integrate so it both downloads and adds one to the database.
Thanks for looking.
EDIT:
I can now get it to do both, but now it only increments the SQL field once per logon (will download every time though). The user needs to logout , then log back in for it to work properly again. I need it to increment by one every time they click download.
I changed this:
function download() {
var dt = c5.toDataURL("image/png", 1.0);
this.href = dt;
};
function insert(){
var insert = <?php $insert; ?>;
};
dload.addEventListener('click', download, false);
dload.addEventListener('click', insert, false);
to this (which is what I had originally):
function download() {
var dt = c5.toDataURL("image/png", 1.0);
this.href = dt;
};
dload.addEventListener('click', download, false);
And changed my button to this:
echo <a id="dload" download="YourFileName.png" value="<?php echo $insert; ?>">Download as image</a>

file_get_contents error whilst using aviary

I have embedded aviary into my webpage and it is working fine but I am unable to use the file_get_contents command to grab the saved image.
the aviary code:
JS:
<!-- Load Feather code -->
<script type="text/javascript" src="http://feather.aviary.com/js/feather.js"></script>
<!-- Instantiate Feather -->
<script type='text/javascript'>
var featherEditor = new Aviary.Feather({
apiKey: '*********',
apiVersion: 3,
theme: 'light', // Check out our new 'light' and 'dark' themes!
tools: 'crop,orientation,brightness,sharpness,redeye,effects,stickers,focus,contrast,whiten,warmth,colorsplash,enhance,saturation,blemish,draw,text,frames',
appendTo: '',
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
onError: function(errorObj) {
alert(errorObj.message);
},
postUrl: 'http://example.com/featherposturl'
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
HTML:
<div id='injection_site'></div>
<img id='image1' src='photo.jpg' style="max-height:360px;" on/>
<p><input type='image' src='http://images.aviary.com/images/edit-photo.png' value='Edit photo' onclick="return launchEditor('image1', document.getElementById('image1').src);"/></p>
According to the aviary documentation I can grab the temp file that has been created on the aviary server but using this php code:
<?php
$image_data = file_get_contents($_REQUEST['url']);
file_put_contents("photo.jpg",$image_data);
?>
When I run this it errors out with this error
[24-Sep-2013 12:14:16 UTC] PHP Warning: file_get_contents() [function.file-get-contents]: Filename cannot be empty in......
Does anyone have any experience as to how I can grab the file that has been created on the aviary server and upload a copy to my server.
UPDATE
I notice a file called 'photo.jpg' is added to the server with a filesize of 0kb. I am assuming that this is from the file_put_contents("photo.jpg",$image_data); but the image data is blank as this is the error if the file_get_contents
Any ideas?
Please check that on your sever allow_url_fopen = 0
if it's value is 1 file_get_contents can't work
it that case you can use curl
Aviary posts back to a URL of your choice with a link to the file saved on their servers. So, you need to add a route on your server with the server-side code snippet above and make sure the postUrl you specify is the URL on your server that will call this code.
I had the same problem, this answer is probably a little late now, but I got around it this way. Its not the best way but it does work
In your javascript change this:
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
to This:
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
var old_image = $('#oldimage').val(); //this is a hidden field with the HTML LINK for the original image on your server
$.ajax({
url : 'PHP Processing page',
type : 'POST',
dataType : 'JSON',
data : {oldimage : old_image, newimage : img.src},
success : function (json) {
console.log(json);
}
});
}
HTML:
<input id="oldimage" type="hidden" value="ORIGINAL IMAGE" />
<button class="button special fit" onclick="return launchEditor('image1', 'ORIGINAL IMAGE');">Edit This Image</button>
In the PHP processing page:
$default = getenv("DOCUMENT_ROOT");
define("SITEROOT",$default."/yoursite/");
define("SITEHTMLROOT", "http//www.yoursite.com/");
$oldimage = str_replace(SITEHTMLROOT, SITEROOT, $_POST['oldimage']);
$newimage = $_POST['newimage'];
copy($newimage, $oldimage);
As long as allow_url_fopen is set to on/1 this will work
You don't need to add the
postUrl: 'http://example.com/featherposturl'
line to do it this way
As this post is very old, if you did find a good way of doing this would you share it?

No way to pass data using form with Uploadify

sorry if I am being redundant but I've tried every single example I found here and on google :D
What I am trying to do is on the upload of image, what was typed on inputbox will be send along to the uplodify.php where my insert is. My problem is, name of picture has being saved to the mysql but what was typed on the textfield dont.
Would you guys let me know what is going on?
This is the part of my code
'multi' : true,
'auto' : false,
'onUploadStart' : function(file) {
$("#file_upload").uploadify('settings', 'formData', {'galeria': $('#galeria').val()});
},
<form id="form1" name="form1" action="">
<p>
<input type="file" id="file_upload" name="file_upload" />
<br>
<br>
Galeria<br>
<label>
<input type="text" name="galeria" id="galeria">
uplodify.php
$galeria = $_POST['galeria'];
$regiao = $_POST['regiao'];
if (!empty($_FILES)) {
$img = $_FILES['Filedata']['name'];
$ext = substr($img, -4);
$img = md5($img).date("dmYHis").$ext;
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $img;
$adicionar = mysql_query ("INSERT INTO imagens (foto, galeria, regiao) VALUES('$img','$galeria','$regiao')");
// $fileTypes = str_replace('*.','',$_REQUEST['fileext']);
// $fileTypes = str_replace(';','|',$fileTypes);
// $typesArray = split('\|',$fileTypes);
// $fileParts = pathinfo($_FILES['Filedata']['name']);
// if (in_array($fileParts['extension'],$typesArray)) {
// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);
move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
// } else {
// echo 'Invalid file type.';
// }
}
Try changing your onUploadStart method to extend the uploadify formData property like this:
onUploadStart: function ( file ) {
var $fileUpload = $('#file_upload')
, formData = $fileUpload.uploadify('settings', 'formData')
, newFormData = $.extend({}, formData, { galeria: $('#galeria').val() });
$fileUpload.uploadify('settings', 'formData', newFormData);
}
I finally managed to made it work
This is the code I used
$('#file_upload').attr('file_upload', response).show();
$.post("insert2.php",{name: fileObj.name, galeria: $("#galeria").val(), regiao: $("#regiao").val()}, function(info) {
alert(info); // alert UPLOADED FILE NAME
});
}
});
Now I have a different problem lol it always show right...
Since the code to save the file on dabase is on insert2.php and the code to rename the picture inside the uploadify.php. How can I save the new name on the database instead the name of file I uploaded?
Another question.... is that a way to generate a thumbnail based on those pictures on database?

HTML5 URL to saved image displays previously created image when clicked

I have an HTML5 app that saves the canvas image to the server and then provides a link to that image that opens in a new window.
This works fine the first time I save it, but if I create and save a new image and then click on the link it displays the old image that was previously created.
Clicking on refresh will force it to display the new one, but I was wondering if there is a way to make sure it displays the correct image so that I don't have to refresh the page?
Below is what I am using to save the image.
<script>
function saveImageAs (imgOrURL) {
if (typeof imgOrURL == 'object')
imgOrURL = imgOrURL.src;
window.win = open (imgOrURL);
setTimeout('win.document.execCommand("SaveAs")', 500);
}
</script>
<script type="text/javascript">
//****************************************************************
// Save canvas content into image file. //
//****************************************************************
function saveViaAJAX()
{
document.getElementById('saveimage').style.visibility="hidden";
document.getElementById("debugFilenameConsole").innerHTML="Please wait while your image is been generated";
var testCanvas = document.getElementById('canvas');
var canvasData = testCanvas.toDataURL("image/jpg");
var postData = "canvasData="+canvasData;
var debugConsole= document.getElementById("debugConsole");
debugConsole.value=canvasData;
//alert("canvasData ="+canvasData );
var ajax = new XMLHttpRequest();
ajax.open("POST",'savecanvas.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
//ajax.setRequestHeader('Content-TypeLength', postData.length);
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
//alert(ajax.responseText);
// Write out the filename.
document.getElementById("debugFilenameConsole").innerHTML="Saved as <a target='_blank' href='myimage.php'> MyImage.jpg"+ajax.responseText+"</a><br>Reload this page to start a new image or click on the link above to open the file.";
}
}
ajax.send(postData);
}
</script>
And the PHP
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'MyImage.jpg', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
header("Content-Type: image/jpg");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment; filename=MyImage.jpg");
imagejpeg($img, null, 100);
?>
Because you are giving the image the same name and path, the browser is helpfully caching it for you.
Use a unique path to avoid this!
You can try
var random=new Date();
var random2=getTime();
var rand=random+random2;
imgOrURL = imgOrURL.src+'?rnd='+rand
or for PHP
$rand=rand();
MyImage.php?rand=<?=$rand?>
or
$image='MyImage.php?rand='.$rand.'';
For future use, to save headache. Add dates and times first because using md5 , sha1() or a rand() or JavaScript unique key can be a nightmare, example:
/// This is much cleaner
/11.1.2012/11.05/eachier93.jpg
/11.1.2012/11.05/4358390485/93.jpg
/11.1.2012/11.10/3249203489834/234234.jpg
/// then this
/files/342748234234234/234982348394/333535.jpg
/files/4535345345/234234234234/3332.jpg
/files/23423434324/023840348234/2343.jpg

Categories