How does the loading of an image with "?random=" attached work? - javascript

So, I wanted to avoid the cache to see images I'm uploading to this website I'm working on, which I access through localhost.
I hit a handy solution pretty quick:
Attaching to the end of image's path ?random= and a random number generated by Math.floor(). All this with the help of a script.
The HTML showed in the browser:
<img class="gallery_img" src="./uploads/4.jpg?random=172">
Awesome, it works beautifully.
Now, the thing that has been hard to find is an explanation of why and how this actually works.
I mean, 1) how the browser still finds the image in the server with this new path?
Or asked the other way around, 2) how the server handles this ?random=172 attachment and delivers the image asked before that?
If somebody could point me to the right direction I would be grateful.
Solution:
Have a look on what are query parameters.
And if you are dealing with the problem of avoiding the cache, have a look here:
Disable cache for some images

That is not part of the path, that is a query parameter.
And most of the times the server of images does not care about query parameters, at least not a literally random one, maybe it would support a query parameter called width or size and dynamically generate an image of the correct size. But random is most likely simply discarded and the image is served normally.

Related

For image Aspect ratio calculation image is getting loaded 2 times

I'm trying to solve image is loading 2 times for a single preview
1st time image will be loaded for preview purpose in iframe
2nd time image metadata such as width, height will be fetched with same path
Below image shows 2 times loading same image:
in both the call 8.9kB,8.6kB will be loaded i want to avoid that.
Question: I want to calculate image aspect ratio with single load of image. 2 calls i need to avoid
Note: i want iframe based solution
Here is demo: https://codepen.io/eabangalore/pen/rNLWJWE?editors=1010
For reproducing: we need to disable cache
Please help me thanks in advance!!!
The way you asked your question is very frustrating because you have created arbitrary "limitations" (eg. iframe, disabled cache) but don't describe why those limitations are necessary. Looking at your code it's clear that you don't have much experience working in the web/javascript, so it would be really nice if you told us what you needed as opposed to how to do it. We could probably come up with a much better solution for you.
Anyhow, to answer your question the way you asked... what you need to do is load the resource ONCE outside of an image tag or iframe (in memory), base64 encode the result, and use the encoded data for both the iframe src and the image src. Here's the pseudocode:
// this first line will load the image
const imageData = fetchImageAsDataUrl('http://path-to-your-image');
// these next two lines use the existing image data from above
// you will see two entries in the "network" tab with urls like "data:image/jpeg..."
// but there was no additional data transferred across the internet
iframe.src = imageData;
img.src = imageData;
const dimensions = getImgDimensions(img)
If you look at the network tab, you will see that only one image is transferred over the internet (the first circle). The next two circled entries happen because the iframe/img src attributes are set, but the data was not loaded over the internet (notice how the url starts with data:image/jpeg...).
Here's the codepen:
https://codepen.io/DesignByOnyx/pen/gOMKYzL?editors=1010
The browser is generally speaking smart enough to not fetch the same asset twice from the server, this is called caching. The checkmark Disable cache in your devtools is checked, meaning it will not use cache. This can be useful while developing but you can trust that people generally will not disable cache.
I also don't see the same behaviour on the codepen.
The only way you would be able to achieve this using an iframe is if you have control over the domain it is loading or there are means by which you can enable cross origin resource sharing. That way you will be able to access the DOM contents of the iframe and retrieve the needed information from the image element in there.
Another solution is to avoid using iframe in the first place which doesn't make much sense in the example you have given, but you've said you prefer it to stay that way.
And still worth mentioning, as stated in the other answer, the browser will most likely not fetch the image twice anyway so you don't need to worry about that.

Issue displaying local image files via css class and/or img src attribute

I have some issues rising up displaying Image files from local filesystem.
And to say it before: yes i am aware of the security breach this is causing and there is no other way playing it different because my company has no file Server yet to serve these images in a proper way.
With that out of the way the scenario:
I have an angular app which should show me some Images on my page. I wrote a directive called Gallery to do so.
Into this gallery I am handing in the absolute paths to my Image files and just set the src attribute via javascript. I tested it with some random chosen files picked from Google and everything worked out well. Allthough my browser is throwing out error because of security the picutres were displayed.
But when i got the real data from my company collegue Things started getting nasty. The error still thrown in console but nothing was displayed. I checked first overwriting the img.onload listener finding out that the testimages are giving me the Output i put onto the listener, my real data images didn't.
Next I tried to set the background attribute and not the src one. My test images were displayed the real data ONLY if it is placed into the assets folder of my app. This got me quite confused because like mentioned above using my test images it doesn't matter where they are placed, they are displayed everytime.
I also tried changing file format from png to jpg but nothing happens.
Also scaling down the images (real data has big px solutions) didn't work either.
So my question is simple ...what am i doing wrong? Could it be possible that those real data images are not exported properly. But if that's the case, why do they work in the assets folder? Like mentioned security block is not possible because my test pictures a doing well.
Finally I found the bug which was responsible for the behaviour ... It was no wrong linking it was the IIS Express which was caching old links. #mrunion and #cloned links to filesystem are still working on IE and also in Edge just for devs which have no other choice then to do it that way
Cheers Max

Prevent caching of Images on webpage

I am using an IHttpHandler to display an image stored in an azure blob on a webpage. This works fine. I also give the user the ability to rotate the image. The code to rotate the image is working. However when I then try to show the rotated image to the user:
document.getElementById("imageControl").src = "/ImageHandler.ashx?container=images&ID=blobFileName;
the image shown on the page is not updated although the image stored at 'blobFileName' has been changed. After some trial and error I found that if I store the rotated blob under a new file name, say 'blobFileNameRotated' the code:
document.getElementById("imageControl").src = "/ImageHandler.ashx?container=images&ID=blobFileNameRotated;
works and displays the rotated file. I assume that the original code doesn't work because the image has been cached by the browser? I tried running the code in a couple of browsers and found that in Chrome the original code works, but only for small files, and that it doesn't work at all in IE11.
My question is how can I control how a browser caches the image file (if that is the problem) and force the browser to re-display the image even if I haven't changed the file name. I tried setting src to a different file and then back to the blob file but that didn't work.
Not really an Azure issue but a few things to try:
You could add a cache-buster to your Image Handler URL. I'd recommend just appending a random number on the end to force the browser to re-request the URL. The problem is no image will ever be cached. Example:
document.getElementById("imageControl").src = "/ImageHandler.ashx?container=images&m=" + Date.now();
Use the same approach but output the number of images to be shown and change Date.now() to am image name / ID so that we as you rotate you will eventually get the same image which should be cached.
// output using some server-side logic.
var imageIds = new Array("ImageA","ImageB","ImageC");
// in an eventHander have similar to:
document.getElementById("imageControl").src = "/ImageHandler.ashx?container=images&ID=" + imageIds[currentImage]
Make sure you set the correct cache headers in your hander's C# code. See Caching ASHX Image Response
Sorry for the slow response to this, my solution was sort of working so I've only just got round to testing out Simon's better solutions. I thought I would add some other things I've found out along the way in case others come to this question looking for information about blobs and images.
My solution involved changing the name of the file each time I rotated it. This meant that I stored a new blob for each 90 degree rotation. This worked but Simon's solution just involves changing the call to the imagehandler so the blob filename doesn't need to change.
I initially ran into problems because I didn't set the content type of the blob after I had rotated it. When I then tried to use the image in a report, the code complained because it wasn't an image type.
Note that if you want to copy the content type from the blob you are rotating it is not available after you have executed:
Dim blob As ICloudBlob = GetBlob(sContainer, blobFileName)
but only after the blob has been downloaded:
blob.DownloadToByteArray(byteData, 0)
This tripped me up at another time as well because I assumed that a blob had been found because I didn't get an error on the dim blob as line of code when in fact it couldn't have been found because I'd passed in the wrong container name.
Happy blobbing.

is it possible to convert a DIV to image with any javascript library [duplicate]

I'm wondering is there a JavaScript library available that would allow me to generate an Image from the contents of a DIV.
Basically this is required for some Server-Side Printing code, which needs to print a background from the Browser.
What I'd ultimately like to do would be encode the DIV contents into PNG format and post up the encoded data with the print operation.
Any ideas if this is possible ?
[EDIT] What I have is a mapping application where background data is coming from an image server straight into a browser DIV (Think Google Maps). That div is background to me main data. When Print is pressed the server generates a PDF from the data it knows about, but knows nothing about the browser's background data. What I'd really like is to be able to provide the server with the browsers background image in some way!
Cheers,
Ro
Maybe it's possible with the Canvas:
MDN - Drawing Graphics with Canvas
You can create an image tag from JavaScript but not the actual image in it: JS has no commands to allocate memory for the bitmap and it has no commands to render anything on it.
The usual solution is to have a report generator on the server which creates the image on request. Look at BIRT or JasperReports.
[EDIT] Based on your comment, the solution is simple: Examine the DIV, find the URL for the background image and replace the DIV with an IMG element. Put the URL into the SRC attribute and then print.
Very interesting question.
Actually I solve this problem using ajax (transfer images' positions to the server, server creates one image from pieces, save it and send url to the client). I don't very like this solution but I don't know other yet.
I really don't think this is possible on the browser, certainly not without some kind of plugin.
Could you send some coordinate info or something to the web server and that way have the web server request the same map image from the image server?
Generating images was only possible in IE5 :( Then due to security reasons it was dropped. I'm still missing it.
I think I've worked out a way to do it.
1) When the user presses Print, interrogate the DIV
2) Images on that DIV are being generated by the OpenLayers API
3) Grab the URL of each Image
4) Grab the location on screen of each image
5) Translate the screen location into a Real-World location (I have API for this)
6) As part of the print send up all the image URL's along with their real-world extents
7) Allow the server to re-request the Images and draw them into their appropriate locations.
Does it have to be done on the browser side? I have seen where you can do a server side call and the MIME type on the server response is the image type. I think the example I'm thinking of was for b64 encoded jpegs in a db, but the process should be the same. The response would be the data that is currently in your DIV. Sorry if I'm way off base.

javascript button which stops the image loading process

I want to make a javascript (or jQuery if that's a possibility) button for my HP which stops the loading of the images on the page (for example when a user has to pay per MB and is only interested in the text).
I searched and searched and found answers like "remove the src", or "use window.stop()", but the problem is that they don't work, cancel the whole loading process, or simply don't do what I had in mind (like removing the images completely).
Does anyone know how I could achieve that?
Thank you very much :)
PS.: found a how to that claims that it can stop the download of specific parts of the site, but it doesn't really explain how to specify the part. I don't get how to link things here so here's the url: http://www.ehow.com/how_6104889_kill-browser-downloads-javascript.html
Thanks again.
Short answer: don't bother. If a user has such limited bandwidth that loading images is a problem, they will have disabled images anyway, or they will use some mechanism to load images on demand. You don't want to burden users with a non-standard solution that only works on your homepage. Simply put, it is not your problem.
Long answer: you can use placeholders instead of actual images on the initial page load, and then use Javascript to set the src attributes one by one, having each successful load trigger the next image. You will lose parallel loading though, which means you are punishing high-bandwidth users (which is the overwhelming majority these days) with much longer loading times, and you'll be spending a lot of effort on a feature that is (see short version) mostly useless.
You could try to change src to point to an empty image.
You won't be able to cancel the image loading process programmatically from within the web page.
You could try breaking all image srcs using JavaScript but it's a dirty approach, and your results may vary - it could be that the browser continues to load the resource nevertheless.
The best way to go would probably be either loading images on demand (which is possible to do from within the page), or offer the option of serving pages from server side that don't contain the images in the first place.
However, as #tdammers correctly points out in his answer, it's probably best not to bother. People on a traffic quota will take their own precautions against loading too much content.
I wouldn't bother replicating a browser configuration option with an in-page button, but I would recommend showing a placeholder image then lazy-loading the images for mobile users.
Also as you like JQuery, there are jQuery Lazy-Loading plugins out there.

Categories

Resources