Refresh Image With a New One At the Same Url

Refresh image with a new one at the same url

What I ended up doing was having the server map any request for an image at that directory to the source that I was trying to update. I then had my timer append a number onto the end of the name so the DOM would see it as a new image and load it.

E.g.

http://localhost/image.jpg
//and
http://localhost/image01.jpg

will request the same image generation code but it will look like different images to the browser.

var newImage = new Image();
newImage.src = "http://localhost/image.jpg";
var count = 0;
function updateImage()
{
if(newImage.complete) {
document.getElementById("theText").src = newImage.src;
newImage = new Image();
newImage.src = "http://localhost/image/id/image" + count++ + ".jpg";
}
setTimeout(updateImage, 1000);
}

Use React to refresh image with a new one at the same Signed Url

I was able to resolve this. Pointing the img.src directly at the Signed Url left me with no way to force the browser to refresh the image.

However, I was able to fetch the image through the Signed Url in my React javascript instead, convert it to base 64, and then set the img.src to a data string. This can be set on a timer as needed.

const url ='signed url';

// Fetch from the signed url. Ensure that the image is not retrieved from cache
const response = await fetch(url, { cache: 'no-store' });
const buffer = await response.arrayBuffer();

// Convert from buffer to base64 (thanks [devlucky][1])
let binary = '';
const bytes = [].slice.call(new Uint8Array(buffer));
bytes.forEach(b => binary += String.fromCharCode(b));
const base64 = window.btoa(binary);

const src = `data:image/jpeg;base64,${base64}`;

this.setState({ src });
<img src={this.state.src}>

How to properly refresh a page to display an image

I think this could be a cache issue. Even though the images are different after refresh, the browser is showing the previously cached images since the file name is the same. Perhaps try adding a query parameter to the end of the image src to bypass the browsers caching functionality for images with the same src. Try writing it like this and see if it works:

<!DOCTYPE HTML>
<html>

<head>
<title>RePlay</title>
<meta http-equiv="refresh" content="10">
</head>

<body id = "body" style = "text-align:center;">

<h1 style = "color:green;" >
RePlay
</h1>

<h2 style = "color:black;" >
Courts Live Update
</h1>


<img id="img-1" src="Image1.png" align = "left" width="500" height="333">
<img id="img-2" src="Image2.png" align = "right" width="500" height="333">

</body>
<script>
let img1 = document.getElementById('img-1');
let img2 = document.getElementById('img-2');

img1.src = 'Image1.png?t=' + new Date().getTime();
img2.src = 'Image2.png?t=' + new Date().getTime();
</script>
</html>

In this example, I'm adding the datetime to a query parameter to ensure a new pathname for the image each refresh. That way the browser won't try to cache the image since the src will be different each time.

Reload img element from same source

The problem is that the image src is not altered so the image is not reloaded.

You need to convince the browser that the image is new. A good trick is to append a timestamp to the url so that it is always considered new.

function update() {
var source = 'http://192.168.1.53/html/cam.jpg',
timestamp = (new Date()).getTime(),
newUrl = source + '?_=' + timestamp;
document.getElementById("img").src = newUrl;
document.getElementById("img1").src = newUrl;
setTimeout(update, 1000);
}

refresh image when source changed

Everytime that the image changes you execute this code:

yourImage.src = "http://localhost/image.jpg?" + new Date().getTime();

If you can't catch this event, just instantiate an interval

setInterval(function(){ yourImage.src = "http://localhost/image.jpg?" + new Date().getTime(); }, 1);

Auto reload HTML image on each loop iteration in Python code using BottlePy

If you add random parameter to url - map.png?random_value (ie. current date with time and seconds) - then browser automatically reload image.

So in JavaScript you can do

<img id="map" src="{{ get_url('static', filename='map.png') }}" />

$.get('/refresh', function(){
d = new Date();
$("#map").attr("src", "{{ get_url('static', filename='map.png') }}?"+d.getTime());
});

Minimal working code

import os
import time

import bottle
from bottle import route, run, template, BaseTemplate, static_file

import numpy as np
from PIL import Image

app = bottle.default_app()
BaseTemplate.defaults['get_url'] = app.get_url

@route('/')
def index():
return template('''<!DOCTYPE html>
<html>
<head>
<title>HARTA</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<img id="map" src="{{ get_url('static', filename='map.png') }}" />
<script>
$(document).ready(function(){
setInterval(refreshFunction, 1000);
});

function refreshFunction(){
$.get('/refresh', function(){
d = new Date();
$("#map").attr("src", "{{ get_url('static', filename='map.png') }}?"+d.getTime());
console.log($("#map").attr("src"));
});
}
</script>
</body>
</html>''')

@route('/<filename:path>', name='static')
def serve_static(filename):
return static_file(filename, root='static')

@route('/refresh')
def refresh():
os.makedirs('static', exist_ok=True)
newmapp = np.random.rand(100,100,3) * 255
data = Image.fromarray(newmapp.astype('uint8')).convert('RGBA')
data.save('static/map.png')
return "OK"

run(host='localhost', port=8080)

Reload image without refreshing the page

Change your img tag to this:

<img id="badge" src="$cms_url/imaging/badge.php?badge=$mygroup['badge']; ?>">/imaging/badge.php?badge=<?php echo $mygroup['badge']; ?>" />

Then you can use below code to change your image source on click of a button, anchor or whatever:

document.getElementById("badge").src="new image src here";

You can use jQuery as well:

$("#badge").attr("src", "new image src here");

How to reload image url one more time if url shows error in loading

Try setting image url in state and update when error on loading image.

product.js

import React from 'react';
import { View } from 'react-native';
import FastImage from 'react-native-fast-image';

class Product extends React.Component {
constructor(props){
super(props);
this.state = {
uri : this.props.product.productImage,
errorCount : 0
}
}

render() {
const { productImage } = this.props.product
return (
<View>
<FastImage
style={{ width: 200, height: 200, borderWidth: 2, }}
source={{ uri:this.state.uri }}
resizeMode={FastImage.resizeMode.contain}
onError={e =>
this.state.errorCount < 3 &&
this.setState(
{uri: '', errorCount: ++this.state.errorCount},
() => this.setState({uri: productImage}),
)
}
/>
</View>
)
}
}

export default Product;

What is the best way to force an image refresh on a webpage?

This is a trick, but it works.

Put a variable and random number in the image url. Something like:

<img src="photo.jpg?xxx=987878787">

Maybe there's a better way, but it works for me.



Related Topics



Leave a reply



Submit