Load TIF/TIFF in HTML5 canvas and avoid download - javascript

I want to show tiff/tif images inside an HTML5 canvas. Following this doc I´ve accomplished to do it with uploaded images but when I need to dynamically reference external images by URL the browser always force the download.
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.open('GET', "url/of/a/tiff/image/file.tiff");
xhr.onload = function (e) {
var tiff = new Tiff({buffer: xhr.response});
var canvas = tiff.toCanvas();
document.body.append(canvas);
};
xhr.send();
At the begining I had CORS issues but I solved that problem, now the uploaded images are display correctly but URL are not.
How can I do this for both cases uploaded images and URL
Thanks in advance!
UPDATE!
Working on later I noticed that when load .tiff files there is no problem. The download is forced when is a .tif file. Are these mime types differents?

Related

How can I download a video given its URL in JavaScript?

I have a URL, for example this:
https://r6---sn-vgqsrn76.googlevideo.com/videoplayback?expire=1566535969&ei=wRxfXezPAoORV-3ogpgK&ip=185.27.134.50&id=o-ALFdSvuvmX_bqDsm4oRW7q9c4igbKlBmECWdISuA4Jxe&itag=22&source=youtube&requiressl=yes&mime=video%2Fmp4&ratebypass=yes&dur=624.175&lmt=1529213992430932&fvip=6&c=WEB&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRAIgZzTTsBPpVznwCvzArBFuSF7Bm3yhcO0rwQdfOjBibnsCIBqf8iHuAwahqi0T6qZ3MNbj8BfLgGo2Y3fPOi96RgEV&redirect_counter=1&cm2rm=sn-aigeey7d&req_id=8f890b1c72fda3ee&cms_redirect=yes&mip=2607:fea8:4d9f:fa68:40a2:35d0:8863:2d17&mm=34&mn=sn-vgqsrn76&ms=ltu&mt=1566514280&mv=m&mvi=5&pl=41&lsparams=mip,mm,mn,ms,mv,mvi,pl&lsig=AHylml4wRQIgSCcxaGd_IpVykCuglJtHwewUuZZIyKKr1FBbNP5MvqsCIQCYQEUoM9SpfpySHA_13lB6SvevIuMvhyFDEcrsX0y0ig==
How can I download the video in this URL programmatically through JavaScript? I cannot use PHP, Apache, JQuery etc, only Pure JavaScript and HTML.
I have tried using download.js, but I do not think that is the right approach to download videos. I have also looked/tried at various other websites and Stack Overflow answers, but none of them fixed this issue.
EDIT: The other SO answer that someone suggested will not work since the video is on a different baseurl than my own, which means that
<a href="file" download="filename">
will not work on Chrome. Doing this just opens the video.
function downloadImage() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://via.placeholder.com/150', true);
xhr.responseType = 'blob';
xhr.onload = function () {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.target = '_blank';
tag.download = 'sample.png';
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
};
xhr.onerror = err => {
alert('Failed to download picture');
};
xhr.send();
}
I found the solution to the problem. The link was a YouTube source video link that I was trying to download, and on all videos (except the ones with music or the music genre) all you needed to do was to add
&title=[NAME OF FILE HERE]
which would download the video.
Edit: Downloading these videos worked with download.js. You need to make a XMLHTTP request to the video to get the data, and then use the function
download(data, name, mime)
For more documentation, look on the download.js GitHub page.

Google Chrome extensions - Get images from cache

I am reprogramming a Google Chrome extension, it was able to download an image using the src attribute, but now, the page change the way it shows the image, it use in the src attribute some kind of script that in background changes the image, getting a different image that web page is showing. I can see the image that I need but using "ChromeCacheView" of NIRSOFT, but it's a desktop solution, so it can't help to do it in the Chrome extension.
Someone could help me, please!
This code below is what I'm using now, but as I said already, it can't show me the web page image is showing.
var xhr = new XMLHttpRequest();
// I think here is where I need the change Getting this ID from cache
var kima = $(frame1).contents().find("#ccontrol1");
xhr.open('GET',kima[0].src,true);
//
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'image/png'});
kym_send_image(blob);
kym_process01();
}
};
xhr.onerror = function (e) {
window.location.href = url1;
return;
};
xhr.send();
Well you need to use request.fetch,
You could replace your code with this one below
fetch(kima[0].src,{cache : "force-cache"}).then(r => r.blob({type: 'image/jpg'})).then(blob => function_to_catch_blob(blob));
Hope this could help you!

How to read png meta data from JavaScript?

My custom server embeds meta data about an image in the PNG meta data fields. The image is loaded via a regular img tag. I'd like to access the meta data from JavaScript - any way to achieve this?
If not, what are the alternatives for serving additional information for an image? The images are generated on the fly and are relatively expensive to produce, so I'd like to serve the meta data and the image data in a single round trip to the server.
i had a similar task. I had to write physical dimensions and additional metadata to PNG files. I have found some solutions and combined it into one small library.
png-metadata
it could read PNG metadata from NodeJS Buffers, and create a new Buffers with new metadata.
Here how you can read PNG metadata in the Browser:
function loadFileAsBlob(url){
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status === 200) {
resolve(this.response);
// myBlob is now the blob that the object URL pointed to.
}else{
reject(this.response);
}
};
xhr.send();
})
};
const blob = await loadFileAsBlob('1000ppcm.png');
metadata = readMetadataB(blob);
A couple of solutions I can think of:
Pass the metadata as headers, use XMLHttpRequest to load the image and display it by converting the raw bytes to a data uri, as talked about here. Looks roughly like this:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var metadata = xhr.getResponseHeader("my-custom-header");
image.src = window.URL.createObjectURL(xhr.response);
}
xhr.open('GET', 'http://whatever.com/wherever');
xhr.send();
Alternatively, write a little png parser in js (or compile libpng to javascript using something like emscripten), and do basically the same thing as above.
It probably wouldn't be too hard to write actually; since you don't care about the image data, you'd just have to write the chunk-traversing code. Read up on how chunks are laid out here, and figure out what chunk type you're storing the metadata in. Still, don't really recommend this if you can just use headers...

Load a binary asset file into Chrome App

I'm trying to make a Chrome app that will have some animated objects in it.
I can load textures by using: new Image() and then setting the image's src property to the name of a file in my app's root directory. (This will load the texture)
Is it possible to do a similar thing for binary files that contain my proprietary animation data? I've looked and looked but I don't seem to find anything that lets me load a binary file that has NOT been picked by the user or dragged and dropped by the user.
If this is something that is not allowed, (presumably for security issues) anyone got any clever workarounds?
For files inside the app's package, it should be as simple as loading the file with XHR.
Use the fully-qualified URL to be on the safe side, obtained with chrome.runtime.getURL(pathRelativeToRoot)
This was what worked for me:
function reqError() {
console.log("Got an error");
}
function reqListener() {
var buffer = this.response;
console.log("Load complete! Length = ", buffer.byteLength);
}
function LoadBinaryFile(fileName) {
var path = chrome.runtime.getURL(fileName);
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;
oReq.open("GET", path, true);
oReq.responseType = "arraybuffer";
oReq.send();
}

Cross origin problems getting base64 encoding of an image

I am making a "simple" bookmarklet for 4chan (potentially extensible to other sites) that will download all images in the current thread as a zip archive. The images displayed in a 4chan thread are just thumbnails. The images themselves are provided as links that can be accessed by clicking the thumbnails.
My code should work almost perfectly. I found the class that contains the links to the full-sized images. I select all of these 's with jquery. I am using JSZip to compile the images. But JSZip requires the image data encoded in base64. After scourging SO for methods to do this, it seems almost unanimous that drawing an image onto a canvas and converting the image to base64 that way is the best way to do it. However, since 4chan provides links to its images instead of them being right there in the site, the canvas becomes "tainted" when I draw a linked image onto it, and I cannot get the base64 encoding from it.
How can I do this differently so that it works? Is there a way around the cross origin thing? I tried adding crossorigin="anonymous" to the images I'm creating, but it doesn't work.
var getDataUri = function (targetUrl, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
var proxyUrl = 'https://cors-anywhere.herokuapp.com/';
xhr.open('GET', proxyUrl + targetUrl);
xhr.responseType = 'blob';
xhr.send();
};
getDataUri(path, function (base64) {
// base64 availlable here
})
While converting into base64 you can use a proxy URL (https://cors-anywhere.herokuapp.com/) before your image path to avoid cross-origin issue
Check the window.btoa() (doc) which you can use to base-64 encode binary data.
There shouldn't be need for canvas in this case, just download the data with "ajax" (SO) instead.
If you use canvas and the image is for example JPEG you will get a re-compressed image as well (reduced quality) and it will be slower so I wouldn't recommend canvas in this case.
Here is a solution as well (SO).

Categories

Resources