Data URI alternative - javascript

My web app does not work well with long data URI that I use to display images. When the encoded data is shown within a text areas It gets unbelievably slow. Sometimes the entire page crashes when I click the download page button on my app if the data URI is somewhere in the DOM.
Is there an alternative to data URI? The user submits an image file from their computer and the data URI code is used like this to display the image <img src="dataURI"/>. This is not a server-based application so server-side languages aren't an option.
I have looked into JavaScript BLOB, although I have no idea how to work with that.

Edit, Updated
Try (v3)
html
<input id="change-image-input" type="file" accepts="image/*" />
<img src="BLOB HERE" alt="test" class="identify-selected-option-image"/>
<div></div>
js
var input = document.getElementById("change-image-input")
, div = document.querySelectorAll("div")[0]
, img = document.getElementsByClassName("identify-selected-option-image")[0];
input.addEventListener("change", function(e) {
var file = e.target.files[0];
var url = window.URL.createObjectURL(file);
img.onload = function() {
div.style.backgroundImage = "url('" + url + "')";
div.style.width = img.width + "px";
div.style.height = img.height + "px";
}
img.src = url;
});
var input = document.getElementById("change-image-input")
, div = document.querySelectorAll("div")[0]
, img = document.getElementsByClassName("identify-selected-option-image")[0];
input.addEventListener("change", function(e) {
var file = e.target.files[0];
var url = window.URL.createObjectURL(file);
img.onload = function() {
div.style.backgroundImage = "url('" + url + "')";
div.style.width = img.width + "px";
div.style.height = img.height + "px";
}
img.src = url;
});
<input id="change-image-input" type="file" accepts="image/*" />
<img src="BLOB HERE" alt="test" class="identify-selected-option-image"/>
<div></div>

You can create an Image from File or Blob using URL.createObjectURL, which can then be set as img src, painted on canvas, or set as target of download link.
Example HTML:
<!DOCTYPE html>
<input type="file" onchange="update()" />
<a download><img alt="Please select a photo" /></a>
And JavaScript:
function update() {
var a = document.querySelector( 'a' );
var f = document.querySelector( 'input' ).files;
var url = window.URL || window.webkitURL;
if ( ! f || ! f.length ) return;
a.href = document.querySelector( 'img' ).src = url.createObjectURL( f[0] );
}
The image displays on IE 11, Chrome 39, Firefox 33.
The download link works in Chrome and Firefox, but is not supported in IE <=11.
IE users will have to manually right click to save image.

Related

How I can change this deprecated code document.write for improve pagespeed

I would like to improve a code that I have in the sidebar of wordpress, where what I want is that every time people enter randomly loads an image. At the moment with the code I have shown below it works, but when I put my page in google speed it says this:
Avoid use: document.write()
link = new Array();
link[0] = '<img src="" width="300" height="408"/>';
link[1] = '<img src="" width="300" height="408"/>';
link[2] = '<img src="" width="300" height="408"/>';
link[3] = '<img src="" width="300" height="408"/>';
random = Math.random() * (link.length);
random = Math.floor(random);
document.write(link[random]);
<div id="bloquewidget"></div>
There doesn't look to be any need for the array or randomness since the link HTMLs are all the same. Create an <a> with createElement, then use a CSS selector to insert it into the document at the appropriate point. You'll need some way to uniquely identify this <div> - use a class if it already has one, or give the div a class, such as link-container:
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener nofollow';
// do you want to add a non-empty src to the a here?
const img = a.appendChild(document.createElement('img'));
img.width = 300;
img.height = 408;
// do you want to add a non-empty src to the image here?
// insert <a> at the bottom of this div:
document.querySelector('.link-container').appendChild(a);
the
document.write(link[random]);
part can be replaced with:
document.body.innerHTML = document.body.innerHTML + link[random];
It is also worth looking into createElement for creating DOM objects like anchors.
Well I found another solution to my problem I leave the code here in case anyone else needs to put in a wordpress a widget with images that are randomly generated with their own link and not using the deprecated code document.write
<div id="bloquewidget">
<a id="a" rel="nofollow noopener noreferrer" target="_blank"><img id="image" /></a>
<script type='text/javascript'>
var images =
[
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
]
function randImg() {
var size = images.length;
var x = Math.floor(size * Math.random());
var randomItem = images[x];
document.getElementById('image').src = randomItem.ImgSrc;
document.getElementById('a').href = randomItem.Href;
document.getElementById("image").height = "408";
document.getElementById("image").width = "300";
}
randImg();
</script>

How to display dynamic url image in html from which created by javascript

I am trying to display the image directly in HTML through a dynamic link I generated by Javascript.
function dynamicUrl() {
var url = "http://xxx.xxx.xxx" + dynamic_variables + ".jpg";
return url;}
Most of my research, people display image by click on buttons
or what I can do for now is link to the image.
test
Anyone know how to directly display the image using the dynamic URL?
Thanks!
Dynamic create DOM for example:
function dynamicUrl() {
var url = "https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg";
return url;
}
var img = document.createElement("img");
img.src = dynamicUrl();
document.body.appendChild(img);
Manipulate DOM to dynamic change img url:
function dynamicUrl() {
var url = "https://www.62icon.com/client/assets/img/like-icon.svg";
var img = document.getElementById('imageid');
img.src = url;
}
<div>
<p>Image goes here</p>
<button onclick="dynamicUrl()">Change Image</button>
</div>
<img id="imageid" src="https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg" />
Adding a id for the link element
<a id="link" href="">test</a>
Using click event of link element
var link = document.getElementById("link");
link.onclick = function goToDynamicUrl() {
var url = "https://image.flaticon.com/teams/new/1-freepik.jpg";
window.location.href = url;
}
Here is another method:
<div id="dimg">Here add image</div>
<script>
var dimg = document.getElementById('dimg');
function addImg(dv){
dimg.innerHTML ='<img src="http://xxx.xxx.xxx'+ dv +'.jpg'" >';
}
addImg('imgname');
</script>

control height and width client side with javascript

this is my form
<form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp">
<input type="file" name="pho" id="photo" class="inph" accept="image/*">
<button type="submit" id="subFormPhoto" class="spp">press here</button>
</form>
and this is my code JS
<script type="text/javascript">
var inputPhoto= document.getElementById('photo');
inputPhoto.onchange=function(){var photo= this.value; photo.onload=function(){alert(this.width+' '+this.height);};};
</script>
my problem is that not visualize alert(this.width+' '+this.height);.
as if not load photo
this.value gives the file name as a string, so your photo.onload function isn't really looking at the photo but just some string. If you alert or console.log photo you will see what I mean.
You may wish to consider the File API, it will work with modern browsers as from HTML 5.
Here's a working example of your code:
var inputPhoto = document.getElementById('photo');
inputPhoto.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
var photo = new Image();
reader.readAsDataURL(file);
reader.onload = function(_file) {
photo.src = _file.target.result;
photo.onload = function() {
alert(this.width + ' ' + this.height);
};
};
};
I have tried to create what I understood from your question
http://jsfiddle.net/qo8ovmhn/
<input type="file" name="pho" id="photo" class="inph" onchange="myFunction()">
<img id="view" src=""></img>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("photo");
var file = x.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(_file) {
var img = document.getElementById("view");
img.setAttribute("src",_file.target.result);
var height = img.offsetHeight;
var width = img.offsetWidth;
alert(width + " X " + height);
};
}
</script>
see if this is what you were looking for.
The change event of the input is called on choosing an image. The image bytes are read and put in an image tag. Then the dimensions of the image are fetched from the height and width of the image component.
You can hide the image by adding a css style of visibility:hidden or opacity:0
Do not give display:none as this will result in height and width of 0px
Finally the dimensions are shown in an alert.

getElementById() is null?

So I am trying to make a JavaScript program that will take a URL for an image and then put it onto the page while creating an <img> tag so that I can just continue pasting as many photos as I want. Here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Low-Budget Online Album</title>
<meta charset="utf-8">
<script>
function init() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
window.onload = init;
function buttonClick() {
var imageSource = document.getElementById("imageInput").value;
if (imageSource == "") {
alert("Please enter the source for an image.");
}
else {
var newImage = document.createElement("img");
var newSrc = document.getElementById("newImage").src= imageSource;
imageInput.value = "";
}
}
</script>
</head>
<body>
<input type="text" id="imageInput" size="40" placeholder="Image Source">
<input type="button" id="addButton" value="Add Image">
<img id="images" src="">
</img>
</body>
</html>
My problem is, is that when I put int a URL (or picture src from my PC) it says that TypeError: document.getElementById(...) is null, and points to line 20, being my
var newSrc = document.getElementById("newImage").src= imageSource;
line. Any ideas?
Use this
else {
var newImage = document.createElement("img"); //this line creates element <img> element in the dom.
newImage.setAttribute("id", "newImage");
newImage.src= imageSource;
document.body.appendChild(newImage);//adds element <img src="a.jpg" id='newImage'>to the dom.
imageInput.value = "";
}
Understand what mistake you have done above:
1.First you created element and assign to a variable newImage
var newImage=document.createElement("img");
2.You are calling
document.getElementById('newImage');
Here newImage as element that you created and in the dom there is no element with id as newImage so you were getting null.
do you mean something like this:
function init() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
window.onload = init;
function buttonClick() {
var imageSource = document.getElementById("imageInput").value;
if (imageSource == "") {
alert("Please enter the source for an image.");
}
else {
var newImage = document.createElement("img");
newImage.src= imageSource;
newImage.setAttribute("id", "newImage");
imageInput.value = "";
document.body.appendChild(newImage);
}
}
Demo:: jsFiddle
var newImage = document.createElement("img");
var newSrc = document.getElementById("newImage").src= imageSource;
Become:
var newImage = document.createElement("img");
newImage.setAttribute('id','newImage');
var newSrc = document.getElementById("newImage").src = imageSource;
in mdn you can see that createElement only create element and not add it to DOM. So if you want add created element you need change your code like this
var newImage = document.createElement("img");
newImage.id = "newImage";
document.body.appendChild(newImage);
after this line will work
var newSrc = document.getElementById("newImage").src= imageSource;
but you don't need get find it if you already have this image in newImage variable, so this line you can change like
var newSrc = newImage.src= imageSource;
UPDATE
Possibly you need use className instead of id because id should be unique on page, but as i understand you want add many images

Passing image data to another page

I'm trying to access a camera and a photo album on a mobile device and get the chosen image. I did that with the code below. My problem is, it generates image data, and I have to transfer that to another page, but because of the size of the generated string, I can't use URL parameters. It shows me the error: [404] Request-URI Too long. How can I pass the information to the other page?
Here is the code: http://jsfiddle.net/8u426/
The JS:
<script>
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
document.getElementById("fotoImg").src = oFREvent.target.result;
document.getElementById("fotoImg").style.visibility = "visible";
var screenHeight = screen.availHeight;
screenHeight = screenHeight - 220;
document.getElementById("fotoImg").style.height = screenHeight;
document.getElementById("stringImg").innerText = "Data Image: " + oFREvent.target.result;
};
$(function() {
$("input:file").change(function (){
var input = document.querySelector('input[type=file]');
var oFile = input.files[0];
oFReader.readAsDataURL(oFile);
});
});
</script>
Update:
The problem is: if I try to open a new page passing the Data Image string as a parameter in the URL (with "?"). The new page will show the 404 error that I mentioned, because the string is too long.
Try changing your form to
<form id="form1" method="POST" action="[Page2 URL]">
<input id="filePic" type="file" name="image" accept="image/*" capture />
</form>
where [Page2 URL] is the URL for page to receive the image uploaded.
And JavaScript to
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
var screenHeight = screen.availHeight;
screenHeight = screenHeight - 220;
var img = $('#fotoImg');
img.attr('src', oFREvent.target.result);
img.css( { height : screenHeight, visibility: 'visible' });
$("#stringImg").text( "Data Image: " + oFREvent.target.result);
$('#form1').submit();
};
$(function() {
$("input:file").change(function (){
var oFile = this.files[0];
oFReader.readAsDataURL(oFile);
});
});
I couldn't make work with php (considering that I didn't want to work with php) and html forms (methods get and post)... So I used the jQuery library called "jQuery Storage".
It was easy, on the page that I select the image you shoud use:
$.sessionStorage([key],[value]);
So, was like that:
$.sessionStorage('chosenImg', document.getElementById("photoImg").src);
And in the new page, to get the value, just add in the code:
$.sessionStorage('chosenImg');
Of course, I had to download de .js library from the website and add the line below on both html pages:
<script src="jquery.storage.js"></script>
The only inconvenient it is a little heavy for mobile, but was the only way I found...
That is it! Thanks everyone!
dataimage base64 data image

Categories