I need help to add some line of code to check is file is image, to check extension. This is my code that I use for indicate progress of uploading images. I do that in php and user can't upload any file except .jpg .jpeg .gif and .png but he doesn't get a message that file isn't uploaded. When I add javascript code for progress upload, my php message taht i create doesn't display anymore.
This is my javascript
upload.js file code:
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('image_id');
var data = new FormData();
data.append('javascript', true);
if(fileInput.files[0].size > 1050000) {
document.getElementById("image_id").innerHTML = "Image too big (max 1Mb)";
alert('Fotografija koju želite dodati je veća od 1Mb!');
window.location="upload_images.php"
return false;
}
for (var i =0; i < fileInput.files.length; ++i) {
data.append('image', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event) {
if (event.lengthComputable) {
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes()) {
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + ' %'));
}
});
request.upload.addEventListener('load', function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Dodavanje slika nije bilo uspješno! Pokušajte ponovo.');
});
request.addEventListener('readystatechange', function(event) {
if (this.readyState == 4) {
if(this.status == 200) {
var links = document.getElementById('uploaded');
window.location="upload_images.php?success"
console.log(this.response);
} else {
console.log('Server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'upload_images.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
And this is my form for uploading file:
<div id="uploaded">
</div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<input name="image" id="image_id" type="file" size="25" value="Odaberi sliku" />
<input type="submit" id="submit" value="Dodaj Foto"/>
</form>
</div>
<div class="upload_progress" id="upload_progress"></div>
I need in that javascript code also to check is file is image. To allow jpg, jpeg, png and gif extensions and block others. To alert user if he trying to upload other kind of file.
if (!fileInput.files[0].name.match(/\.(jpg|jpeg|png|gif)$/i))
alert('not an image');
for Vue.js
if (filename.match(/.(jpg|jpeg)$/i)){
$('#modalimage').modal('show')
vm.downloadimage = result.data
}else{
const a = document.createElement('a')
a.setAttribute('href', result.data)
a.dispatchEvent(new MouseEvent("click", {'view': window, 'bubbles':
true, 'cancelable': true}))
}
Other accepted answers here were true at their time, but are decade old and are not perfect any more. For now use the below as the latest 2022 solution:
if (!fileInput.files[0].name.match(/\.(jpg|jpeg|png|gif)$/i))
alert('not an image');
Longer Explanation:
For e.g: 'name.ijpg' is not image, but monkeyinsight's accepted old answer still return true. While the latest above solution works perfectly. See below:
console.log('name.ijpg'.match(/.(jpg|jpeg|png|gif)$/i)); // Old Solution
console.log('name.ijpg'.match(/\.(jpg|jpeg|png|gif)$/i)); // Correct Solution
console.log('name.jpg'.match(/\.(jpg|jpeg|png|gif)$/i)); // Correct Solution
style you give class name-jsp
"Choose file",input:true,icon:true,classButton:"btn",classInput:"input-large name-jsp"
at your jsp or html you give id="cekJpg"(at click upload file not choose file)
<input id="cekJpg" type="submit" class="btn btn-primary" value="Upload image">
at javascript
//if click button upload image with id="cekJpg"
$("#cekJpg").on('click', function (e) {
//get your format file
var nameImage = $(".name-jsp").val();
//cek format name with jpg or jpeg
if(nameImage.match(/jpg.*/)||nameImage.match(/jpeg.*/)){
//if format is same run form
}else{
//if with e.preventDefault not run form
e.preventDefault();
//give alert format file is wrong
window.alert("file format is not appropriate");
}
});
Related
Here i have a image upload mechanism. It's purpose is to accept an image and display it in a div with id=imageholder . My problem is if i have this image holder div inside my form , it gives upload error (4) . So i get an empty $_FILES array. But if i omit it i get a populated $_FILES array .But i need that div inside the form for design purpose. How i can escape this situation .
with imagehoder div inside form:
without imageholder div :
code may seem long . But none of it is related to the question. It is generally for validating the mime type
full code :
<?php print_r($_FILES);?>
<html>
<body>
<form method='post' enctype='multipart/form-data' action="<?php echo $_SERVER['PHP_SELF'] ?>">
<div id='photouploder'>
<div id='imagehoder'></div> // creating problem
<div class="inputWrapper">upload image
<input class="fileInput" id='up' type="file" name="image"/>
</div>
</div>
<input type='submit' value='submit'>
</form>
<script>
var imageholder=document.getElementById('imageholder');
function getBLOBFileHeader(url, blob, callback,callbackTwo) {
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
var imgtype= callback(url, header);// headerCallback
callbackTwo(imgtype,blob)
};
fileReader.readAsArrayBuffer(blob);
}
function headerCallback(url, headerString) {
var info=getHeaderInfo(url, headerString);
return info;
}
function getTheJobDone(mimetype,blob){
var mimearray=['image/png','image/jpeg','image/gif'];
console.log('mimetype is :'+mimetype);
if(mimearray.indexOf(mimetype) !=-1){
printImage(blob);
}else{
document.getElementById('up').value='';
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
console.log('you can not upload this file type');
}
}
function remoteCallback(url, blob) {
getBLOBFileHeader(url, blob, headerCallback,getTheJobDone);
}
function printImage(blob) {
// Add this image to the document body for proof of GET success
var fr = new FileReader();
fr.onloadend = function(e) {
var img=document.createElement('img');
img.setAttribute('src',e.target.result);
img.setAttribute('style','width:100%;height:100%;');
imageholder.appendChild(img);
};
fr.readAsDataURL(blob);
}
function mimeType(headerString) {
switch (headerString) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
type = "image/jpeg";
break;
default:
type = "unknown";
break;
}
return type;
}
function getHeaderInfo(url, headerString) {
return( mimeType(headerString));
}
// Check for FileReader support
function fileread(event){
if (window.FileReader && window.Blob) {
/* Handle local files */
var mimetype;
var mimearray=['image/png','image/jpeg','image/gif'];
var file = event.target.files[0];
if(mimearray.indexOf(file.type)===-1 || file.size >= 2 * 1024 * 1024){
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
document.getElementById('up').value='';
console.log("you can't upload this file type");
file=null;
return false;
}else{
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
document.getElementById('up').value='';
remoteCallback(file.name, file);
}
}else {
// File and Blob are not supported
console.log('file and blob is not supported');
} /* Drakes, 2015 */
}
document.getElementById('up').addEventListener('change',fileread,false);
</script>
</body>
</html>
First of all: HTML attribute values should always be encapsulated in double quotes.
Second, this is a correct example of reading files using html5 API like you tried:
(Also check the documentation for it: https://developer.mozilla.org/en-US/docs/Web/API/FileReader)
window.onload = function() {
var fileInput = document.getElementById('up');
var fileDisplayArea = document.getElementById('imagehoder');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!"
}
});
}
<body>
<form method="post" enctype='multipart/form-data' action="<?php echo $_SERVER['PHP_SELF'] ?>">
<div id="photouploder">
<div id="imagehoder"></div>
<div class="inputWrapper">upload image
<input class="fileInput" id="up" type="file" name="image" />
</div>
</div>
<input type="submit" value="submit">
</form>
</body>
I'm not sure about the 'design purpose' in your question. If the 'design purpose' means UI design (CSS related), then probably this reason doesn't stand since they are totally irrelevant.
Also, the file upload technology is very mature now. There are bunches of open source implements in all languages and are well-tested and easy-to-use I highly recommend you to take a look at them before implementing it yourself.
I'm on a cordova and jquery mobile project.
I've been able to upload one image with file transfer plugin.
Now i try to upload 2 or 3 images following.
here is the html code:
<label for="image">Pictures:</label>
Get first picture<br>
Get second picture<br>
Get third picture<br>
<img id="image1" style="display:none;width:25%;">
<img id="image2" style="display:none;width:25%;">
<img id="image3" style="display:none;width:25%;">
<label for="title">Title</label>
<input data-clear-btn="true" name="title" id="title" value="" type="text">
<input value="Continue" type="submit" id="adButton">
here is jquery code:
multi_upload(user_id);
function multi_upload(user_id) {
var image1 = "image1";
var image2 = "image2";
var image3 = "image3";
if($('#image2').prop('src') == ''){
// upload one file
upload(user_id, image1, "true");
}
if($('#image3').prop('src') == ''){
// upload two files
upload(user_id, image1, "false");
upload(user_id, image2, "true");
}
if($('#image3').prop('src') != ''){
// upload three files
upload(user_id, image1, "false");
upload(user_id, image2, "false");
upload(user_id, image3, "true");
}
}
function upload(user_id, imagesrc, final) {
var img = '';
var imageURI = '';
img = document.getElementById(imagesrc);
imageURI = img.src;
console.log("[imageURI] "+imageURI);
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = {};
params.timestamp = Math.round(+new Date()/1000);
params.public_token = localStorage.getItem("token_public");
params.hash = SHA1(params.timestamp+localStorage.getItem("token_private"));
params.user_id = user_id;
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
if(final == "true"){
ft.upload(imageURI, "http://www.example.com/api/index.php/privates/upload", finalwin, fail, options);
}else{
ft.upload(imageURI, "http://www.example.com/api/index.php/privates/upload", win, fail, options);
}
}
If i upload two files for example, the code will upload two times the last selected picture. the console give me the imageURI who looks like this:
file:///storage/sdcard0/Android/data/fr.myproject.propro/cache/modified.jpg?1418726649440:500
I suppose that is a temporary file, so i presume when i select the last file, it delete the previous one... how can i find the real path of this images?
We recently sat with the same problem, and found that the cache file (project/cache/modified.jpg) was overriden (as you note) by a new selection, although FileTransfer.upload seems to treat it as two different files (presumably due to the ?-parameter) and thus uploads it twice.
As a workaround, we ended up renaming the files to include a timestamp before the name, such that modified.jpg?1418726649440 becomes 1418726649440modified.jpg, prior to uploading them:
function renameFile(src, callback) {
var d = new Date();
//find the FileEntry for the file on the device
window.resolveLocalFileSystemURL(src, function(fileEntry) {
//get the parent directory (callback gives a DirectoryEntry)
fileEntry.getParent(function(parent) {
//rename the file, prepending a timestamp.
fileEntry.moveTo(parent, d.getTime() + fileEntry.name, function(s) {
//Callback with the new URL of the file.
callback(s.nativeURL);
}, function(error) {
alert('Error on moving file!');
callback(src); //Fallback, use the src given
});
}, function(error) {
alert('Error on getting parent!');
callback(src); //Fallback
});
}, function(error) {
alert('Error on resolveLocalFileSystemURI!');
callback(src); //Fallback
});
}
With src being the imageURI (i.e. path of the file), and callback being the function that uploads the file. (I should note that we're not entirely sure if we need the getParent call, as one could presumably get the DirectoryEntry by parsing src, but better safe than sorry)
NOTE: This requires the File plugin, and, depending both on your version of Cordova and File, may need to be edited somewhat (as the API has changed a little between versions).
I'm trying to upload generated client side documents (images for the moment) with Dropzone.js.
// .../init.js
var myDropzone = new Dropzone("form.dropzone", {
autoProcessQueue: true
});
Once the client have finished his job, he just have to click a save button which call the save function :
// .../save.js
function save(myDocument) {
var file = {
name: 'Test',
src: myDocument,
};
console.log(myDocument);
myDropzone.addFile(file);
}
The console.log() correctly return me the content of my document
data:image/png;base64,iVBORw0KGgoAAAANS...
At this point, we can see the progress bar uploading the document in the drop zone but the upload failed.
Here is my (standart dropzone) HTML form :
<form action="/upload" enctype="multipart/form-data" method="post" class="dropzone">
<div class="dz-default dz-message"><span>Drop files here to upload</span></div>
<div class="fallback">
<input name="file" type="file" />
</div>
</form>
I got a Symfony2 controller who receive the post request.
// Get request
$request = $this->get('request');
// Get files
$files = $request->files;
// Upload
$do = $service->upload($files);
Uploading from the dropzone (by drag and drop or click) is working and the uploads are successfull but using the myDropzone.addFile() function return me an empty object in my controller :
var_dump($files);
return
object(Symfony\Component\HttpFoundation\FileBag)#11 (1) {
["parameters":protected]=>
array(0) {
}
}
I think i don't setup correctly my var file in the save function.
I tryied to create JS image (var img = new Image() ...) but without any success.
Thanks for your help !
Finally i found a working solution without creating canvas :
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
And the save function :
function save(dataURI) {
var blob = dataURItoBlob(dataURI);
myDropzone.addFile(blob);
}
The file appears correctly in dropzone and is successfully uploaded.
I still have to work on the filename (my document is named "blob").
The dataURItoBlob function have been found here : Convert Data URI to File then append to FormData
[EDIT] : I finally wrote the function in dropzone to do this job. You can check it here : https://github.com/CasperArGh/dropzone
And you can use it like this :
var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAAKwCAYAAA...';
myDropzone.addBlob(dataURI, 'test.png');
I can't comment currently and wanted to send this to you.
I know you found your answer, but I had some trouble using your Git code and reshaped it a little for my needs, but I am about 100% positive this will work for EVERY possible need to add a file or a blob or anything and be able to apply a name to it.
Dropzone.prototype.addFileName = function(file, name) {
file.name = name;
file.upload = {
progress: 0,
total: file.size,
bytesSent: 0
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
return this.accept(file, (function(_this) {
return function(error) {
if (error) {
file.accepted = false;
_this._errorProcessing([file], error);
} else {
file.accepted = true;
if (_this.options.autoQueue) {
_this.enqueueFile(file);
}
}
return _this._updateMaxFilesReachedClass();
};
})(this));
};
If this is added to dropzone.js (I did just below the line with Dropzone.prototype.addFile = function(file) { potentially line 1110.
Works like a charm and used just the same as any other. myDropzone.addFileName(file,name)!
Hopefully someone finds this useful and doesn't need to recreate it!
1) You say that: "Once the client have finished his job, he just have to click a save button which call the save function:"
This implies that you set autoProcessQueue: false and intercept the button click, to execute the saveFile() function.
$("#submitButton").click(function(e) {
// let the event not bubble up
e.preventDefault();
e.stopPropagation();
// process the uploads
myDropzone.processQueue();
});
2) check form action
Check that your form action="/upload" is routed correctly to your SF controller & action.
3) Example Code
You may find a full example over at the official Wiki
4) Ok, thanks to your comments, i understood the question better:
"How can i save my base64 image resource with dropzone?"
You need to embedd the image content as value
// base64 data
var dataURL = canvas.toDataURL();
// insert the data into the form
document.getElementById('image').value = canvas.toDataURL('image/png');
//or jQ: $('#img').val(canvas.toDataURL("image/png"));
// trigger submit of the form
document.forms["form1"].submit();
You might run into trouble doing this and might need to set the "origin-clean" flag to "true". see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements
how to save html5 canvas to server
I'm trying to get image as Object of javascript on the client side to send it using jQuery
<html>
<body>
<script language="JavaScript">
function checkSize()
{
im = new Image();
im.src = document.Upload.submitfile.value;
if(!im.src)
im.src = document.getElementById('submitfile').value;
alert(im.src);
alert(im.width);
alert(im.height);
alert(im.fileSize);
}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <input type="file" name="submitfile" id="submitfile" />
<input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>
But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?
The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.
var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
var width;
var height;
var fileSize;
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
width = img.width;
height = img.height;
fileSize = imgFile.files[0].size;
alert(width);
alert(height);
alert(fileSize);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(imgFile.files[0]);
}
I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.
This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.
<div>
<div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
<input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>
$('img#logo').click(function(){
$('#logoupload').trigger('click');
$('#logoupload').change(function(e){
var reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
});
function onFileLoad(e) {
var data = e.target.result;
$('img#logo').attr("src",data);
//Upload the image to the database
//Save data on keydown
$.post('test.php',{data:$('img#logo').attr("src")},function(){
});
}
});
$('#imagess').change(function(){
var total_images=$('#total_images').val();
var candidateimage=document.getElementById('imagess').value;
formdata = false;
var demo=document.getElementById("imagess").files;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = demo.length, img, reader, file;
for ( ; i < len; i++ ) {
file = demo[i];
if (file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images", file);
}
}
}
$('#preview').html('Uploading...');
var url=SITEURL+"users/image_upload/"+total_images;
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
$('#preview').html('');
if (res == "maxlimit") {
alert("You can't upload more than 4 images");
}
else if (res == "error") {
alert("Image can't upload please try again.")
}
else {
$('#user_images').append(res);
}
}
});
});
Suppose i have EXTERNAL URL(not from my website) and i want to verify it to make sure this url is one from these files:- jpg, jpeg, gif, png and also is a correct image file (not any script file or php). Also if this is possible:- Check if the url of the image is working or not.
#jfriend00 ok so here is what i'am trying to do. I had maded html form and when people submit it, it will call to a javascript function which will verify if the url is an image. So here is my code. But it's not working. Please tell me what should i do from here?
<script type="text/javascript">
function vrfyImgURL() {
var x = document.forms["submitIMGurl"].elements["img_url"].value;
if(x.match('^http://.*/(.*?).(jpe?g|gif|png)$')){
var imgsrc = x;
var img = new Image();
img.onerror = function(){
alert("Can't Be Loaded");
return false;
}
img.onload = function(){
alert("Loaded Successfully");
return true;
}
img.src = imgsrc;
}else{
alert("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.");
return false;
}
}
</script>
<form action="http://www.example.com/current_page" enctype='multipart/form-data' method="post" onsubmit="return vrfyImgURL();" name="submitIMGurl">
<input type="text" value="http://" name="img_url" />
<input type="submit" value="Submit" />
</form>
Your code in this post is not a correct implementation of the function I gave you in the previous post and will not work for a number of reasons. You cannot return true/false from the onload, onerror handlers. Those are asychronous events and your vrfyImgURL function has already returned.
You really HAVE to use the code I put in that previous post. It works. Just use it. Don't modify it. You pass in a callback and that callback gets called with the validation check results. You have to use asynchronous programming to use this where the callback gets called with the result. You can't use straight sequential programming like you are trying to do. It is your modifications to my code that have made it stop working.
You can see the code I gave you previously work here:http://jsfiddle.net/jfriend00/qKtra/ and in the example, it's working with images from a variety of domains. It is not sensitive to the domain of the image and <img> tags are not restricted by domain.
To hook it up to your form submit, you can do this:
<form action="http://www.example.com/current_page" enctype='multipart/form-data' method="post" onsubmit="return formSubmit();" name="submitIMGurl">
<input type="text" value="http://" name="img_url" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function formSubmit() {
var url = document.forms["submitIMGurl"].elements["img_url"].value;
if (!checkURL(url)) {
alert("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.");
return(false);
}
testImage(url, function(testURL, result) {
if (result == "success") {
// you can submit the form now
document.forms["submitIMGurl"].submit();
} else if (result == "error") {
alert("The image URL does not point to an image or the correct type of image.");
} else {
alert("The image URL was not reachable. Check that the URL is correct.");
}
});
return(false); // can't submit the form yet, it will get sumbitted in the callback
}
function checkURL(url) {
return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
}
function testImage(url, callback, timeout) {
timeout = timeout || 5000;
var timedOut = false, timer;
var img = new Image();
img.onerror = img.onabort = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "error");
}
};
img.onload = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "success");
}
};
img.src = url;
timer = setTimeout(function() {
timedOut = true;
callback(url, "timeout");
}, timeout);
}
</script>
If this were my interface, I would disable the form and put up a note that the image URL is being checked starting when testImage is called and ending when the callback is called.