I'd like to know if there is any way so that I can display a multi-paged tif image in browser using client-side coding (not server-side) in a way that user can navigate between the pages like common jquery photo libraries. I found Tiff.js from https://github.com/seikichi/tiff.js, but this library only gives download link of multi-paged tiff and do not display it in html.
I can do it in server-side using libraries like ImageMagic, LibTiff.Net etc but don't want to because the number of photos are huge and if I do that it consume the large amount of server's cpu
do you know any alternative solution??
I had this problem too and converting the images was not an option for us.
You can use tiff.js that you linked to, have a look at the demo and then view source at http://seikichi.github.io/tiff.js/multipage.html.
$(function () {
Tiff.initialize({TOTAL_MEMORY: 16777216 * 10});
var xhr = new XMLHttpRequest();
xhr.open('GET', 'images/multipage.tiff');
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
var buffer = xhr.response;
var tiff = new Tiff({buffer: buffer});
for (var i = 0, len = tiff.countDirectory(); i < len; ++i) {
tiff.setDirectory(i);
var canvas = tiff.toCanvas();
$('body').append(canvas);
}
};
xhr.send();
});
Replace 'images/multipage.tiff' with the path to your file and it will add each page to the body element (just replace $('body') with your element if you want it somewhere else). Works with single tiff as well.
Browsers won't support tif images.
check this Wiki Link.
You have to generate a png image and store it and show that in browser for the tif.
Related
I've got a FileReader that lets the user upload a file (image) to my site.
Here's the code that does the reading:
$("input[type='file']").change(function(e) {
var buttonClicked = $(this);
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
console.log(reader.result);
}
reader.readAsDataURL(file);
}
});
All is good and well, until I tried to print out my result. I used this file for example:
When I console.log() the result, it spits out over 95000 characters.
This image in particular is around the same size as the images I will be accepting into my site.
I was hoping to store these images in a database as well, and so I'm wondering how this is going to be possible with image sources that are so extremely long. Is there a way to shorten this or get the image path a different way?
I'm moreso curious as to why they're so long, but if someone has a tip to store these (100s per user, 500+ users) that'd be nice as well!
Thanks-
Store the Files as ... Files.
There are very little use cases where you need the toDataURL() method of the FileReader, so every time you use it, you should ask yourself why you need it.
In your case :
To display the image in the page. Well don't use a FileReader for this, instead create a direct pointer to the file in the form of an url, available only to this session. This can be achieved with the URL.createObjectURL(File_orBlob) method.
To store this image on your server. Don't store a ~37% bigger base64 version, send and store directly the file as a file (multipart). This can be achieved easily with the FormData API.
inp.onchange = function(){
var file = this.files[0];
if(file.type.indexOf('image/') !== 0){
console.warn('not an image');
}
var img = new Image();
img.src = URL.createObjectURL(file);
// this is not needed in this case but still a good habit
img.onload = function(){
URL.revokeObjectURL(this.src);
};
document.body.appendChild(img);
}
// not active but to give you da codez
function sendToServer(){
var file = inp.files[0];
var form = new FormData();
// here 'image' is the parameter name where you'll retrieve the file from in the request
form.append('image', file);
form.append('otherInfo', 'some other infos');
var xhr = new XMLHttpRequest();
xhr.open('post', 'yourServer/uploadPage')
xhr.onload = function(){
console.log('saved');
};
xhr.send(form);
}
<input type="file" id="inp">
And if you need PHP code to retrieve the File form this request :
if ( isset( $_FILES["image"] ) ){
$dir = 'some/dir/';
$blob = file_get_contents($_FILES["image"]['tmp_name']);
file_put_contents($dir.$_FILES["image"]["name"], $blob);
}
You're going to want to upload the files to a server of some sort (a backend that is serving up your javascript), and then from there you'll want to
Validate the file
Store the file on a physical server (or the cloud) somewhere
Add an entry in a database that relates the file path or ID of that upload to the user who just uploaded it (so you can retrieve it later if needed)
So basically, you don't store the image in your database, you store it on a file share/cloud host somewhere, and instead you only store what is needed to download/retrieve the image later.
is it possible to load an image directly into a canvas control using a generic handler without using the image element?
This is my handler:
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.ContentType = "image/jpeg";
var camIndex = Convert.ToInt16(context.Request.QueryString["camIndex"]);
context.Response.BinaryWrite( Shared.Feeder[camIndex].JpegData);
}
My JavaScript:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1/Media/FrameHandler.ashx?camIndex=' + camIndex, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
var uInt8Array = new Uint8ClampedArray(this.response);
imageData[camIndex].data.set(uInt8Array);
ctxLiveViews[camIndex].putImageData(imageData[camIndex], 0, 0);
};
xhr.send();
which gives me this image (which is obviously wrong)
Is it possible to load an image directly into a canvas control using a generic handler without using the image element?
It is, but you are in for a hand-full as you will need to manually parse the image file format yourselves (with all the various combinations of image format, color model etc. and error checks and so forth). It's doable (been there done that), but chances are, unless you need to access some special data or bitmap formats, that the browser will do the job at least faster than a manual approach in JavaScript.
Using an Image element is easy and does all these steps for you in compiled code.
This line:
var uInt8Array = new Uint8ClampedArray(this.response);
will only hold the original file bytes, uncompressed, undecoded including header, chunks and metadata. While putImageData() require a raw bitmap in the format RGBA per pixel. This is why you see the noise as the data being fed to putImageData is the file itself, not a bitmap.
Quite simply, is there anyway to detect what file type a source file is?
Context:I have an HTML5 audio element and depending on what button someone clicks I want to randomly change the source of that audio element using JavaScript (please, no jQuery solutions) so that different songs will play. I have several hundred sound files, so I really don't want to have to convert them all to one file type.
I currently have a method that gets a random but always correct file name via a RNG but no way of knowing the file extension this file is (it could be .ogg, .wav, .m4a or .mp3). It just tries every possible extension until one works but am having a bit of trouble with the error handling which is causing other issues to occur so it would be really great if you could help me out here with a better solution. Thanks!
// fileInput is an HTML input element: <input type="file" id="myfileinput" multiple>
var fileInput = document.getElementById("myfileinput");
// files is a FileList object (similar to NodeList)
var files = fileInput.files;
var file;
// loop trough files
for (var i = 0; i < files.length; i++) {
// get item
file = files.item(i);
//or
file = files[i];
alert(file.type);
}
developer.mozilla link
You can use a mixture of the new XMLHttpRequest Level 2 API and File API to check the file type of a server resource.
For example, to get the type of an image:
url = '/favicon.ico';
xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var file = this.response;
alert(file.type);
}
};
xhr.send();
JSFIDDLE demo
I need to calculate the total length of an mp3 file.
Currently I am using a PHP class which I found # http://www.zedwood.com/article/php-calculate-duration-of-mp3.
This is working perfectly if the mp3 file in same server.
but if I have a URL from other site it throwing error. Please help me.
Is there any JavaScript J-Query function to get the length of the mp3 file
<?php include("mp3.class.php");
$f = 'http://cdn.enjoypur.vc/upload_file/5570/5738/5739/7924/Blue%20Eyes%20-%20Yo%20Yo%20Honey%20Singh%20(PagalWorld.com)%20-192Kbps%20.mp3';
$m = new mp3file($f);
$a = $m->get_metadata();
if ($a['Encoding']=='Unknown')
echo "?";
else if ($a['Encoding']=='VBR')
print_r($a);
else if ($a['Encoding']=='CBR')
print_r($a);
unset($a);
?>
Here's how you can get mp3 duration using Web Audio API:
const mp3file = 'https://raw.githubusercontent.com/prof3ssorSt3v3/media-sample-files/master/doorbell.mp3'
const audioContext = new (window.AudioContext || window.webkitAudioContext)()
const request = new XMLHttpRequest()
request.open('GET', mp3file, true)
request.responseType = 'arraybuffer'
request.onload = function() {
audioContext.decodeAudioData(request.response,
function(buffer) {
let duration = buffer.duration
console.log(duration)
document.write(duration)
}
)
}
request.send()
There is actually a library that can run at client-side, attempting to fetch just enough of the MP3 to read the ID3 tags:
http://github.com/aadsm/JavaScript-ID3-Reader
or
Try
HTML File API.
http://lostechies.com/derickbailey/2013/09/23/getting-audio-file-information-with-htmls-file-api-and-audio-element/
Perhaps the simplest solution is to use the audio html element to get the time duration and to obtain the size directly from the file returned by the FileReader object. A code example of this approach is shown below.
One down side of this and all the other solutions presented so far is the 10-20 second delay it takes for the audio tag's durationchanged event to fire when loading large, eg > 200MB files. Clearly there is a faster way to get this info because the duration is shown immediately when the file is entered into the browser as a file:///.... URL.
function checkMp3SizeAndDuration()
{
var files = document.getElementById('upload-file').files;
var file = files[0];
if (file.size > MAX_FILE_SIZE) {
return;
}
var reader = new FileReader();
var audio = document.createElement('audio');
reader.onload = function (e) {
audio.src = e.target.result
audio.addEventListener('durationchange', function() {
console.log("durationchange: " + audio.duration);
},false);
audio.addEventListener('onerror', function() {
alert("Cannot get duration of this file.");
}, false);
};
reader.readAsDataURL(file);
});
Having not been able to find something that was fast and didn't require a bunch of extra boilerplate code, I tweaked an existing server side javascript utility to run directly in the browser. Demo code is available at: https://github.com/eric-gilbertson/fast-mp3-duration
A Famous and Very SPI that you can use MP3 SPI
and the code is also very simple
File file = new File("filename.mp3");
AudioFileFormat baseFileFormat = AudioSystem.getAudioFileFormat(file);
Map properties = baseFileFormat.properties();
Long duration = (Long) properties.get("duration");
Use getID3() PHP library that works for VBR files as well.
This link help you sourceforge.net.
It's very much active in development.
We are using the Eclipse SWT WebBrowser control to render HTML pages for our Java application. If the page contains an image, we want to get the image content. We can access the DOM to get the IMG element, but there doesn't seem to be a way to get the actual content (i.e. the bytes of the image) other than re-fetching the image using the image URL. (We can get the image URL via the 'src' attribute.) Is there any way to get the actual bytes of the image from the DOM?
I am not sure if this is what you are looking for, but basically you can just make a typed XHR (such as ArrayBuffer) to the image source (it should be cached, so no real hit by doing this). I am assume you are using an HTML5 compliant browser (or such that supports ArrayBuffer or the type you need). I am assuming the document has at least one image with a proper source, see Fiddle for working demo.
var img = document.querySelector('img'), xhr = new XMLHttpRequest();
xhr.open('GET', img.src, true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', handleBuffer, false);
xhr.send();
// Your image data ArrayBuffer, feel free to change the type.
function handleBuffer (data) {
var arryBuffer = data.target.response;
}
Sample Fiddle
Check out https://developer.mozilla.org/en-US/docs/Web/API/FileReader it will let you create base64 data urls, may not work depending on your browser versions.