save image with text as a image to photo gallery in javascript - javascript

I have a temporary image which i want to copy to gallery using javascript(phonegap).
Any help?
function save() {
var image = document.getElementById("tempImg");
//upload image to gallery of mobile . But how??
}
My image contains photo and text together...
i just want to arrange all div data including image inside div with some text on it and save it as an full image with any format .jpg,png etc in javascript.
I referred this link but that is for canvas to image but i want div to image .
Canvas to PhotoLibrary [Phonegap]

You might want to check out this url: http://html2canvas.hertzen.com/.
Using this script, you can convert your div into a canvas, then use the "Canvas to PhotoLibrary [Phonegap]" to do the rest.
Your code would look something like this:
function save() {
var image = document.getElementById("tempImg");
html2canvas(image, {
onrendered: function(canvas) {
// use "Canvas to PhotoLibrary [Phonegap]" on the canvas variable
}
});
}

you save this using session storage(or)local storage
save:
var z1,z2,z3;
function save() {
var a=$("#theme1_text").val();
var b=$("#image_div").css("background-image");
var c=$("#background_theme1").css("background-image");
sessionStorage.z1=a;
sessionStorage.z2=b;
sessionStorage.z3=c;
};
view:
function view() {
$("#theme1_text").val(sessionStorage.z1);
$("#image_div").css("background-image",sessionStorage.z2);
$("#background_theme1").css("background-image",sessionStorage.z3);
};

Related

How can I use cropme.js to allow users upload their profile image?

This is a knowledge sharing Q&A.
Cropme is a nice JS add-on for cropping and rotating an image using visual sliders. The author provided good documentation, but building a working implementation is not as simple as it should be.
The question I want to answer is this:
I want to allow my website-users to upload their profile image. That image must be exactly 240x292 pixels. The users should be able zoom and rotate their image, then crop it to that specific size and upload it to my website. How can I do all that with cropme?
These are the requires steps:
Show an empty placeholder for the image we want the user to load.
By clicking the "Get Image" button, the user can select an image from its local files.
The selected file is loaded into memory, and presented for editing using 'cropme'. The user can use visual sliders to rotate and zoom in/out
After clicking "Crop", the user is presented with the cropped image, and can decide to save the image or to cancel.
After clicking "Save", the cropped image is uploaded to a PHP server, the modal window is closed, and the placeholder image is replaced with the link to the just-uploaded image.
So how can we do this?
A fully working demo is presented here:
https://codepen.io/ishahak/pen/XWjVzLr
I will explain some of the details, step by step.
Note: usually in my code when you see obj[0], it is simply a conversion from jQuery object into a simple JS object.
1. Showing a placeholder for the image.
We can create a real SVG image on the fly using this code:
getImagePlaceholder: function(width, height, text) {
//based on https://cloudfour.com/thinks/simple-svg-placeholder/
var svg = '\
<svg xmlns="http://www.w3.org/2000/svg" width="{w}" \
height="{h}" viewBox="0 0 {w} {h}">\
<rect fill="#ddd" width="{w}" height="{h}"/>\
<text fill="rgba(0,0,0,0.5)" font-family="sans-serif"\
font-size="30" dy="10.5" font-weight="bold"\
x="50%" y="50%" text-anchor="middle">{t}</text>\
</svg>';
var cleaned = svg
.replace(/{w}/g, width)
.replace(/{h}/g, height)
.replace('{t}', text)
.replace(/[\t\n\r]/gim, '') // Strip newlines and tabs
.replace(/\s\s+/g, ' ') // Condense multiple spaces
.replace(/'/gim, '\\i'); // Normalize quotes
var encoded = encodeURIComponent(cleaned)
.replace(/\(/g, '%28') // Encode brackets
.replace(/\)/g, '%29');
return 'data:image/svg+xml;charset=UTF-8,' + encoded;
}
2. By clicking the "Get Image" button, the user can select an image from its local files.
This process involves an input element of type "file" which has no visible appearance (we set it with the 'd-none' class), and a button element which 'clicks' it to open a dialog:
<button id="btnGetImage" class="btn btn-primary">Get Image</button>
<input class="d-none" type="file" id="fileUpload" accept="image/*" />
And the relevant code:
$('#btnGetImage').on('click', function(){
//force 'change' event even if repeating same file:
$('#fileUpload').prop("value", "");
$('#fileUpload').click();
});
$('#fileUpload').on('change', function(){
CiM.read_file_from_input(/*input elem*/this, function() {
console.log('image src fully loaded');
$('#imgModal-dialog').modal('show');
});
});
When a file is selected, the 'change' event is firing, leading us to read the file into memory.
3. The selected file is loaded into memory, and presented for editing using 'cropme'. The user can use visual sliders to rotate and zoom in/out
Our read_file_from_input mentioned above is implemented like this:
imgHolder: null,
imgHolderCallback: null,
read_file_from_input: function(input, callback) {
if (input.files && input.files[0]) {
imgHolderCallback = callback;
var reader = new FileReader();
if (!CiM.imgHolder) {
CiM.imgHolder = new Image();
CiM.imgHolder.onload = function () {
if (imgHolderCallback) {
imgHolderCallback();
}
}
}
reader.onload = function (e) {
console.log('image data loaded!');
CiM.imgHolder.src = e.target.result; //listen to img:load...
}
reader.readAsDataURL(input.files[0]);
}
else {
console.warn('failed to read file');
}
}
When the FileReader is ready, we set the src for our internal image holder, and wait for the 'load' event, which signals that the img element is ready with the new content.
We listen to that 'load' event, and when triggered we show the modal. A modal in Bootstrap has several events. We listen to the one which signals that the modal is shown, meaning that the width and set and we can plan our Cropme dimensions based on it.
update_options_for_width: function(w) {
var o = CiM.opt, //shortcut
vp_ratio = o.my_final_size.w / o.my_final_size.h,
h, new_vp_w, new_vp_h;
w = Math.floor(w * 0.9);
h = Math.floor(w / o.my_win_ratio);
o.container.width = w;
o.container.height = h;
new_vp_h = 0.6 * h;
new_vp_w = new_vp_h * vp_ratio;
// if we adapted to the height, but it's too wide:
if (new_vp_w > 0.6 * w) {
new_vp_w = 0.6 * w;
new_vp_h = new_vp_w / vp_ratio;
}
new_vp_w = Math.floor(new_vp_w);
new_vp_h = Math.floor(new_vp_h);
o.viewport.height = new_vp_h;
o.viewport.width = new_vp_w;
}
We wait for the size of the modal to be set because cropme must be set with specific viewport dimensions. At the end of our shown.bs.modal handler, we create our Cropme instance.
4. After clicking "Crop", the user is presented with the cropped image, and can decide to save the image or to cancel.
Here is the save-button handler:
$('#imgModal-btnSave').on('click', function(){
uploadImage(croppedImg[0], function(path_to_saved) {
savedImg[0].src = path_to_saved;
$('#imgModal-dialog').modal('hide');
});
});
The uploadImage function goes like this:
uploadImage: function(img, callback){
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture (needed??)
imgCanvas.width = img.width;
imgCanvas.height = img.height;
// Draw image into canvas element
imgContext.drawImage(img, 0, 0, img.width, img.height);
var dataURL = imgCanvas.toDataURL();
$.ajax({
type: "POST",
url: "save-img.php", // see code at the bottom
data: {
imgBase64: dataURL
}
}).done(function(resp) {
if (resp.startsWith('nok')) {
console.warn('got save error:', resp);
} else {
if (callback) callback(resp);
}
});
}
It is matched with a simple PHP script which appears at the end of the HTML in the codepen. I think this answer went too long, so I'll finish here.
Good luck - have fun :)

Div to image with jQuery/JavaScript

I am trying to convert div to image using html2canvas library. I tried but no success can't convert full div to image, the dropper is missing in image.
URL: https://www.makethatvape.com/ejuicecalc/
Tried with code:
html2canvas($("#widget")).then(function(canvas) {
bimg = canvas.toDataURL(); // by default png
});
So, any idea how to overcome this problem. I played with html2canvas and it work for text and CSS div to canvas conversion.
Try this
<div id="copyDiv"></div>
var element = $("#widget"); // global variable
var getCanvas; // global variable
html2canvas(element, {
onrendered: function (canvas) {
$("#copyDiv").append(canvas);
getCanvas = canvas;
}
});
Note: If HTML markup contains an image tag, then for some browsers the above code will not be able to create the image of it. To make this work you need to use 2 parameters i.e. allowTaint, useCORS
Sample code :
html2canvas(document.getElementById("html-content-holder"), {
allowTaint: true, useCORS: true
}).then(function (canvas) {
var anchorTag = document.createElement("a");
document.body.appendChild(anchorTag);
document.getElementById("previewImg").appendChild(canvas);
anchorTag.download = "filename.jpg";
anchorTag.href = canvas.toDataURL();
anchorTag.target = '_blank';
anchorTag.click();
});
Detail Article: Convert HTML to image using jQuery / Javascript with live demos
Simpler way to do it:
var convertMeToImg = $('#myDiv')[0];
html2canvas(convertMeToImg).then(function(canvas) {
$('#resultsDiv').append(canvas);
});
https://html2canvas.hertzen.com/getting-started

Convert Canvas to image then download

I am trying to convert a section of my site into a downloadable image.
Firstly I convert the html to a canvas using:
$(function() {
$("#download").click(function() {
html2canvas($("#the-grid"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
$("#saved").append(canvas);
$("#saved canvas").attr('id', 'scan');
}
});
Which works fine the canvas get generated and all look's good.
I then want to turn that into an image which I can use for thumbnails later but also initiate a download of the image.
To do so I complete the function like this.
$(function() {
$("#download").click(function() {
html2canvas($("#the-grid"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
$("#saved").append(canvas);
$("#saved canvas").attr('id', 'scan');
var c=document.getElementById("scan");
var d=c.toDataURL("image/png");
var w=window.open('about:blank','Download Mix');
w.document.write("<img src='"+d+"' alt='Custom Blend'/>");
}
});
But it doesn't work.
The error's I get are totally irrelevant.
I am an experienced developer but I'm pretty new to Jquery so any help would be appreciated.
UPDATE
Got it to work.
Create image like this
$(function () {
$("#download").click(function () {
html2canvas($("#the-grid"), {
onrendered: function (canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
$("#saved").append(canvas);
$("#saved canvas").attr('id', 'scan');
var image = canvas.toDataURL("image/png");
$("#saved").append("<img src='"+image+"' alt='Custom Blend'/>");
}
});
image html ends up looking like
<img src="data:image/png;base64,iVBORw0KGgoAAAANS..." alt="Custom Blend">
Maybe this can help you :
var image = canvas.toDataURL("image/png"); // build url of the image
window.location.href=image; //activate download
image = "<img src='"+image+"'/>"; // set canvas image as source
Here's how I did this (note, there's no way to download a file in Safari and set the filename without pinging a server):
First, you need to get the canvas as a png: var img = canvas.toDataUrl('image/png');
Then, you'll want to convert that dataURL to a blob. For a good way to do that, see this function.
Now you want to download that blob. This will work in all browsers but Safari:
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob, 'image.png');
} else {
var url = window.URL || window.webkitURL;
var objectURL = url.createObjectURL(blob);
var ele = $('<a target="_blank"></a>')
.hide()
.attr('download', 'image.png')
.attr('href', objectURL);
$('body').append(ele);
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false,
});
ele[0].dispatchEvent(clickEvent);
window.setTimeout(function() {
url.revokeObjectURL(objectURL);
ele.remove();
}, 1000);
}
This creates an invisible link and simulates a click on it. The click() function won't work in Firefox, so you have to create an event and dispatch it by hand. Finally, it does a bit of clean up by removing the invisible link after one second. In IE, it uses the method provided by Microsoft. This will download the image with the filename "image.png". It also has the benefit of being able to download any blob, if you need to be able to do more with your code. Hopefully this helps!

Change image size without losing quality via html2canvas

I take screenshot of the div via html2canvas. I want to change the size of caption div but without losing quality.
Here is my code example:
$(".meme-submit").on('click',(function() {
html2canvas($(".meme-img-upload"), {
onrendered: function(canvas) {
var extra_canvas = document.createElement("canvas");
extra_canvas.setAttribute('width',canvas.width*3);
extra_canvas.setAttribute('height',canvas.height*3);
var ctx = extra_canvas.getContext('2d');
ctx.drawImage(canvas,0,0,canvas.width, canvas.height,0,0,canvas.width*3,canvas.height*3);
$("#img_val").val(extra_canvas.toDataURL("image/png"));
document.getElementById("upload-meme").submit();
}
});
}));
Is someone have idea?

create screenshot of webpage using html2canvas (unable to initialize properly)

I am attempting to use http://html2canvas.hertzen.com/ to take screenshots of my webpage. I am unable to initialize a canvas element using...
var canvas = $('body').html2canvas();
If I were able to get a proper canvas I would follow with something like
var dataUrl = canvas.toDataURL(); //get's image string
window.open(dataUrl); // display image
Unfortunately, the documentations is very limited IMO. http://html2canvas.hertzen.com/documentation.html . I do not believe I need to preload as I am not using any dynamic graphics(but am not even getting that far anyways)
I am simply too noob to understand if this guy is having success with screen capturing using html2canvas
I don't seem to be getting any farther than this fellow..
How to upload a screenshot using html2canvas?
My ideal solution would demonstrate how to create screenshot with minimal code. (Copy html to canvas. get toDataURL string. output string)
ANY insight is GREATLY appreciated =)
You should use it this way:
$('body').html2canvas();
var queue = html2canvas.Parse();
var canvas = html2canvas.Renderer(queue,{elements:{length:1}});
var img = canvas.toDataURL();
window.open(img);
It took me few hours to figure it out, how to use it the right way.
The {elements:{length:1}} is required, due to incomplete implementation of the plugin, otherwise you'll get an error.
Good luck!
You could also use the following:
var html2obj = html2canvas($('body'));
var queue = html2obj.parse();
var canvas = html2obj.render(queue);
var img = canvas.toDataURL();
window.open(img);
To just get a part of the page you can use it this way:
$('#map').html2canvas({
onrendered: function( canvas ) {
var img = canvas.toDataURL()
window.open(img);
}
This is what worked for me.
html2canvas(document.body, {
onrendered: function(canvas) {
var img = canvas.toDataURL()
window.open(img);
}
});
This created a new window for the screenshot.
I only wanted a portion of my page in the screenshot, specifically a container div. So I did the following:
html2canvas($('#myDiv'), {
onrendered: function(canvas) {
var img = canvas.toDataURL()
window.open(img);
}
});
For people looking up the same question, if the above options don't help, hopefully this will.
You can use the following code to capture a screenshot and download the screenshot.
html button creation
<button class="btn btn-default btn-sm" style="margin:0px 0px -10px 970px; padding:2px 4px 1px 4px" onclick="genScreenshot()"><span class="glyphicon glyphicon-envelope"></span></button>
<a id="test"></a>
<div id="box1"></div>
function definition
<script type="text/javascript">
function genScreenshot() {
html2canvas(document.body, {
onrendered: function(canvas) {
$('#box1').html("");
if (navigator.userAgent.indexOf("MSIE ") > 0 ||
navigator.userAgent.match(/Trident.*rv\:11\./))
{
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob,'Test file.png');
}
else {
$('#test').attr('href', canvas.toDataURL("image/png"));
$('#test').attr('download','screenshot.png');
$('#test')[0].click();
}
}
});
}
</script>
note: I have created a html button where I have called the function. test is an attribute and box1 is to get the canvas elements.
I have try this way and it working fine for me, you can try this one also.
https://github.com/vijayowork/screenshot-of-div-using-javascript.
I using domtoimage method.

Categories