i am using localstorage html5. first i am saving mysql db values into localstorage then i am fetching where i want.its fine. i want to save images (like images of products) into localstorage and then want to show them where i want,
i did an experiment as I saved images in blob in mysql, and i am able to fetch and show them using php but i dont want to use php here,the purpose is of offline working.i am unable to show image via javascript
any one can help me??
There might be two ways,
one is can we encript image (i have to path to image)in some sort of string in javascript and then can i show that on anywhere.
Second way..
as i said i saved it in blob can i use javascript to just show image from blob. by the way i can fectch value from database easily.now the only thing is to save that value into javascript and show its image where i want.
I will wait for reply thank you:)
You can also use URL.createObjectURL(blob) specified here and for cross-browser compatibility, check this out:
var uri = URL.createObjectURL(blob);
var img = new Image();
img.src = uri;
document.body.appendChild(img);
You can use a Data URI scheme for the images:
<img src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />
This requires you to encode the data and there is a limit to the size in some browsers (32kb in IE, for example).
Related
I have a site that displays a lot of external images and thumbnails etc, easily up to 100 on a single page. I crawl and index the urls to the images and save them in mysql and display them with this code inside simple loops from queries.
<img src="<?php echo $row['img_url']; ?>" onerror="this.onerror=null;this.src='http://example.com/image.jpg';" width="150" height="150">
I use that particular code to replace any broken image urls with a default image.
My question is, is it possible to use javascripts onerror or something else to capture the image url that is broken when a broken url is found so that I can pass the url back to php and be able to automatically delete the urls from my database?
I am not very good with javascript and after searching I can't seem to find anything similar to what I am looking for, I mostly just find lots of posts on how to replace the broken image.
I am open to any ideas really, the original image urls come from $row['img_url'] as you can see in the code but I know I need javascript or something to catch the errors and then somehow get the urls passed back to php so that I can automate the deletion process instead of just replacing images with default images like my currnt code.
you can use file_exists to check like so:
if(file_exists($row['img_url'])){
echo '<img src="'.$row['img_url'].'" onerror="this.onerror=null;this.src="http://example.com/image.jpg";" width="150" height="150">';
}
You are almost there. Simply replace this:
this.src='http://example.com/image.jpg'
with:
this.src='http://example.com/image-missing.php?url={$row['primaryKey']}&w=150&h=150'
Now, "image-missing.php" receives the URL of the missing file and the intended size of the missing image. What it needs to do is clean the database (after checking that the call is legitimate (1) and that the referred row exists(2)), and output a replacement image in the proper size.
(1) otherwise you have just handed the possibility of deleting your whole image database to the first guy with time on his hands.
(2) someone else might have loaded the same page, and called the same script one millisecond ago.
You should try something like this (example uses vanilla JS, no jquery or any 3rd party library):
var allImages = document.querySelectorAll('img');
for (var i = 0; i < deleteLink.length; i++) {
document.querySelector('img').addEventListener('error', function(e) {
// Delete a user
var url = "<DELETION_URL>";
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url+'?resource=' + e.target.src, true);
});
}
<DELETION-URL> should point to a PHP script that accepts DELETE (or at least POST) requests and read the resource parameter. It will then remove the image provided that resource is truly missing.
I have a file upload that saves images as .png on the server and the link in a mysql database. To show thumbnails of the image before uploading I have a function that convertes the file list object to a preview pic. Now I want the user to edit the file selection later. For that I need to load the images from the server back as thumbnails. I think the best way to do this is to convert the file path stored in the database to a file object and apply this object to the function that creates the thumbnails that I don't need to rewrite this function.
So my question is how can I convert my stored image links to a file list object?
Edit:
upload:
user selection -> file object -> base 64 -> blob -> display blob -> (maybe) edit -> upload selection as base 64 to server -> base 64 to .png -> save pic -> save link
later edit selection by user(how to do?):
saved link -> file object -> base 64 -> blob -> display blob -> (maybe) edit -> ...
saved link -> file object How to do? Possible? Better way?
I hope it's now clearer to understand.
If someone has an idea how to do this or a better way please answer.
(I know that you should show Code when asking a question but I don't think that it is necesarry to upload the whole upload function here)
You process is all frowned, so I may not answer correctly your question, but I'm pretty sure this is an X-Y problem.
Javascript File objects inherit from the Blob object.
From MDN :
A File object is a specific kind of a Blob, and can be used in any context that a Blob can.
Never convert a File to a base64 dataURL, if it's to convert it back to a Blob ; this makes no sense and only pollute the browser's memory.
To display a Blob (or a File) in the browser, from media elements, or iframes, use the URL.createObjectURL(blob) method. This will return a blobURI, that will be available only for the life time of the initiating page, and only for the user's browsers. In case of user uploaded Files, the file is not even copied to memory, and the uri returned is just a direct pointer to the file on the user's system.
inp.onchange = function(){
var url = URL.createObjectURL(this.files[0]);
var img = new Image();
img.onload = function(){
document.body.appendChild(this);
}
img.onerror = function(){
console.log('probably not a supported image file');
}
img.src = url;
}
<input id="inp" type="file" accept="image/*">
If you need to modify the image, you can do so by drawing the resulting image on a canvas.
Then, instead of exporting your canvas to a dataURI, directly use the toBlob method, which can be polyfilled.
To send you File/Blob on your server, send the File/Blob directly instead of its 30% heavier base64 string representation.
This can be done really easily thanks to the FormData API.
var xhr = new XMLHttpRequest();
xhr.onload = done;
var formData = new FormData();
formData.append('file', theFile, fileName);
xhr.open('POST', yourServer);
xhr.send(formData);
Then you can retrieve it server side just like any File uploaded through the basic Multipart/Form method.
I created a coupon-creator system that uses HTML 5 canvas to spit out a jpg version of the coupon you create and since I'm not hosting the finalized jpg on a server, I am having trouble retrieving the URL. On some browsers when I drag the image into the address bar all I get is "data:" in the address bar. But on windows, if I drag it into an input field, sometimes it spits out the huge (>200 char) local-temp url. How can I use javascript(?) to find that exact temporary URL of the image generated by my coupon creator and be able to post it on an input form on the same page? Also, it'd be very helpful if you guys know the answer to this as well, as I assume it is correlated with the retrieval of the URL: When I click the link that says "Save it" after it's generated, how can I have it save the created image to the user's computer? Thanks a lot!
This is what I'm using in JS right now to generate the image:
function letsDo() {
html2canvas([document.getElementById('coupon')], {
onrendered: function (canvas) {
document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/jpeg');
// AJAX call to send `data` to a PHP file that creates an image from the dataURI string and saves it to a directory on the server
var mycustomcoupon = new Image();
mycustomcoupon.src = data;
//Display the final product under this ID
document.getElementById('your_coupon').appendChild(mycustomcoupon);
document.getElementById('your_coupon_txt').style.display="block";
}
});
}
Here is the live URL of the creator: http://isleybear.com/coupon/
I ended up dumping this code into the js stated above. It was a pretty simple fix. Then to test it, I set an onclick html element to show the source.
var mycustomcoupon = document.getElementById('your_coupon');
mycustomcoupon.src = data;
}
});
}
function showSource(){
var source = document.getElementById('your_coupon').src;
alert(source);
}
I'm trying to render MJpeg stream in HTML5 using the img tag.
When I'm running the following, everything works great, meaning, the video starts to play until the video ends:
<img src="http://[some ip]:[port]/mjpg">
My question is how can I get the stream frame by frame.
For each frame, I want to get it, do something (ajax call to the server) and then display the frame as an image.
Thanks.
You can do this without repeatedly making Http requests. Only one will suffice. You can use the fetch api to create a ReadableStream, access it's Reader and keep reading from the stream.
Once you have the reader keep reading chunks from the stream recursively. Look for the SOI ( 0xFF 0xD8) in the byte stream which signals the end of the header and the beginning of the JPEG frame. The header will contain the length of the JPEG in bytes to be read. Read that many bytes from the chunk and any successive chunks and store it into a Uint8Array. Once you've
successfully read the frame convert it into a blob, create a UrlObject out of it and assign it to the src property of your img object.
Keep doing this till the connection is closed.
Shameless plug. Here's a link to a working sample on github.
If the camera exposes raw JPEG images (not .MJPEG extension) you'll have to reaload it manually (if the extension is .MJPEG the browser will do everything, just put the correct src). If you have .MJPEG and want to use the raw .JPEG check your camera documentation. Most cameras expose both the .MJPEG and raw .JPEG streams (just on different URLs).
Unfortunately you won't be able to easily get the image through ajax, but you could change the src of the image periodically.
You can use Date.getTime() and add it to the querystring to force the browser to reload the image, and repeat each time the image loads.
If you use jQuery the code will look something like this:
camera.html
<!DOCTYPE html>
<html>
<head>
<title>ipCam</title>
</head>
<body>
<h1>ipCam</h1>
<img id="motionjpeg" src="http://user:pass#127.0.0.1:8080/" />
<script src="motionjpeg.js"></script>
<script>
//Using jQuery for simplicity
$(document).ready(function() {
motionjpeg("#motionjpeg"); // Use the function on the image
});
</script>
</body>
</html>
motionjpeg.js
function motionjpeg(id) {
var image = $(id), src;
if (!image.length) return;
src = image.attr("src");
if (src.indexOf("?") < 0) {
image.attr("src", src + "?"); // must have querystring
}
image.on("load", function() {
// this cause the load event to be called "recursively"
this.src = this.src.replace(/\?[^\n]*$/, "?") +
(new Date()).getTime(); // 'this' refers to the image
});
}
Note that my example will play the MotionJPEG on page load, but won't allow play/pause/stop functionalities
If you stream source can't return frames on another address (http://[some ip]:[port]/frame/XXX) then you can use MJPEG stream parser on the server. For example, Paparazzo.js parse stream and return single jpeg. Actually it returns only last frame without saving previous, but it can be changed.
Problem can't be solved only in browser with js without some plugins and server.
I have image data (either JPEG or PNG) in a Javascript variable. How do I display the image in an HTML document? These are very large images and code like this doesn't work because the URI is too long:
// doesn't work because the URI is too long
$('img#target').attr('src', 'data:...');
Using canvas is probably the answer but I cannot figure out how to load it with the image data.
In case you are wondering: no, I cannot just download the image data directly to the img tag. It came from the server encrypted and was decrypted within the browser using Javascript.
Thanks,
-- Art Z.
To use a data URL to draw on a canvas:
var img = new Image;
img.onload = function(){
myCanvasContext.drawImage(img,0,0);
};
img.src = "data:...";
Per this question/answer be sure that you set the onload before the src.
You say that "the URI is too long", but it is not clear what you mean by this. Only IE8 has a 32kB limit on the data URI; for other browsers it should work fine. If you are experiencing an error, please describe it.
It turns out that
$('img#target').attr('src', 'data:...');
does work in all except IE. My problem originated elsewhere.