html2canvas loading issue when saving the image - html2canvas

I am using the following code to save the content of div (image and text) as an image using html2canvas.
$(function() {
$("#save").click(function() {
var flag = true;
var imgpath = document.getElementById('file').value;
if(imgpath.length == 0)
{
alert('Please select image file to upload.');
flag = false;
}
else
{
html2canvas($('.body740'), {
onrendered: function(canvas) {
theCanvas = canvas;
var url = canvas.toDataURL("image/png");
var br = document.createElement("br");
var center = document.createElement("center");
var newImg = document.createElement("img"); // create img tag
newImg.src = url;
$(".body740").hide();
$("#canvas").show(); //div where the final image is shown
document.getElementById("rsimg").src=url;
document.getElementById("rsa").href=url;
}
});
}
});
});
This is my link : http://www.aamras.com/greetings2/
But, when I click the save image button, it takes a lot of time to generate the image. Why is it taking so much time to load? What is the issue?

Solved : Change the version of html2cannvas. I was previously using html2canvas 0.5.0-alpha 2014 version
I Switched to html2canvas 0.5.0-alpha1. It generates the image properly and takes no time to do so. You can download the files from https://github.com/niklasvh/html2canvas/releases

Related

quality problem with html2canvas and jscharts

I have been searching and testing for hours and cant seem to find a solution. I need to convert a html div with a jschart to an image. I am using the below code to create the image but the quality is very low. I am using version 0.4.1, for some reason the newest version of html2canvas is not working..
Anybody found a solution to this?
function saveAsImage() {
var $wrapper = $("#ReportContainer");
html2canvas($wrapper, {
onrendered: function(canvas) {
var link = document.createElement('a');
link.href = canvas.toDataURL('image/jpeg');
link.download = 'myChart.jpeg';
link.click();
}
});
}

Ionic 3 image broken when save without run livereload

I get base64 string from take picture by camera. After that I save it into externalRootDirectory, everything works fine when I use ionic cordova run android -l -c.
But when I use ionic cordova run android the image file was broken.
This is my code:
b64toBlob(b64Data, contentType, sliceSize) {
var contentType = contentType || '';
var sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''));
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: contentType});
}
savebase64AsFile(folderPath, fileName, base64, contentType){
var DataBlob = this.b64toBlob(base64,contentType,512);
this.file.writeFile(folderPath, fileName, DataBlob).catch(e => console.log('File didn\'t save: ' + e.message));
}
saveImage(){
this.savebase64AsFile(folderPath, nameFile, base, this.image.type);
}
What you are experiencing is a problem with the Content Security Policy. When you load with live-reload it's like a web, but without it load like a direct file and then need some policy to load some contents.
Try adding this in index.html
<meta http-equiv="Content-Security-Policy" content="img-src: 'self' blob: ;"/>
Check this links for any other load resource problem:
Whitelists
Content-security-policy refused to load image
I make a test project and I can get the blob load into a img from a url with this way:
Make a new pipeline class
#Pipe({name: 'safeBlob'})
export class SafeBlob{
constructor(private sanitizer:DomSanitizer){}
transform(html) {
return this.sanitizer.bypassSecurityTrustResourceUrl(html);
}
}
Then in your img:
<img [src]="imageInBlobObjectUrl | safeBlob" alt="Blob image">
Angular2 Base64 sanitizing unsafe URL value

tinyMCE editor setting localised path as src of uploaded image

I've setup tinyMCE to do image uploading and it displays uploaded images in the editor, but on inspecting the source of the editors HTML I can see that the src attribute is set like it would be a file path:
<img src="../../../api/images/1"/>
I have a file_picker_callback which POSTs the image to my backend server to save the image, and returns an absolute URL in the "location" key as specified in the tinyMCE docs: https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_url
But I am unsure why regardless of providing an absolute URL the src set on the image begins with "../../../".
The relevant tinyMCE configuration:
tinymce.init({
file_picker_types: 'file image',
file_picker_callback: function(cb, value, meta) {
let tinyMCE = this;
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*,.doc,.docx,.txt,.rtf,.odt,.pdf');
input.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function () {
// Register the blob in TinyMCEs image blob registry.
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinyMCE.editorUpload.blobCache;
var base64 = reader.result.split(',')[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
backend.save(file).then(
fileLocation => {
let options = {};
if (meta.filetype == 'file') {
options = {
title: file.name,
text: 'My Attachment'
};
}
cb(fileLocation, options);
},
(/* error */) => {
blobCache.removeByUri(blobInfo.blobUri());
}
);
};
reader.readAsDataURL(file);
};
input.click();
}
});
I can see that there is an options object I can pass to the callback which sets some element attributes of the image, but I can't find a reference to what this object can contain in the docs :(
Would like some help to solve this and get absolute URLs in my image srcs, thanks
convert_urls: false,
By default all URLs are automatically converted to relative URLs. If you want to insert the real URL of the uploaded image, set convert_urls option to false. It will restore URLs to their original values.

html2canvas toDataURL(image/png") return poor image quality

I tried to use html2canvas to get image screenshot byte from website. However, the screenshot result ended with poor resolution. Looking for advice to improve screenshot quality. Thanks.
How about something like this:
var $wrapper = $("#yourDiv");
setSize($wrapper, "2000px", "20pt");
html2canvas($wrapper, {
onrendered: function (canvas) {
var a = document.createElement('a');
a.href = canvas.toDataURL("image/jpg");
a.download = 'filename.jpg';
a.click();
setSize($wrapper, "1000px", "10pt");
}
});
function setSize(dv, width, fontsize) {
dv[0].style.width = width;
dv[0].style.fontSize = fontsize;
}
This resizes the div and font to bigger size and then shrinks back afterwards.

Preload Images for Photoswipe Gallery

So I have an array of images I want to load into a gallery using Photoswipe, but I'm having trouble predefining the image width and height. Specifically, I think I need to preload the images
Here's my JS to render the page, here I'm defining slides and listing as a local variable for the ejs page to use:
var sizeOf = require('image-size');
var url = require('url');
var http = require('http');
var slideshow = [];
for(var i = 0; i < listing.listing_images.length; i++) {
var image = listing.listing_images[i];
var width, height = 0;
var imgUrl = image.url;
var options = url.parse(imgUrl);
http.get(options, function (response) {
var chunks = [];
response.on('data', function (chunk) {
chunks.push(chunk);
}).on('end', function() {
var buffer = Buffer.concat(chunks);
**height = sizeOf(buffer).height;
width = sizeOf(buffer).width;**
});
});
var item = {
src: image.url,
h: height,
w: width
};
slideshow.push(item);
}
res.render('example.ejs', {
listing: listing,
slides: slideshow
});
And here is the script in the ejs page :
<% var slides = locals.slides %>
<script>
$('document').ready(function() {
var pswpElement = document.querySelectorAll('.pswp')[0];
// build items array using slideshow variable
var items = <%- JSON.stringify(slides) %>;
console.log(items);
// grab image
if (items.length > 0) {
// define options (if needed)
var options = {
// optionName: 'option value'
// for example:
index: 0 // start at first slide
};
// Initializes and opens PhotoSwipe
var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
}
</script>
Basically what's happening is the array of photoswipe items is being passed in fine, but the width and height aren't set until photoswipe initializes and triggers the img to load. So the images don't show, because their height and width aren't set yet.
Is there a way to trigger the loading of the images in the slideshow array so that the width & height are set before passing to Photoswipe? I've also tried seeing if I could just set them initially to 0, and then try and update the height and width later and try to force photoswipe to reload, but photoswipe doesn't recognize the image's new height/width.
Sorry if any of this is unclear/muddled with ejs nonsense, feel free to ask anything and I'd love to clarify.
Thanks
Ended up solving this leveraging the API:
gallery.listen('gettingData', function(index, item) {
// index - index of a slide that was loaded
// item - slide object
var img = new Image();
img.src = item.src;
item.h = img.height;
item.w = img.width;
});
gallery.invalidateCurrItems();
// updates the content of slides
gallery.updateSize(true);
If anyone happens to be reading this and there's a better way to read image size without creating a new img, or optimize this I'd love suggestions. :)