How to embed a large image with data uri - javascript

I currently have a large base64 image uri (Received via external JS script) and want to embed it into the HTML page. I did this successfully locally but now that it pulls it from another place it seems to not work, it loads part of the image then says "Image corrupt or truncated. URI in this note truncated due to length." This occurs both just in the <img> tag and using <canvas>, is there any way to load large images from uri? Or another way to display images from a base64 string?
What doesn't make sense is it works fine if I specify the base64 string as a javascript variable, but when I include it as a variable in an external script, it gives this error. Would breaking up the string then putting it back together fix this?

You shouldn't use data-URLs for huge files.
You could try to convert your base64 URL into a blob object and the blob object into a temporary blob url using the following javascript function:
function dataurlToBlobUrl(url){
var parts = url.split(',',2);
var mime = parts[0].substr(5).split(';')[0];
var blob = b64toBlob(parts[1],mime);
return URL.createObjectURL(blob);
}
And the b64toBlob function from here:
https://stackoverflow.com/a/16245768/5406901
Just make sure to use "URL.revokeObjectURL" whenever you no longer need the blob url.

Related

Modifying Images on Webpage with Web Extension

I am currently working on a web extension that goes through all the images in the current webpage and blurs them. I have created a backend API that accepts a base64 encoded string of an image and returns the encoded string for the blurred image. My current issue is that I can't find a way to access all the images on the current webpage and get their base64 encoded string through javascript. How can I do this?
The intended architecture of the extension is as follows: the javascript file reads all the images on the webpage and encodes them into a base64 string, which is passed to the backend API. The API then blurs the image and returns a base64 encoded string of the blurred image. The javascript then decodes the string and replaces the original image with the blurred image.
Any help would be greatly appreciated.
I have tried going through all the image tags in the html of the webpage and fetching their urls, however this does not allow me to get the base64 encoding of the image(s). I would like to write a function that takes in the url to an image and returns the base64 encoding.

Creating a pdf file from mpdf string output?

I'm using mPDF server side to create a pdf file. It works okay if I output the file to the server, however, I would like to return a string back to the client and build a pdf file from it which I can then use like any normal file from a file input.
server side, the (simplified) code is
$output_dest = 'S';
$content = $mpdf->Output($post_data->fileName, $output_dest);
//$mpdf->Output($post_data->fileName, 'F'); //just to check that the output should be correct
$response->setContent($content);
and client side i've tried using Blobs to create a file
var fileObj = new Blob([offerString], {type : 'application/pdf'});
but there are 2 problems. First, the blob, when sent to the server, doesn't have the required name. Secondly, the pdf file created (using window.saveAs to save the blob) is blank. It has the correct number of pages and author information, but it's completely blank.
If I use mPDF's file output, the resulting file is correct, so the problem must lie somewhere within the string->blob process.
Edit: The solution is to create the Blob not straight from the string but from an arrayBuffer. I've created the arrayBuffer using the solution suggested in another answer here

encoding WAV data in Javascript

I am generating WAV data using JavaScript, and I'm able to generate the data and store it in a variable waveFileOutput, then send it to an embedded player by setting the source to following dataURI I set up:
var dataURI = "data:audio/wav;base64," + escape(btoa(waveFileOutput));
I'm also able to get the file to (sort of) "save" by opening a window using the same data after encoding it and saving the window as a file. The problem is that the data is not properly encoded as a WAV file in the new window, even though the embedded play is fine with the encoding. I need to figure out the correct way to encode it. Here are a couple of things I've tried (but neither works):
Try #1: window.open("data:application/octet-stream," +
encodeURIComponent(waveFileOutput));
Try #2: window.open("data:application/octet-stream," +
escape(btoa(waveFileOutput)));
I can post the whole (working) file if that helps, but seemed like it might be a waste of space.
Suggestions for how to get the data encoded properly when "saving" it using this approach?

Storing the image from an HTML input file form locally

I was wondering if it is possible to store the image from
<input type="file" id="image">
locally. Would I have to store the image, or could I simply store the image location?
For context, it's from a form that takes name, address etc from input forms, creates an object, stores it in an array and displays the array.
Contrary to the other answers here, if you're using a modern browser you can get and store quite a bit about the contents of a file <input> using elm.files, FileReader and window.localStorage. You can even tell the browser to save it again (default download behaviour).
It should be noted that doing this does not mean you can set the .value on the <input> node.
Here is an example of what you can do, assuming a file has been chosen.
// From <input> node
var elm = document.getElementById('image'),
img = elm.files[0],
fileName = img.name, // not path
fileSize = img.size; // bytes
// By Parsing File
var reader = new FileReader(),
binary, base64;
reader.addEventListener('loadend', function () {
binary = reader.result; // binary data (stored as string), unsafe for most actions
base64 = btoa(binary); // base64 data, safer but takes up more memory
}, false);
reader.readAsBinaryString(img);
From here you can save in localStorage, create dataURIs etc. For example, Say from fileName we know the image is a .jpg, then you could display it by setting an <img>'s src to "data:image/jpeg;base64," + base64.
Note that any modification of this data will not have any effect on the original file chosen.
No way. But if you could that would raise serious security issues.
If you try to get value of your file input e.g.:
document.getElementById('image').value
the value would be "C:\fakepath\somefile.txt"
No. Since storing a file or accessing a file on the local OS would violate the permissions of the browser. So your scripts cannot access the content unless it has been uploaded to the server. Also different browsers handle the path of the file that has been selected in different ways. So you encounter a number of problems there.
That said, there are some ways to get around this that I will not discuss. Simply put, the image should be uploaded to the server in some fashion and then your scripts can reference the path or the image itself from the path that it was uploaded to.
If you want to get the file name, or even display the image, you can do that using the File API (on browsers that support it). The path is not available for security reasons.

Is there a way to let a user view an image they are about to upload client side before uploading to the server?

When a user is uploading an image, is there a way I can load the image client side and show it to them first, before uploading it to the server? Preferably using javascript/jquery only, but using flash would be acceptable too.
It is possible with the new FileReader interface defined in HTML5 and works on Firefox currently.
A file input has an associated files property which tracks the list of files currently selected for that input. To display a file from this list, create a new FileReader object, initialize its onload event handler, and read the file as a data URL.
// get the first file, foo is a file input field
var file = document.getElementById('foo').files[0];
// setup the reader and the load complete callback
var reader = new FileReader();
reader.onload = function(e) {
var image = new Image();
// string representing the image
image.src = e.target.result;
document.body.appendChild(image);
};
// read the file as a data url
reader.readAsDataURL(file);
Once the file is loaded, you will have access to its contents in a data url scheme, for instance:
data:image/jpeg;base64,...aqHI7sNyPGFjdtQvFr/2Q==
Create a new Image and set its src attribute to this data string.
See a working example here. Firefox only.
You can't really do this cross-browser in JavaScript alone due security restrictions that are in place, there are a few flash versions available though, here's one example (the free version does what you're after).
There are probably more free flash versions out there as well.
Since HTML 5 those things are possible, thanks to the File Object, File Reader and the ´files´ property of the input element.
See here for more information: http://demos.hacks.mozilla.org/openweb/ & http://hacks.mozilla.org/2009/12/file-drag-and-drop-in-firefox-3-6/.
Example (only for demonstration, requires FF 3.5+):
See here: http://gist.github.com/536024
In case you wonder, File.url is brand new, with it you dont anymore need to read the whole file into the memory, and assign the whole DataUrl (data:image/src,base64;DF15EDFE86..) to the src property.
Well, the <img> tag needs a path to the image. That path can be to something on the web, or to a local file. So far, so good. The trick is, how do you tell your javascript the path on the local system, so it can set the IMG SRC attribute.
The path of the file <input> tag is unavailable to javascript (as a security precaution --- you don't want a want page upload files from you system behind your back).
On the other hand, if you can get your users to enter a correct file path name into a text <input> field, then it should be possible.

Categories