how to save DIV as Image with canvas2image with extension - javascript

I have done the following code to convert HTML Content(DIV) to save as Image (JPEG, PNG,GIF Etc) with below code.
<pre>
html2canvas($(".mainbox"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
Canvas2Image.saveAsImage(canvas);
$("#FinalImage").append(canvas);
}
});
</pre>
I have also included html2canvas.js,base64.js and canvas2image.js in my page. At the end Image is shown in #FinalImage DIV and browser ask me to save it in my drive up to now all are working fine.
Now the question is name of the saved image has no Extension, every time I need to go to the image and assign the Extension(".jpg",".png" etc...). Is there any solution to set extension by default when user saves from the browser.
Thanks in advance.

I have done same functionality for capturing signature. This is different from your approach. but this code snippet may help you. plz comment if u need whole source code.
var canvas = document.getElementById(<canvas element id>)// get canvas element
var dataURL = canvas.toDataURL("image/png");// convert to img, specify extension
document.getElementById(<new image id>).src = dataURL; // write as an image
In line two I specified png.there you can change the extension of image. Hope it helps

Related

Once an image has failed loading, how can I make the browser retry?

I'm making a Chrome extension which in order to reduce bandwidth usage it stops all outcoming requests which are images.
I want to provide functionality where if the user clicks on the image (or technically a layer on top of that image) it would try to reload the image, this time not being blocked by the extension.
How can I tell the browser to retry loading the image? And if there isn't a straightforward way to do it, what would be a work around? Deleting the old image from the DOM and adding it again?
Any help is appreciated. :)
EDIT 1:
To answer #CBroe's question:
Using the chrome.webRequest.onBeforeRequest API in a background script.
To answer #jfriend00's question:
The usual placeholder "couldn't load image" icon, I guess also known as "broken file" icon:
See all those broken images?
That screenshot also illustrates the point of a layer on top of another image. Should those images not be broken, the loaded image would be there but that layer (the one in a dark grey which shows the image's dimensions) still remains there.
The desired href still exists there in the img tag:
If simply assigning the same src value to the img element is not enough¹, then create a new Image object in JavaScript, and assign the value to its src property.
¹ It might not be, if the browser just goes, “oh hey, that is the same value for the src attribute that the img already had, so I don’t have to do anything” – creating a new JS Image object however should make the browser request that resource again if he realizes he does not have it cached already.
What I would do instead is replace the URLs of the images with an image from your extension. A 1x1 pixel transparent GIF or PNG.
When you do this, add an attribute to all of the elements you replaced... something like data-yourextension-originalurl, with the URL of the original image. If the user then wants to load images, it's easy enough to go back and fix those image elements.
While I'm not too familiar with the Chrome API, a quick glance seems to suggest that there's no way to get the specific img element from each onBeforeRequest, which you'd need to know in order to figure out where to attach custom code.
This may be better accomplished with native JavaScript of some sort. For example, if Chrome lets you inject code on load, you could apply a function like the one below to all img elements after document load but before image load.
// Given an img element, replaces its src with a placeholder URL,
// and sets its click action to load its original src
function makePlaceholder(elem){
elem["data-oldtitle"] = elem.title;
elem["data-oldhref"] = elem.href;
elem["data-oldsrc"] = elem.src;
elem["data-oldonclick"] = elem.onClick;
elem.title = "Click to load the blocked image.";
elem.href = '';
elem.src = "http://example.com/placeholder.png";
elem.onClick = function(){
this.src = this["data-oldsrc"];
this.title = this["data-oldtitle"];
this.href = this["data-oldhref"];
this.onClick = this["data-oldonclick"];
};
}
The simple way to force reloading an image in JavaScript is:
var img = document.getElementById("myImage");
img.src = img.src.replace(/\?.+/,"") + "?" + new Date().getTime();
This adds a unique QueryString to the image which basically forces the browser to not use a cached version of the image.

Assistance with HTML5 Canvas and JS displaying images on it please?

I'm making an Android game, in HTML5 and Javascript, I am part of the way there, but have hit something that has stumped me, My JS file and my Html file were working together, to draw on the canvas etc, but now I'm trying to draw an image on the canvas, nothing is being displayed, I know the img function is being found, as, alert (img);, works so it's just lost on me. (currently this is copied from a book I was given at college, and it's identical, the JS has been verified in JSHint and passes, so I'm lost) also, please be quite simple, I'm pretty new to JS but have used html for a long time, and this just has to be a simple game for a college assignment.
My HTML code is
<canvas id="game" width="1024" height="600">Sorry, your browser does not support this</canvas>
and my JS is:
function init() {
var elem = document.getElementById('game');
var canvas = elem.getContext('2d');
var img = document.createElement('img');
img.setAttribute('src', 'http://www.minkbooks.com/content/snow.jpg');
img.addEventListener("load", function() {
canvas.drawImage(img, 20, 20);
alert(canvas);
});
}
addEventListener("load", init);
and here it is on JSfiddle: http://jsfiddle.net/xw8m7/
This answer is based on your jsfiddle. You are executing your javascript code as soon as it is loaded. Depending on where your code is located in the html, the canvas element might not be loaded yet, and that would prevent your code from loading the image into the canvas element, and you would still get the alert.
In JSFiddle, you need to set the option of running your code "onDomready". That means that the JavaScript won't run until everything has been loaded (your canvas element). After changing that in your jsfiddle, your function loaded the image into the canvas just fine.
Update:
Based on your comment about XDK, I found a bit of example code and modified it. Original source: https://software.intel.com/en-us/node/493117
document.addEventListener("intel.xdk.device.ready",function(){
init();
},false);

How to force a download instead of opening the file?

So basically, I am using a simple library called HTML2Canvas
This is my current code working great and is being called from an onclick event from a button:
function saveForm()
{
html2canvas(document.body, {
onrendered: function(canvas) {
document.body.appendChild(canvas);
}
});
}
Basically, all it does is take a screen shot and append it to the bottom of the page.
There was already a question similar to this, although the answer did not work and the download is always a corrupt jpg file:
html2canvas saving as a jpeg without opening in browser
Would there be a way to force a download within this function instead of appending it to the bottom of the page?
Use canvas.toDataURL to get the canvas content as an image src
open a window/popup
add an <img> to the popup
assign the image src as src for the image
function saveForm() {
html2canvas(document.body, {
onrendered: function(canvas) {
var img = canvas.toDataURL("image/png");
var open = window.open('','','width=500,height=500')
open.document.write('<img id="img" style="width="400">');
open.document.getElementById('img').setAttribute('src', img);
}
});
}
Tested the code inside onrendered, and it works for sure - but not along with html2canvas.
If you right click on the image in the popup -> save image as, the saved image is valid.
The reason why I am using setAttribute and not simply src="..." is that if you assign the data src as string the image get corrupted.
Edit
I know :( I think you have to set HTTP Headers to force a download, and this can only be done by the server (correct me if I am wrong). I think of a "proxy" on the server like this mockup, download.php :
<?
$src=$_POST['src'];
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="download.png"');
header('Content-Length: '.count($src));
echo $src;
?>
and call it by
var img = canvas.toDataURL("image/png");
window.open('download.php?src='+img);
But then you will face a lot of Request-URI Too Large-messages, unless all your canvas-images is in icon-size.
A second way - and probably the one that would work - would be to save img in a table on the server through ajax, eg calling a script with img src that saves it. When this call is finished, you could call another server script with the correct headers for image download, including the img src saved just before. But this is a more extensive approach you could try yourself..?
Here is a solution that builds on the accepted one to enable a download button without server-side code using jQuery.
https://codepen.io/nathansouza/pen/OXdJbo
function download(url){
var a = $("<a style='display:none' id='js-downloder'>")
.attr("href", url)
.attr("download", "test.png")
.appendTo("body");
a[0].click();
a.remove();
}
function saveCapture(element) {
html2canvas(element).then(function(canvas) {
download(canvas.toDataURL("image/png"));
})
}
$('#btnDownload').click(function(){
var element = document.querySelector("#capture");
saveCapture(element)
})

Phonegap: How to save a HTML5 canvas as image to device photo gallery/library

Hey I am developing an app that could tag an image with the geolocation and the time stamp, using Phonegap. I have been able to tag the image by editing the image as a canvas. Now I need to save that edited image to the device Photo gallery/library as a new image or replace the image selected to be tagged. The purpose of using phonegap is that the application must function cross-platform. Is there any way this could be achieved ?
The following code edit the image as canvas and converts the image back to a Data URI.
var canvas = document.getElementById("canvasPnl");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj,0,0,300,300 );
context.fillStyle="#FFFFFF";
context.fillText('Latitude: '+ lat.toString()+' Longitude: '+ lon.toString(), 0, 10);
context.fillText(new Date(), 0, 20);
};
imageObj.src=imageURI;
dataURI= canvas.toDataURL();
Can this be converted to an image object and saved to phone gallery???
https://github.com/devgeeks/Canvas2ImagePlugin apparently does what you want, although I've not tried it.
I don't think you can make the image save in the gallery using just JavaScript but you can send the user to the image or display the image where the user can manually save it.
Maybe you could try the plugin I wrote for IOS (If you want to save a canvas element to photogallery, you could get the dataURI of the canvas the use the downloadWithUrl method below). Hope it works for you.
here is the git link: https://github.com/Nomia/ImgDownloader
Short Example:
document.addEventListener("deviceready",onDeviceReady);
//google logo url
url = 'https://www.google.com/images/srpr/logo11w.png';
onDeviceReady = function(){
cordova.plugins.imgDownloader.downloadWithUrl(url,function(){
alert("success");
},function(){
alert("error");
});
}
//also you can try dataUri like: 1px gif
//url = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
you can also save a local file to image gallery use the download method

select an image and manipulate it in javascript (no form submission)

Is there by any chance a way of letting the user select an image from his hard drive and without submitting it to the server use this image in the browser?
I need this because I want the users to be able to crop an image before sending this cropped image to the server (thus saving a post and some bytes of data).
What I tried to do is using an input type file and then capturing the submit event, but the value from the input is just a fake path (useless).
Any help would be greatly appreciated.
Here is a very basic example (with many globals, without input validation...) of image scaling: http://jsfiddle.net/89HPM/3/ . It's using the File API and a canvas element.
As #anu said the save can be done using toDataUrl method of the canvas.
In similar way you can achieve crop.
JavaScript
(function init() {
document.getElementById('picture').addEventListener('change', handleFileSelect, false);
document.getElementById('width').addEventListener('change', function () {
document.getElementById('canvas').width = this.value;
renderImage();
}, false);
document.getElementById('height').addEventListener('change', function () {
document.getElementById('canvas').height = this.value;
renderImage();
}, false);
}());
var currentImage;
function handleFileSelect(evt) {
var file = evt.target.files[0];
if (!file.type.match('image.*')) {
alert('Unknown format');
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
currentImage = e.target.result;
renderImage();
};
})(file);
reader.readAsDataURL(file);
}
function renderImage() {
var data = currentImage,
img = document.createElement('img');
img.src = data;
img.onload = function () {
var can = document.getElementById('canvas'),
ctx = can.getContext('2d');
ctx.drawImage(this, 0, 0, can.width, can.height);
};
}​
HTML
<input type="file" name="picture" id="picture" /><br />
<input type="text" id="width" value="200" />
<input type="text" id="height" value="200" /><br />
<canvas width="200" height="200" style="border: 1px solid black;" id="canvas"></canvas>​
Here is a blog post which I made about that basic example: blog.mgechev.com
New HTML5 File API is probably the closest solution to what your looking for:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
It allows you to browse for and read files within Javascript. Do whatever processing you like, and then upload to the server. Anything besides this is going to be very tricky indeed, and probably an unavoidable trip to the server and back.
Downside here is browser support.....as always
I am not sure which browsers work perfectly but HTML5 got DnD and File API. Let me give you steps which can work for you using FileAPI.
DnD API: Starts with the drop event when the user releases the mouse and the mouse-up event occurs.
DnD API: Get the DataTransfer object from the drop event
File API: Call DataTransfer.files to get a FileList, representing the list of files that were dropped.
File API: Iterate over all the individual File instances and use a FileReader object to read their content.
File API: Using the FileReader.readAsDataURL(file) call, every time a file is completely read, a new “data URL” (RFC 2397) formatted object is created and an event wrapping it is fired to the onload handler on the FileReader object.
FYI: The “data URL” object is Base64-encoded binary data, with a spec-defined header sequence of chars. Browsers understand them.
HTML5 DOM: set the image href to the File Data URL
You can't, for the following reasons:
For the reasons stated in this post: Full path from file input using jQuery
The fact that if you even try to create an img element loading a
local file path you'll get the error Not allowed to load local
resource: in your browser's console.
The fact that once you have an image in place you can only alter it's
appearance on screen and not alter the file on the system or send the altered image up to the server
You've stated that you need cross browser support, so HTML5 File API and Canvas API are out, even though they would only allow part of the functionality anyway.
I've just solved a problem closed to yours.
As everybody said you can't got the real image file address. But, you can create a temporary path and show the image in your page without submiting it to server. I'll show how easy it is, next to next paragraph.
Once you show it you can use some javascripts events to "pseudo-crop-it" and get the crop params (corners). Finaly you can add the params to some hidden field and submit the form. As a result you may use som php to crop the submited image at server and to save the result using a number of image formats as .png, jpg, gif, etc. Sorry if i do not write a complete solution, have not enough time.
/* some scripting to bind a change event and to send the selected image
to img element */
$(document.ready(function(){
$("input:file").each(function(){
var id = '' + $(this).attr('id');
var idselector = '#'+id, imgselector=idselector+'-vwr';
$(idselector).bind("change", function( event ){
(imgselector).fadeIn("fast").attr('src',
URL.createObjectURL(event.target.files[0]));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<!-- create a img element to show the selected image and an input file element to select the image.
ID attribute is the key to have an easy and short scripting
note they are related suffix -vwr makes the difference
-->
<img src="" id="image-input-vwr" alt="image to be cropped">
<input type="file" id="image-input" name="image_input">
Hope it help some body as it is a very old question.
Luis G. Quevedo

Categories

Resources