I can load an image file located in the same relative path as the JavaScript file
var imgObj = new Image();
imgObj.src = "images/backdropLevel0.jpg";
But how do I do the same (as simply and with pure JavaScript) for a text file ? (it has some initial data for a webGL game I am working on).
PS. I am not asking about user input from the client's computer using the new File object.
Fetching an image is easy since the browser takes care of all the fetching and rendering. However, loading an arbitrary file into your script requires a couple more lines:
var req = new XMLHttpRequest();
req.onload = function(){
process_webgl_data(this.responseText);
};
req.open('GET', './webgl_init.dat');
req.send();
Where process_webgl_data is whatever you want to do with the text of the file.
EDIT: Two quick things. Remember that request URIs are resolved with respect to the html file rather than the script, and second, here's the documentation for XHR.
You can also archive the same using fetch JavaScript API
Example:
fetch('./webgl_init.dat').then(r=>r.text()).then(process_webgl_data)
Related
I have code in here:
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
ctx.fillRect(50,50,50,50);
src="https://www.pixelstalk.net/wp-content/uploads/2016/07/3D-High-Resolution-Images-620x349.jpg"
var image = new Image();
image.crossOrigin = "anonymous";
image.onload = function(){
var imgWidth=image.width;
var imgHeight=image.height;
ctx.drawImage(image,0,0,imgWidth,imgHeight);
}
image.src = src
I find sometime when I use the url of a web image, it works. But sometime I must use the 'Data URLs' of a web image. So which one should we choose in general? the original url or Data URLs?
Can anyone give some advises?
This is because you retrieve the image from an external server. try to convert images from the same server as yours, or convert the image to base64. you find on the Internet several sites to convert an image to base6
example : src="data:image/jpeg;base64,/9j/4QAYRXhpZg.......DEFF";
It is not depends of picture size - it is Cross domain request browser restriction. You can't retrieve http resources from another domain without special HTTP header (Access-Control-Allow-Origin) in a response.
You can find more in https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
As others have pointed out the problem resides in CORS permissions. Basically the browser will not allow you to load up the contents of an image hosted on an external server (unless it has explicit CORS permissions to do so). Sometimes setting crossOrigin to anonymous solves it but in most cases it won't.
The only way to solve this problem is to do a cURL request to the image, download it to your server and then use it.
Usually you will only need DataURLs (base64 encoded images) when exporting the image from the canvas - using toDataURL() although, if you do make a cURL request and don't want to keep the physical image on your server you can just base64encode the response and load it on your canvas as a base64 DataURL.
I'm having a hard time finding easy documentation for JSZip that doesn't involve Base64 or NodeJS. Basically, I have a directory, in which is test.html and a folder called "images". Inside that folder is a bunch of images. I would like to make a zip file out of that folder.
Can anyone help me with some very simple "hello world" type code for this? The documentation on http://stuk.github.io/jszip/ includes things like adding an image from Base64 data or adding a text file that you create in JavaScript. I want to create a .zip file from existing files.
Perhaps the only support for adding images to .zip files with JSZip involves adding them via Base64 data? I don't see that anywhere in the documentation, nor an image-url-to-base64 function, though I did find one elsewhere on StackOverflow.
Any advice?
In a browser you can use an ajax request and use the responseType attribute to get an arraybuffer (if you need IE 9 support, you can use jszip-utils for example) :
var xhr = new XMLHttpRequest();
xhr.open('GET', "images/img1.png", true);
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function(evt) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var zip = new JSZip();
zip.file("images/img1.png", xhr.response);
}
}
};
xhr.send();
This example is limited because it handles only one file and manually creates the xhr object (I didn't use any library because you didn't mention any) but should show you how to do it.
You can find a more complete example in the JSZip documentation : it uses jQuery promises and jszip-utils to download a list of files and trigger a download after that.
If you use a library to handle the ajax request, be sure to check if you can ask for an arraybuffer. The default is to treat the response as text and that will corrupt your images. jQuery for example should support it soon.
Now first of all, I'm making a UserScript, meaning that I don't own the servers from which I download files or the servers to which I upload files.
So I need to download a file from a server (needs to be any type, not just text files), and then somehow submit that file to a file upload form on another website. Is that possible? At first I was wondering if I'd be able to submit the file directly from one server to the other, but I don't think that's possible.
So is there any way I can do this? I can use jQuery as well.
As long as you won't be blocked by XSS prevention, load the data using an XMLHttpRequest then post it to the other site.
Here is a very basic functional example:
var xhr = new XMLHttpRequest();
xhr.open("get", "http://www.example.com/file", true);
xhr.onload = function () {
xhr.close();
var xhr2 = new XMLHttpRequest();
xhr2.open("post", "http://www.example2.com/form", true);
xhr2.send(xhr.response);
}
xhr.send();
I would advise that you add some code to catch errors
For more details on XMLHttpRequests, the documentation can be found on MDN here, with instructions on how to use it on MDN here
My page generates a URL like this: "blob:http%3A//localhost%3A8383/568233a1-8b13-48b3-84d5-cca045ae384f" How can I convert it to a normal address?
I'm using it as an <img>'s src attribute.
A URL that was created from a JavaScript Blob can not be converted to a "normal" URL.
A blob: URL does not refer to data the exists on the server, it refers to data that your browser currently has in memory, for the current page. It will not be available on other pages, it will not be available in other browsers, and it will not be available from other computers.
Therefore it does not make sense, in general, to convert a Blob URL to a "normal" URL. If you wanted an ordinary URL, you would have to send the data from the browser to a server and have the server make it available like an ordinary file.
It is possible convert a blob: URL into a data: URL, at least in Chrome. You can use an AJAX request to "fetch" the data from the blob: URL (even though it's really just pulling it out of your browser's memory, not making an HTTP request).
Here's an example:
var blob = new Blob(["Hello, world!"], { type: 'text/plain' });
var blobUrl = URL.createObjectURL(blob);
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.onload = function() {
var blobAsDataUrl = reader.result;
window.location = blobAsDataUrl;
};
reader.readAsDataURL(recoveredBlob);
};
xhr.open('GET', blobUrl);
xhr.send();
data: URLs are probably not what you mean by "normal" and can be problematically large. However they do work like normal URLs in that they can be shared; they're not specific to the current browser or session.
another way to create a data url from blob url may be using canvas.
var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)
as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)
For those who came here looking for a way to download a blob url video / audio, this answer worked for me. In short, you would need to find an *.m3u8 file on the desired web page through Chrome -> Network tab and paste it into a VLC player.
Another guide shows you how to save a stream with the VLC Player.
UPDATE:
An alternative way of downloading the videos from a blob url is by using the mass downloader and joining the files together.
Download Videos Part
Open network tab in chrome dev tools
Reload the webpage
Filter .m3u8 files
Look through all filtered files and find the playlist of the '.ts' files. It should look something like this:
You need to extract those links somehow. Either download and edit the file manually OR use any other method you like. As you can see, those links are very similar, the only thing that differs is the serial number of the video: 's-0-v1-a1.ts', 's-1-v1-a1.ts' etc.
https://some-website.net/del/8cf.m3u8/s-0-v1-a1.ts
https://some-website.net/del/8cf.m3u8/s-1-v1-a1.ts
https://some-website.net/del/8cf.m3u8/s-2-v1-a1.ts
and so on up to the last link in the .m3u8 playlist file. These .ts files are actually your video. You need to download all of them.
For bulk downloading I prefer using the Simple Mass Downloader extension for Chrome (https://chrome.google.com/webstore/detail/simple-mass-downloader/abdkkegmcbiomijcbdaodaflgehfffed)
If you opt in for the Simple Mass Downloader, you need to:
a. Select a Pattern URL
b. Enter your link in the address field with only one modification: that part of the link that is changing for each next video needs to be replaced with the pattern in square brackets [0:400] where 0 is the first file name and 400 is the last one. So your link should look something like this https://some-website.net/del/8cf.m3u8/s-[0:400]-v1-a1.ts.
Afterwards hit the Import button to add these links into the Download List of Mass Downloader.
c. The next action may ask you for the destination folder for EACH video you download. So it is highly recommended to specify the default download folder in Chrome Settings and disable the Select Destination option in Chrome Settings as well. This will save you a lot of time! Additionally you may want you specify the folder where these files will go to:
c1. Click on Select All checkbox to select all files from the Download List.
c2. Click on the Download button in the bottom right corner of the SMD extension window. It will take you to next tab to start downloading
c3. Hit Start selected. This will download all vids automatically into the download folder.
That is it! Simply wait till all files are downloaded and you can watch them via the VLC Player or any other player that supports the .ts format. However, if you want to have one video instead of those you have downloaded, you need to join all these mini-videos together
Joining Videos Part
Since I am working on Mac, I am not aware of how you would do this on Windows. If you are the Windows user and you want to merge the videos, feel free to google for the windows solution. The next steps are applicable for Mac only.
Open Terminal in the folder you want the new video to be saved in
Type: cat and hit space
Open the folder where you downloaded your .ts video. Select all .ts videos that you want to join (use your mouse or cmd+A)
Drag and drop them into the terminal
Hit space
Hit >
Hit Space
Type the name of the new video, e.g. my_new_video.ts. Please note that the format has to be the same as in the original videos, otherwise it will take long time to convert and even may fail!
Hit Enter. Wait for the terminal to finish the joining process and enjoy watching your video!
Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:
function blobToDataURL(blob, callback) {
var fileReader = new FileReader();
fileReader.onload = function(e) {callback(e.target.result);}
fileReader.readAsDataURL(blob);
}
I'm very late to the party.
If you want to download the content you can simply use fetch now
fetch(blobURL)
.then(res => res.blob())
.then(blob => /*do what you want with the blob here*/)
Here the solution:
let blob = new Blob(chunks, { 'type' : 'video/mp4;' });
let videoURL = window.URL.createObjectURL(blob);
const blobF = await fetch(videoURL).then(res => res.blob())
As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.
However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.
<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>
Insert this to the page containing blob url and click the button, you get the content.
Another way is to intercept the ajax call via a proxy server, then you could view the true image url.
I'm currently developing a solution for a web-to-print, poster printing application.
One of features I'd like to include is the ability to 'edit' (crop/scale/rotate) a given image, before proceeding to order a poster of said image.
To avoid the requirement of the user uploading the image to a remote server before editing, I'd like to know the following:
Is it possible (using JavaScript) to load an image stored on the client machine into the browser / browser memory for editing, without uploading the image to a remote server? And if so, how is this done?
Thanks,
BK
The image can be edited without the user needed to upload the image to the server.
Take a look at the link below. It can be done quite easily.
Reading local files using Javascript
Yes you can! But in order to do it the browser must support Local storage! It is HTML5 api so most modern browsers will be able to do it! Remember that localstorage can save only string data so you must change images into a blob string. YOur image source will look something like this
This is a short snippet that will help you!
if(typeof(Storage)!=="undefined"){
// here you can use the localstorage
// is statement checks if the image is in localstorage as a blob string
if(localStorage.getItem("wall_blue") !== null){
var globalHolder = document.getElementById('globalHolder');
var wall = localStorage.getItem('wall_blue');
globalHolder.style.backgroundImage= "url("+wall+")";
}else{
// if the image is not saved as blob in local storage
// save it for the future by the use of canvas api and toDataUrl method
var img = new Image();
img.src = 'images/walls/wall_blue.png';
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL();
localStorage.setItem('wall_blue', dataURL);
};
}}else{//here you upload the image without local storage }
Hope you will find this short snippet useful. Remember Localstorage saves only string data so you cant
Oh and by the way if you are using a jcrop for cropping the images you have to save the blob code from image to the form and send it to the server manually because jcrop only handles images as a file not as a base64 string.
Good luck! :D
Using Html/Javascript you can only select files using the file upload html component (I think Flash / Silverlight wrap this to make things easier but its still sandboxed)
You can however use Java Applets (orwhatever they are called these days), Native ActiveX controls or .Net Controls to provide additional functionality (this hase security implications and required VM/Runtimes Frameworks etc)
Adobe Air or other client side technology might work, but looks like you want to do this in JavaScript. In this case, uploading the file to the server and manipulating from there is the best bet.
*[EDIT]
Since 2010, since this question was answered, technology has moved on, html now has the ability to create and manipulate within the browser. see newer answers or these examples:
http://davidwalsh.name/resize-image-canvas
http://deepliquid.com/content/Jcrop.html
*