Store, Update, delete, preview the image - php

I'm trying to retrieve the image from DB even when clicked on refresh.
Javascript function:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(50)
.height(50);
};
reader.readAsDataURL(input.files[0]);
}
}
Now when i choose the file, i will get a small thumbnail, but when i refresh, there will be no image.
Functionality i'm trying to achieve,
Upload a file, show a preview small. - which is done.
When i refresh it has to be there, since i'm concentrating on only one ID at the moment.
This application is to store,update,delete an image[while previewing all the time in a small thumbnail]. I'm using Normal PHP here, where as the app is in CodeIgniter.
EDIT: All need is to ECHO the last uploaded image src.

You are not saving the file to the server, so when you refresh, you are just blowing away all of the JavaScript variables that are holding the data.

Related

preview file from file input field php

Is it possible to preview the file that is selected in the input field before taking any actions?
ex.
I will upload a text file so I will select it then before I click the upload button I want to preview the text file in tables or something like that.
As #RichardTheobald mentioned, it isn't possible with PHP to preview a file before it's uploaded, however, with JavaScript it is.
To read a text file before it's uploaded with JavaScript, you'll need to use a FileReader object. You'll be able to get the list of files from the <input type="file"> element and pop each of these into a FileReader. HTML5Rocks has a good article on reading local files which I've adapted to this question in a JSFiddle.
input.addEventListener("change", function(e) {
var file = e.target.files[0];
// Only render plain text files
if (!file.type === "text/plain")
return;
var reader = new FileReader();
// Once the FileReader loads, pop the result into an output element
reader.onload = function(event) {
document.getElementById("output").innerText = event.target.result;
};
reader.readAsText(file);
});

Best method for clearing temp upload folder

On one of my current projects, I am allowing users to upload images and set them as profile pictures.
The image initially will be stored in a temporary folder until the user crops & saves, or cancels the upload. Of course, there will be cases where they won't actually hit the cancel button. So I have to go through the temp folder and remove images not used after x minutes.
I can think of one way to do this, which would store the image data in MySQL, but I would rather just keep everything on Apache - though I'm not sure what language I'd use to actually perform the search and delete function.
Would this be a cron job?
If the crop and save function is all JS I would recommend you to use the users local file and upload on "save".
JavaScript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
// jQuery
$("#imgInp").change(function(){
readURL(this);
});
// plain JS
document.getElementById('imgInp').onchange = function(){
readURL(this);
}
HTML:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
jsfiddle
Credit to Preview an image before it is uploaded

Display thumbnail image but print full_res using generateimage.php?url=

I have a page which will display photos. I want it to load the thumbnail version of the photo, but when I come to print it should display the highres version.
The photo's are loaded using PHP (imagecreatefromjpeg).
src=\"php/generateimage.php?imgname=".$_SESSION['ROOT_PATH']."data/images/".$value2['location']."&restraint=".$restraint."\"
I have found that by using "display:none" the generateimage.php is not creating the image for print. And when I come to print them, which changes the images to "display:block-inline" the images simply are not available.
Using "visibility:hidden" still loads the images into memory which slows the computer down which is why I don't really want to display them before printing.
I hope this makes sense?
Why not open a new window, load the image, then initiate the print?
<img src="http://lorempixel.com/output/food-q-g-640-480-8.jpg"><br>
<button onclick="printImage();">Print</button>
<script>
function printImage() {
var popup = window.open();
var img = popup.document.createElement("img");
img.src = "http://lorempixel.com/output/food-q-c-640-480-8.jpg";
img.onload = function() {
popup.print();
popup.close();
};
popup.document.body.appendChild(img);
}
</script>
Fiddle (Instead of low quality and high quality, it's gray-scale and color)

Using AJAX / jQuery to refresh an image

This is probably a simple question but I am stumped and just don't know where to start.
I have a PHP script (image_feed.php) that returns a URL to an image. Every time this URl is called it returns the latest image available (the image changes every couple of seconds).
What I want to happen is that when the page loads, there is an AJAX call to image_feed.php, which returns the latest url. This URl is then inserted into the HTMl replacing the appropriate image src.
After 5 seconds, I want the process to repeat, and for the image to update. However, I don't want the image to be swapped until it has finished loading, and I want to avoid a white space appearing before the new image loads.
At the moment I have the following jQuery, which simply loads the return value of image_feed.php directly into a div called #image1. image_feed.php is correctly formatted to provide a html image tag.
$(document).ready(function(){
var $container = $("#image1");
$container.load('image_feed.php?CAMERA_URI=<?=$camera_uri;?>')
var refreshId = setInterval(function()
{
$container.load('image_feed.php?CAMERA_URI=<?=$camera_uri;?>');
}, 5000);
});
This works, but there is a problem. I get a white space the size of the image in IE and Firefox every time the image refreshes, because the image takes a while to download.
I know what I need to is for image_feed.php to return the plain URL to the image. I then use some jQuery to request this URL, pre-load it and then swap it with the existing image.
However, I'm still struggling to get anywhere. Could someone be so kind as to give me some pointers / help?
$(document).ready(function() {
var $img = $('#image1');
setInterval(function() {
$.get('image_feed.php?CAMERA_URI=<?=$camera_uri;?>', function(data) {
var $loader = $(document.createElement('img'));
$loader.one('load', function() {
$img.attr('src', $loader.attr('src'));
});
$loader.attr('src', data);
if($loader.complete) {
$loader.trigger('load');
}
});
}, 5000);
});
Untested. Code above should load the new image in the background and then set the src attribute of the old image on load.
The event handler for load will be executed only once. The .complete check is necessary for browsers that may have cached the image to be loaded. In such cases, these browsers may or may not trigger the load event.
You can. When you want to reload something, you can just append a search query, so that it refreshes the source.
For Eg., when there is a frequently changing image (say captcha) and you wanna load it again, without refreshing the browser, you can do this way:
Initial Code:
<img src="captcha.png" alt="captcha" />
Refreshed Code:
<img src="captcha.png?1" alt="captcha" />
The script used here would be just:
var d = new Date();
$('img').attr('src', $('img').attr('src') + '?_=' + d.getMilliseconds());
Hope this helps! :)
Consider, if you have to fetch the URL again from the server, for a new image URL, you can do this way:
$.ajax({
url: 'getnewimageurl.php',
success: function(data) {
$('img').attr('src', data);
}
});
The server should return only a new image name in it. For eg., the PHP code should be this way:
<?php
$images = array("jifhdfg", "jklduou", "yuerkgh", "uirthjk", "xcjhrii");
die($images[date('u') % count($images)] . ".png"); // Get the random milliseconds mod by length of images.
?>
I suggest you use jQuery 'onImagesLoad' Plugin
This provides you with a callback when an image has finished loading.
When you receive new image URL from server, you create a new <img object with src="new_url_from_server" and attach 'onImagesLoad' callback to it. When your callback is called, your image has finished downloading.
Now you can just replace the 'src' attribute of old img object with new_url_from_server.
Since new image is already avaiable in cache, it will not be downloaded again and will be immediately displayed!
Aletrnatively, you can hide the old image and add this new image to DOM (not required if above works correctly)
Some bare bones sample could be like this:
<!DOCTYPE html>
<html>
<body>
<img id='bla' src="10.jpg" />
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.onImagesLoad.js"></script>
<script type="text/javascript">
$(function(){
var img = $('<div><img src="http://myserverbla/images/verybig.jpg"></img></div>');
img.onImagesLoad({
all : allImgsLoaded
});
function allImgsLoaded($selector){
var allLoaded = ""; //build a string of all items within the selector
$selector.each(function(){
$('#bla').attr('src','http://myserverbla/images/verybig.jpg');
})
}
});
</script>
</body>
</html>

Want to show “loading” image during the image download - Javascript

I am using the following script to display big images on mouse over the small images (example photo attached in the last). I want to show the 'loading' image (like this) while the big image is being downloaded from the server. How can this be achieved?
Note: I have asked a similar question here but I was not successful in applying the append function to the following code. Please help.
<script type="text/javascript">
function showIt(imgsrc)
{
var holder = document.getElementById('imageshow');
var newpic= new Image();
newpic.src=imgsrc;
holder.src=imgsrc;
holder.width = newpic.width;
holder.height=newpic.height;
}
</script>
<body>
/***on hover, xyz.jpg will be replaced by bigA.jpg and so on***/
<img src="smallA.jpg" onMouseOver="showIt('bigA.jpg')"/>
<img src="smallB.jpg" onMouseOver="showIt('bigB.jpg')"/>
<img src="xyz.jpg" id="imageshow" />
</body>
Images have a load event. As long as you set the load handler before the image.src is set, you should get notified when the image has successfully loaded or encounters some kind of error in loading. I do that very thing in a slideshow that I wrote so I know when the next image is ready for display and I display a wait cursor (animated gif like you're wanting) if the image has been delayed more than one second beyond it's appointed display time so the user knows what's going on.
In general, you can do something like this:
function loadImage(url, successHandler, errorHandler) {
var myImg = new Image();
myImg.onload = myLoadHandler; // universally supported
myImg.onabort = myErrorHandler; // only supported in some browsers, but no harm in listening for it
myImg.onerror = myErrorHandler;
myImg.src = url;
function myLoadHandler() {
successHandler(myImg, url);
}
function myErrorHandler() {
if (errorHandler) {
errorHandler(url);
}
}
}
Using code like this, you can display the wait cursor when you initiate the image load and hide it when the successHandler gets called.
If there were any other listeners to these events, then you should use addEventListener or attachEvent instead of onload, onabort, onerror, but if there's only one listener, you can go either way.
If the desired images are known in advance, then it's sometimes a better user experience (less waiting) to preload images that may be used later. This gets them into the browser's memory cache so they will appear instantly when needed. One can preload images either in HTML or in JS. In HTML, just insert tags into the web page for all the desired images (but hide them with CSS). In JS, just create an image array and create the image objects:
// image URLs to preload
var preloadImageURLs = [
"http://photos.smugmug.com/935492456_5tur7-M.jpg",
"http://photos.smugmug.com/835492456_968nf-M.jpg",
"http://photos.smugmug.com/735492456_3kg86-M.jpg",
];
var preloads = []; // storage for preloaded images
function preloadImages() {
var img, i;
for (i = 0; i < preloadImageURLs.length; i++) {
img = new Image();
img.src = preloadImageURLs[i];
preloads.push(img);
}
}
This will cause all the images in the preloadImageURLs array to be preloaded and available instantly later on in the life of the web page, thus preventing any user delays while waiting for images to be loaded. Obviously, there's a short amount of time for the preloaded images to actually get loaded, but for smallish images that usually happens before the user interacts with the web page so it makes for a faster feel to dynamic parts of the web page that use images.
<img id=access src=loading.gif>
<script>
window.onload=function(){
document.getElementById('access').src='access.jpg';
}
</script>
Hope this helps.

Categories