Save image as jpg with extension - javascript

I'm using Backbone and html2canvas.js, this is the code I have so far for transforming a div to canvas and saving it. It works, but it doesn't add the .jpg extension. Because of this, after downloading the image, FF and Chrome first ask me about the program I want to use to open the file and IE just tells me that I don't have the right program and suggests visiting the store.
In FF and Chrome I can see the image when choosing the default Windows picture viewer etc.
What I would like to achieve is to add the .jpg extension so the file opens in the default program right away:
savePicture: function() {
//$(this.el).find('.drag-img').unwrap();
var image = $(this.el).find('#droppable2');
html2canvas(image, {
onrendered: function(canvas) {
var img = canvas.toDataURL("image/jpeg");
var frame = document.getElementById("myHideFrame");
if (!frame) {
frame = document.createElement("iframe");
frame.id = "myHideFrame";
document.body.appendChild(frame);
}
frame.src = img.replace(/^data[:]image\/(png|jpg|jpeg)[;]/i, "data:application/octet-stream;");
}
});
},

Sadly, IE8 and above only supports data URIs in CSS, <link>, and <img>. So adding it to a frame as you are doing will not work.
Could you, for IE8 and above, put the data into an <img> and ask the user to right click and save the image?

Related

Download html window object with JS

i have this iframe here, and i want to doanload the window page with pdf inside, js function print() only shows the page, i want to download it automatically, bellow is the full code (i tryed with jspdf too).
<iframe id="conteudoIframe" src="https://eproc.trf4.jus.br/eproc2trf4/controlador.php?acao=acessar_documento_publico&doc=41625504719486351366932807019&evento=20084&key=0562cc6eddee0cc4a81dd869f92328dceab34deeaa59f4a33c43da6361cf42d6&hash=08920b364dc8433ad071d6b10c7e3817" name="superior" width="100%" height="560px"></iframe>
<script>
downloadPdfFromIframe();
function downloadPdfFromIframe() {
var script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js';
document.head.appendChild(script);
script.onload = () => { setTimeout(download(), 20000); };
function download() {
var myIframe = document.getElementById("conteudoIframe").contentWindow;
myIframe.focus();
myIframe.print();
myIframe.close();
var pdf = new jsPDF();
pdf.fromHTML(myIframe);
pdf.save('test.pdf');
return false;
}
}
</script>
Iframes are only a window to remote objects thus while viewing they are showing both the already downloaded html surround and the already downloaded PDF but the PDF is independent It may be downloaded before or after the frame, you can see the pdf behind the print html dialog. So the PDF is in a different application as seen in the second browser view of your HTML.
Thus you have to save/print either one at a time. Frame object or Pdf object, to get both is not impossible, just needs to be done with a suitable application (not browser). So just like here I have ScreenShots, those canvases can be easily saved or printed as PDF.
A Chrome based Browser viewing the iFrame for printing
A Firefox based Browser viewing the iFrame to print using any other method like open in a second application window.
If you need to download the two parts outside a browser then use two Download Commands so here is my.pdf
curl -o my.pdf "https://eproc.trf4.jus.br/eproc2trf4/controlador.php?acao=acessar_documento_implementacao&doc=41625504719486351366932807019&evento=20084&key=0562cc6eddee0cc4a81dd869f92328dceab34deeaa59f4a33c43da6361cf42d6&hash=08920b364dc8433ad071d6b10c7e3817&termosPesquisados="

DataTransfer an image from same page gives URL but image from different page gives file

EDIT
The source of this problem is the behavior of the Edge browser, as identified by Sami. Firefox does the same thing, but Chrome works fine.
Original Question
I have a drop container for users to drag and drop an image to set an <input type="file"> with the image.
If the image is being dragged and dropped from a different page, the image is recognized as a file. However, if the image is dragged and dropped from the same page with the drop container, it is recognized as a URL.
Why isn't the image being recognized as a file when it is dragged and dropped from the same page as the drop container?
Here is the fiddle with the drop container and image file. When you drag the image file on this page into the drop container, it is recognized as a URL although I want it to be recognized as a file.
https://jsfiddle.net/nadf9c82/1/
Next, try dragging the image on this fiddle https://jsfiddle.net/7sqb5r0f/1/ into the drop container on the other fiddle and you will see it is recognized as a file, which is what I want.
Why do images on the same page as the drop container evaluate as URLs and not files? Is there a fix to make them recognized as files and not URLs?
Here is the code for reference
<div class="dropContainer" id="dropContainer">Drop Here</div>
<div id="imagetwo">
<img src="http://a.mktgcdn.com/p/khxNbcdQcr1HQKNgk9cPNUyWUprmZ5Dryx9P5MAV0SE/2669x3840.jpg" />
</div>
<script>
dropContainer.ondrop = function(evt) {
//evt.preventDefault();
if(evt.dataTransfer.files[0]){
console.log("is a file");
const dT = new DataTransfer();
dT.items.add(evt.dataTransfer.files[0]);
fileInput.files = dT.files;
}else{
// Try dataTransfer url second
var dataTransferUrl = evt.dataTransfer.getData('url');
if(dataTransferUrl){
console.log('is a url, not a file');
console.log(dataTransferUrl);
}
}
};
</script>
I think you can do it, but it won't work in Fiddle due to The page at 'https://jsfiddle.net/' was loaded over HTTPS, but requested an insecure resource ... the content must be served over HTTPS due to your HTTP request
Here's what I think, whenever you drop the image, it'll receive an URL instead of the file like you want. Then just make it into a file.
It's called convert your URL image to File object, if my way is not working, it's the keyword for you to have a look more, I hope it'll give you some ways to work around since I'm not good at this, too.
Replace this code of mine into your Try dataTransfer URL second part, but be warned that it'll fire an error on Fiddle due to HTTP request. So I've to replace the HTTP with HTTPS, but it'll get you the CORS Block, so if you have the extension to unblock CORS, it'll work, for development or testing purposes, of course.
let url = evt.dataTransfer.getData('url');
const urlArray = Array.from(url)
urlArray.splice(4, 0, 's')
const urlFinal = urlArray.join('')
fetch(urlFinal)
.then(async (res) => {
const contentType = await res.headers.get('Content-Type')
const blob = await response.blob()
const file = new File([blob], "image.jpeg", { contentType })
})
}
When I drop an image to Drop Here box, it'll create an Object File, so it'll count as a file instead of an URL, I think that's what you want, hope I can help you somehow.
Take an URL as an Object File after Dragging Image and Drop it into Drop Here Box

Open or redirect to Base64 DataURL via jQuery or JS

I have a script which converts a canvas element to an <img>tag and then reloads it in a new window (about:blank page). If I then right-click the image and select 'Open Image In New Tab' it opens the Base64 DataURL (i.e. Just the image).
Is there any way to open the Base64 DataURL without the user having to right-click the image?
Ideally, the user would never even see the about:blank page and would simply be redirected to the DataURL.
Here is the current code that generates the image and opens it in a new window:
<script>
function print_card(){
var canvas=document.getElementById("canvas");
var win=window.open();
win.document.write("<img id='compiledImg' src='"+canvas.toDataURL('image/png')+"' width='324' height='204' style='margin: 0; padding: 0; background: #e6e6e6;'/>");
win.location.assign(reload);
}
$("#printCard").click(function(){ print_card(); });
</script>
It seems like I should be able to get the dataURL from the image id and redirect to it as opposed to a new window, but I have no idea how to accomplish it.
I tried assigning canvas.toDataURL('image/png) to win.location but that did not help.
Any guidance would be much appreciated.
It seems that you are simply trying to open the generated image in a new tab. Most modern browsers do not allow opening data URLs programmatically in the top frame for security reasons, you need to use a different method, eg. a blob like this:
function openCanvasContentInNewWindow(canvas) {
canvas.toBlob(blob => {
const objectURL = URL.createObjectURL(blob);
window.open(objectURL);
}, 'image/png');
}
Reference for the HTMLCanvasElement.toBlob method.
If you need to support browsers that do not support HTMLCanvasElement.toBlob() (such as Edge and older browsers), you can use this polyfill. (Since I am not the author of the polyfill, I am not sure whether it would be OK for me to paste the code here directly.)

Javascript Bookmarklet - Download Images

Edit: Thanks to #Dogoku, I was able to find a solution (here). It turns out that Chrome doesn't allow/handle the download attribute anymore, so we have to force a workaround.
I'm trying to create a javascript bookmarklet that downloads images (code shown below). It's accessing the url correctly, but instead of downloading the image it just opens the image in a new tab.
Please help!
r.addEventListener('click', function(ev) {
r.href = h;
r.download = c;
}, false);
document.body.appendChild(r), r.click(), document.body.removeChild(r);
the variable r is created using document.createElement("a") which creates an element like so:
Before, when using a bookmarklet you could basically just "click" on the image and it would download.

JQuery Feature Detection for <a href="data:..."> support?

I have am using html2canvas to enable screenshots of divs within my web application. It's working well enough in Chrome (including Android), Safari (including iOS) and FireFox. In IE 11, however the image won't save.
Code looks like this:
function displayModalWithImage(canvas, filename) {
var modalcontainer = $('#snapshot');
var modalcontainer_body = modalcontainer.children().find('.snap_shot_container');
var modalcontainer_save = modalcontainer.children().find('.save_snapshot');
var image = new Image();
var data = canvas.toDataURL("image/png");
image.src = data;
modalcontainer_save.attr('download', filename +".png");
modalcontainer_save.attr('href',
data.replace(/^data[:]image\/png[;]/i, "data:application/octet-stream;"));
$(modalcontainer_body).html('');
$(image).appendTo(modalcontainer_body);
$(modalcontainer_save).on('click', function() {
modalcontainer.modal('hide');
});
modalcontainer.modal();
}
Browser behavior varies:
Chrome: displays modal and then saves the file when "Save" is clicked. (acceptable)
Firefox: displays modal and then displays a separate dialog when "Save" is clicked (acceptable)
Safari: display modal and then loads image in a separate tab when "Save" is clicked (acceptable... maybe)
IE 11: displays modal, but does nothing but hide the dialog when "Save" is clicked (unacceptable)
The data.replace was suggested by another SO answer, but it did not appear to have any effect on the behavior of any of the browsers. Previously the href attribute was simply set to data.
So, anyway, at this point replacing the modal dialog with a simple window.location = data is a viable alternative. But, since Chrome works well and Safari and FF work well enough, i'd like to simply do a feature detection that would window.location for IE but show the modal for the other browsers. But, I don't know what "feature" is missing in IE to check for.
tl;dr
is there simply a change or bug in my javascript that would enable IE to work (save the image encoded as data to a file).
if not, which feature in IE should I detect for that would enable me to customize the behavior for IE
if that's not an option; what's the current best practices for old-fashioned browser detection?

Categories