First of all I am sorry if I am asking which was asked previously, But in fact I didn't get anything . I have some <Div> on my asp.net page. And using Javascript I am assigning background image from Url. Below is code
divFloor.style.backgroundImage = "url(Images/FloorPlan/" + hdnFloorImgSplit[1] + ")";
hdnFloorImgSplit is array contains the url of image. This is because I am using Azure cloud service.
When client refresh page or post back the page, The images are getting downloaded each time.
What I want is , I want to store it on client browser and used it from there if exists. This will save server and clients bandwidth and speed will increase dramatically.
Sorry but I am unable to find out the way. I have many images that I want to store and retried. Because of which my site is getting slow.
Any help appreciated
Blade , They have many different methods for do that . I show you one .With localstorage Json db.
You can use another method like Blob with XMLHttpRequest Level 2.
For more information about it , you can check this link
-> Saving images and filesin localStorage - javascript
Storing images ( you need store in first all your pictures with localStorage.SetItem ....)
The idea here is to be able to take an image that has been loaded into the current web page and store it into localStorage. As we established above, localStorage only supports strings, so what we need to do here is turn the image into a Data URL. One way to do this for an image, is to load into a canvas element. Then, with a canvas, you can read out the current visual representation in a canvas as a Data URL.
Let’s look at this example where we have an image in the document with an id of “elephant”:
// Get a reference to the image element
var elephant = document.getElementById("elephant");
// Take action when the image has loaded
elephant.addEventListener("load", function () {
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("image/png");
// Save image into localStorage
try {
localStorage.setItem("elephant", imgAsDataURL);
}
catch (e) {
console.log("Storage failed: " + e);
}
}, false);
Then, if we want to take it further, we can utilize a JavaScript object and do a date check with localStorage. In this example, we load the image from the server through JavaScript the first time, but for every page load after that, we read the saved image from localStorage instead:
HTML
<figure>
<img id="elephant" src="about:blank" alt="A close up of an elephant">
<noscript>
<img src="elephant.png" alt="A close up of an elephant">
</noscript>
<figcaption>A mighty big elephant, and mighty close too!</figcaption>
</figure>
JAVASCRIPT
// localStorage with image
var storageFiles = JSON.parse(localStorage.getItem("storageFiles")) || {},
elephant = document.getElementById("elephant"),
storageFilesDate = storageFiles.date,
date = new Date(),
todaysDate = (date.getMonth() + 1).toString() + date.getDate().toString();
// Compare date and create localStorage if it's not existing/too old
if (typeof storageFilesDate === "undefined" || storageFilesDate < todaysDate) {
// Take action when the image has loaded
elephant.addEventListener("load", function () {
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);
// Save image as a data URL
storageFiles.elephant = imgCanvas.toDataURL("image/png");
// Set date for localStorage
storageFiles.date = todaysDate;
// Save as JSON in localStorage
try {
localStorage.setItem("storageFiles", JSON.stringify(storageFiles));
}
catch (e) {
console.log("Storage failed: " + e);
}
}, false);
// Set initial image src
elephant.setAttribute("src", "elephant.png");
}
else {
// Use image from localStorage
elephant.setAttribute("src", storageFiles.elephant);
}
Related
I have a simple input box of type file and a button. I am trying to store the file in the session on click of button so that if page is refreshed it will be in session.
I tried using
function storeInSession(){
element = document.getElementById('attachments')
var file = element.files[0];
sessionStorage.setItem('fileInSession', file)
sessionFile = sessionStorage.getItem('fileInSession')
}
<input type="file" id="attachments">
<button onclick="storeInSession()">Upload</button>
Is there any way I can do this?
Storing images
The idea here is to be able to take an image that has been loaded into the current web page and store it into localStorage. As we established above, localStorage only supports strings, so what we need to do here is turn the image into a Data URL. One way to do this for an image, is to load into a canvas element. Then, with a canvas, you can read out the current visual representation in a canvas as a Data URL.
Let’s look at this example where we have an image in the document with an id of “elephant”:
// Get a reference to the image element
var elephant = document.getElementById("elephant");
// Take action when the image has loaded
elephant.addEventListener("load", function () {
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("image/png");
// Save image into localStorage
try {
localStorage.setItem("elephant", imgAsDataURL);
}
catch (e) {
console.log("Storage failed: " + e);
}
}, false);
You can encode binary data to base64 format, and use it as string
I have been trying to upload an image and convert it into grayscale version then display both images on a webpage. I have test and verified the working of the javascript code locally and it works. However when I integrate it into my webpage only the orignal image is being uploaded. The greyscale image is not being generated or the function is not being processed.
function doUpload(){
var image = new SimpleImage(inputFile);
image.drawTo(CanvasOG);
var imageGS = grayScale(image);
imageGS.drawTo(CanvasGS);
//var NewImage = grayScale(image);
//NewImage.drawTo(CanvasGS)
}
Can you tell me what went wrong?
PS Im using the Duke university's learn to program course's SimpleImage library for the functions to read the images and pixel values
Im posting a link to the codepen page incase you want to see the entire code with the html page
https://codepen.io/girish-kumar-peddi/pen/PoPBxKb
The nature of SimpleImage.js drawTo() contains a setTimeout(). Thus the imageData is not set instantly, but after 100ms. So after the image is drawn to the canvas, wait sometime before manipulating the image data. Enclosed the drawTo() implementation below.
// Draws to the given canvas, setting its size to match SimpleImage's size
drawTo: function (toCanvas) {
if (this.imageData != null) {
__SimpleImageUtilities.flush(this.context, this.imageData);
toCanvas.width = this.getWidth();
toCanvas.height = this.getHeight();
toCanvas.getContext('2d').drawImage(this.canvas, 0, 0, toCanvas.width, toCanvas.height);
}
else {
var myself = this;
setTimeout(function() {
myself.drawTo(toCanvas);
}, 100);
}
},
I want to play a video in HTML video element and take snapshot on pause. The snapshot is displayed on the page inside a canvas. Now I want the same snap to appear on another page and for this I am trying to encode the snapshot in base 64 using toDataUrl() method & pass it through URL.
But the maximum length of URL can be 2048 char while the output of toDataUrl is much bigger. How to proceed?
Working fine:
video.addEventListener('pause', function(){
$(this).hide();
$("#canvas1").show();
draw( video, thecanvas, img);
}, false);
function draw(video,thecanvas,img){
var context = thecanvas.getContext('2d');
context.drawImage(video,0,0,thecanvas.width,thecanvas.height);
var dataURL = thecanvas.toDataURL('image/jpeg',.1);
img.setAttribute('src',dataURL);
}
Not working: The function to direct to another page
function toskuentry(){
var imgsrc = $('#thumbnail_img').attr('src');
window.location.href = "sku_entry.php?imgsrc="+imgsrc;
}
Don't pass it through the URL, use HTML5 Web Storage. You can use either sessionStorage or localStorage:
function toskuentry(){
localStorage.setItem("img", $('#thumbnail_img').attr('src'));
}
On the next page you can access it by localStorage.getItem("img");.
One good option would be to use Firebase. They have an example of doing that.
https://www.firebase.com/tutorial/#session/n24v8lvnltc
Firebase uses local storage when offline, so that means you could also use local storage if you didn't want to use Firebase.
something like
localStorage["data"] = dataURL;
//...other page
var dataURL = JSON.parse(localStorage["data"]);
I'm working on a web application that involves loading images into a canvas object, then manipulating those images beyond recognition. I need to hide the original source image file (a jpeg) so that the user on the client side should not be able to use dev tools to see the original image.
I have tried to encode the images as a base64 and load it via a JSON data file, but even with this method, the inspector tool still shows the original image file (when it is set as the src of my javascript image object). Is there some way that I can encrypt and decrypt the image files, so that the user has no way of seeing the original image (or have it be some garbled image, for example)? Preferably I'd like to do this on the client side, as all my code is client side at the moment. Thanks in advance!
Here is my code for loading the base64 encoded image data via a JSON file:
//LOAD JSON INSTEAD?
$.getJSON( "media/masks.json", function( data ) {
console.log("media/masks.json LOADED");
//loop through data
var cnt = 0;
for (var key in data)
{
if (data.hasOwnProperty(key))
{
// here you have access to
//var id = key;
var imgData = data[key];
//create image object from data
var image = new Image();
image.src = imgData;
console.log('img src: '+ imgData);
var elementId = $scope.masks[cnt].id;
// copy the images to canvases
imagecanvas = document.createElement('CANVAS');
imagecanvas.width = image.width;
imagecanvas.height = image.height;
imagecanvas.getContext('2d').drawImage(image,0,0);
imageCanvases[elementId] = imagecanvas;
}
cnt++;
}
});
This is what I see in the Chrome dev tools Network inspector (exactly what I'm trying to avoid):
I need to hide the original source image file (a jpeg) so that the user on the client side should not be able to use dev tools to see the original image.
That's not possible. There is always a way to get at the image using developer tools. Even if there wasn't, a simple screen capture would defeat whatever measures you put in place.
Thought I had this, but no. The goal: snap a photo (insurance card), save it locally, and retrieve it later.
// Get a reference to the image element
var elephant = document.getElementById("SnapIt_mobileimage_5");
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height );
console.log( 'Did that' );
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("data:image/jpg;base64,");
// Save image into localStorage
try {
localStorage.setItem("elephant", imgAsDataURL);
}
catch (e) {
console.log("Storage failed: " + e);
};
//Did it work?
var pic = localStorage.getItem("elephant");
console.log( elephant );
console.log( pic );
Each step succeeds, the final output is:
<img id="SnapIt_mobileimage_5" class=" SnapIt_mobileimage_5" name="mobileimage_5" dsid="mobileimage_5" src="files/views/assets/image/IMG_0590.JPG">
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA
On a new page, when I ask
var policy_shot = localStorage.getItem( 'elephant' );
console.log( policy_shot );
$('#TestScreen_mobileimage_1').src = policy_shot ;
It logs the binary:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUg ....
But the image doesn't appear.
Is there a simpler approach?
Why is the getItem (binary) preceded by data:image/png; instead of data:image/jpg ?
Is that why it doesn't display, or am I doing something else wrong?
1) This is the only way you can convert an image into a string locally (with the excpetion of files loaded with FileReader, see below). Optionally you need to use the server to do it.
2) To get a JPEG image you need to use the argument like this:
var datauri = imgCanvas.toDataURL("image/jpeg", 0.5); //0.5 = optional quality
don't use data:... in the argument as that will be invalid and it will produce the default PNG as you can see in your result. toDataURL() can only take a type, ie. image/png, image/jpeg etc.
3)
External files
If your image was loaded from a different origin (scheme, server ...) or by using local referenced files (file://, /my/path/ etc.) CORS kicks in and will prevent you from creating a data-uri, that is: the image will be empty (and therefor invisible).
For external servers you can request permission to use the image from a cross-origin by supplying the crossOrigin property:
<img src="http://extrernalserver/...." crossOrigin="anonymous" />
or by code (img.crossOrigin = 'anonymous';) before setting the src.
It's however up to the server to allow or deny the request.
If it still doesn't work you will need to load your image through a proxy (f.ex. a page on your server that can load and the image externally and serve it from your own server).
Or if you have access to the server's configuration you can add special access allow headers (Access-Control-Allow-Origin: *, see link below for more details).
CORS (Cross-Origin Resource Sharing) is a security mechanism and can't be worked around other than these ways.
Local files
For local files you will need to use FileReader - this can turn out to be an advantage as FileReader comes with a handy method: readAsDataURL(). This allow you to "upload" the image file directly as a data-uri without going by canvas.
See examples here:
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
Unfortunately you can't just pick the files from code - you will need to provide an input element or a drop zone so the user can pick the files (s)he want to store.
Conclusion
If all these steps are fulfilled to the degree that you actually do get an image the problem possibly is in the other end, the string being truncated being too long to store.
You can verify by checking the length before and after storing the string to see if it has been cut:
console.log(imgAsDataURL.length);
... set / get ...
console.log(pic.length);
Other possibilities:
The image element is not properly defined.
A bug in the browser
A bug in the framework
(I think I covered most of the typical pitfalls?)
Update (missed one, sort of.. ;-p)
OP found a specific in the framework which I'll include here for future reference:
In the end, the issue was with $('#TestScreen_mobileimage_1').src =
policy_shot ; I'm using Appery.io and they don't support .src.
It's $('#TestScreen_mobileimage_1').attr("src", policy_shot ) ;
A final note: localStorage is very limited in regards to storing images. Typical storage space is 2.5 - 5 mb. Each char stored takes 2 bytes and storing a data-uri encoded as base-64 is 33% larger than the original - so space will be scarce. Look into Indexed DB, Web SQL or File API for good alternatives.
Here the complete solution using File Api
<html>
<body>
<input type="file" id="image-input" />
<img id="image-container" />
<script type="text/javascript">
(function(){
/** #type {Node} */
var imgInput = document.getElementById( "image-input" ),
/** #type {Node} */
imgContainer = document.getElementById( "image-container" ),
/** Restore image src from local storage */
updateUi = function() {
imgContainer.src = window.localStorage.getItem( "image-base64" );
},
/** Register event listeners */
bindUi = function(){
imgInput.addEventListener( "change", function(){
if ( this.files.length ) {
var reader = new FileReader();
reader.onload = function( e ){
window.localStorage.setItem( "image-base64", e.target.result );
updateUi();
};
reader.readAsDataURL( this.files[ 0 ] );
}
}, false );
};
updateUi();
bindUi();
}());
</script>
</body>
</html>