I am working on a project related to image processing. Currently, I am taking a image from the webcam and saving it in some folder. Then I display that image as a background image on the div. This works fine. But when I take the image again, the background image still remains the same. But when I see the image in the folder, it has changed.
Note: Both the images are saved by same name. So, previous image is just replaced by current image. And the image is taken by clicking a button.
html code:
<button id = "click" onclick = "mooddetect()">MOODY</button>
function mooddetect() {
$.ajax({
url: '/mooddetect/',
type:"POST",
cache:false,
success: function(input) {
var x = document.getElementById('photo');
x.style.backgroundImage = "url('/static/detect/test.jpg')";
},
failure: function(data) {
alert('Got an error dude');
}
});
}
views.py:
def get_image(camera):
retval, im = camera.read()
return im
def webcam():
camera_port = 0
ramp_frames = 30
camera = cv2.VideoCapture(camera_port)
for i in xrange(ramp_frames):
temp = get_image(camera)
print("Taking image...")
camera_capture = get_image(camera)
file = "./music/static/detect/test.jpg"
cv2.imwrite(file, camera_capture)
del(camera)
#csrf_exempt
def mooddetect(request):
webcam()
return HttpResponse("success")
UPDATE 2 - check this question for more info and better ways to acheive that: Refresh image with a new one at the same url
UPDATE:
What helped was saving the images with a new name and send the updated url to the front, as i assumed it have to do with cache, but im not sure why adding ?c=rand didn't helped.
I assume it will have to do with the cache of the browser.
Try to add timestamp or other rand number to the image url, so you will force to load the new image every time.
x.style.backgroundImage = "url('/static/detect/test.jpg?c=|some random number|')";
you can read more: how to clear or replace a cached image
Try this to clear the cache:
x.style.backgroundImage = `url('/static/detect/test.jpg?${Date.now()}')`
Related
Let me explain my use case:
I have a page, where I fetch the image by the url (from remote host) and display it. Also, I have a button on the page. When clicked, the image should be downloaded. I want to download the image without making any other remote calls.
So overall I want to support two things with a single fetch of the image:
Customer should be able to see the rendered image on the page.
Customer should be able to download the image by clicking the button.
Can you help me with how can I do that?
Actually, there is an answer to this:
You said that you would fetch the image:
Code should look something like this, so it is easy to extend.
let imageData
fetch('http://example.com/picture.png')
.then(response => response.blob())
.then(data => {
const urlCreator = window.URL || window.webkitURL;
imageData = urlCreator.createObjectURL(this.data);
document.querySelector("#your-image").src = imageData ;
//add this
document.querySelector("#your-link").href = imageData
//here, make sure your link has a download tag in the HTML or in the javascript
//
});
Demo: https://streamable.com/ize3yh
Did you see window.location.href ? https://www.w3schools.com/js/js_window_location.asp
in my reference project I was taking an image from the back end, making a URL.createObjectURL (img) and assigning a function to a button that simply does window.href.location = Processedimage on on: click. This way you can open the original image in another browser window, but again, I don't know how useful it will be. it is however a possible solution
I just started to learn a little bit of JavaScript and i wondered if there is a way to check if an image is already loaded to cache.
In my script im loading some random images from another webpage and display them.
When the same image will be displayed the second time, the script won't use the already loaded image, but instead load the same image again, so that there are two of them stored in my cache.
Now I want to check if the image is already stored in cache and if so, use the cached one instead of loading it again.
My code:
<script>
var img = document.createElement('img');
var index;
//On Click create random 3digit number between 1 and 100
document.getElementById('image').onclick = function(){
var index = '' + Math.floor(Math.random() * 100 +1);
while(index.length < 3) {
index = '0' + index;
}
loadImages(index);
};
//Load the image with the created number
function loadImages(id) {
var src = 'someWebPage/' + id +'.png';
img.onload = function () {
document.getElementById('image').getContext("2d").drawImage(img, 0, 0, 300, 300);
}
img.src = src;
}
</script>
Picture of my cache:
As you can see 030.png and 032.png are twice in cache.
Hope you can give me some advice.
EDIT:
Just for anyone else that faces this problem, it actually isnĀ“t one at all.
Chrome already did everything right, i only did not notice.
As you can see in the column Size the pictures were already loaded from my cache.
The way caching (in this context) is handled is by the browser negotiating with the server using a set of headers to basically tell the server "I already have this version of this resource", to which the server can then respond "OK, that is still valid, no need to download anything new". So you shouldn't be concerned about the caching in the JavaScript side, but instead make sure you are setting the correct Cache-Control headers on the server side. There are likely already questions/answers for your server/framework of choice on how to setup the caching there.
I am a complete beginner in javascript so I don't even know where to begin. I have a URL that displays a .jpg snapshot. It is served from a video server. I would like to take the image and display it on a webpage with the image being refreshed every 2 seconds. The image will be displayed in a div container with id="snapshot"
Any help or guidance will be greatly appreciated.
For your html, you do the following:
<div id="snapshot"><img/></div>
Then in your JavaScript you do the following:
var url = "some url somewhere";
var snapshotImg = document.querySelector('#snapshot > img');
var updateInterval = setInterval(updateImage, 2000); //start the update every 2 seconds
updateImage(); //immediately update the image
function updateImage(){
snapshotImg.src = url + "?"+ new Date().getTime();
}
In the 'updateImage' function, I added a ? and a time hash to the url so that each time it sets the source, the srcurl is unique. If you don't make it unique each time, the browser will cache the image from the first request, and it won't ever update the image. So, you have to make the url unique, and you that by adding a hash, that is arbitrary, to the end of the url. I hope that makes sense.
I'm using a javascript based opencv (See: https://github.com/mtschirs/js-objectdetect)
and it works perfectly with live video using canvas and html5.
When I try to detect using a dynamically saved image it fails, but works if I hard code an image.
The following (static image):
<img id="image" src="download.png"></img>
works fine, but using
var dataURL = $("#canvas")[0].toDataURL("image/png");
$("#image").attr('src', dataURL);
or using an ajax call which saves the image onto the server and returns the url path
$.ajax({
type: "POST",
url: "saveImage.php",
data: {
img: dataURL
}
}).done(function(o) {
$("#image").attr('src', o);
});
both fail. They both display an appropriate image.
the detection function is
$("#image").objectdetect(..., function(faces) { ... }
Executes, but returns array length 0 unless I use the static image
Had one of my co-workers figure it out. Image didn't load by the time it was being computed.
jQuery.ajaxSetup({
async : false
});
I had originally tried an $(element).load(function() { .. }) didn't seem to work but it seems it was a timing issue with the ajax.
This is the jQuery method that I have at my webpage, it refreshes a image every 5 seconds by loading the same page and replacing the image.
$(document).ready(function () {
var refreshId = setInterval(function () {
$.get('default.aspx', function (data) {
var page = data;
var image = $(page).find("img");
var fecha = $(page).find("div #fecha");
$("#Chart1").attr("src", image.attr("src"));
$("#fecha").text(fecha.text());
});
}, 5000);
});
I saw that everytime it loads the img, the data get stored somewhere in the browser and it doesnt cleans.. And when I open the task manager, I can see the memory usage growing up..
and heres a screenshot of the image axd..
Should I worry about freeing memory? Or everything is working as its supposed to..
why not reload the image by using just the url and not fetch the whole page that gets the url? if you want to prevent cache, either set the image not to cache via server headers, or use cachebusting
var img = document.getElementById('Chart1'); //use plain JS since it's just an ID
var refreshId = setInterval(function () {
var rand = "?"+(Math.random()*10000000000000000); //cache busting method
img.src = "path_to_image"+rand //set src using busted url
}, 5000);
this will still eat up disk space since each busted images is treated like a different image. if it were cached, you'd be using stale images. but at least you are not loading the whole page again an again.
Found out that the browser is just caching the images, but they are being cleaned eventually.
Use $post instead of $get. IE often cash GET request data.
There is just one img#Chart1 in your page, so there is only one image uses memory.
Others would just in the browser's cache.
But I don't think that default.aspx return in html format,
it should return data in json like:
{
imageUrl: "http://example.com/a.jpg",
fetcha: "some text"
}