React native - Convert HTML to PNG and download Base64 - html

I develop a project that able to make a self-graphic image and download it to the computer, but I stack in big problem.
I don't know where is exactly my problem, but it happened when I try to download the image on a different screen.
Suppose that the user make this graphic
when I try to download it on the 27' screen it's like the image above, On the other hand on the 14' screen is looks like this.
Edited: another issue, right now I work on 2 screens left 27' and right is the 14', on left screen download the image clearly and when I drag the window (without change window size) to another screen (14') it's again downloaded it smaller.
const onDownloadImage = () => {
var node = document.getElementById("section");
htmlToImage
.toPng(node)
.then(function (base64) {
let encoded = base64?.split(",");
setBase64(encoded[1]);
triggerBase64Download(base64, "My Canvas");
hideEditElements(false);
})
.catch(function (error) {
console.error("oops, something went wrong!", error);
});};
the library I used :
html-to-image to get the elements by id and convert them to base64.
and react-base64-downloader to download the base64 image.
Thanks all !!

Related

Limit the size (bytewise) of an image loaded with the <img> tag

The initial problem: I want that the users of my future webserver can use an avatar.
The initial solutions (and their problems)
Let the user upload his own image and save it
the pro here is that I might limit from the start the size of the image
the problem, instead, even if no one seems to care too much, is legal: not sure how it works in other countries, but here you might be considered liable for what you store on your hdd, in some cases (which I won't list, but that you might guess). This means that if someone uploads an illicit image as his avatar on your server and then this is reported to the authorities, you might find yourself in some kind of trouble, which, depending from the examining magistrate, might easily lead to the server going under requisition for months, for "further investigations".
And here we came with the second idea: let the user define and save a link to an image, for his avatar
pro: legally safe
cons: what if the user defines a link to a 100MB image, which then all the users might be forced to download to see the page?
So the question is: is there a way to "say" to the browser that when it sees:
<img src='http://external.jpg' ...>
external.jpg size is supposed to be limited to, say, 100KB? And to drop the loading of it, if it goes over that size?
With this function you can get the file size and determine what to do from there. Also you can use an API like Clarifai to check for illicit content if you want to store it on your HDD.
function get_filesize(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("HEAD", url, true); // Notice "HEAD" instead of "GET",
// to get only the header
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(parseInt(xhr.getResponseHeader("Content-Length")));
}
};
xhr.send();
}
get_filesize("URLHERE", function(size) {
alert("The size of foo.exe is: " + size + " bytes.");
});
Source: Ajax - Get size of file before downloading

Is it possible to recalculate the `srcset` image used if browser window is resized?

Is it possible to get srcset to recalculate the browser window size once the page has loaded, and thus update the image its using.
The reason you'd want to do this is because if on a desktop you have your browser window compressed, load a site, then make the browser window bigger, it will just scale the "small.jpg" (as set in the srcset) so the user will end up with a pixilated image.
I started make a jsfiddle to show the issue, but it dosnt work well, as i think srcset is calculated by the browser window, rather than the jsfiddle results grid.
If you are interested you can copy and paste below this into a blank html file and run it in a localserver (must be on a local http:// server so you can view the network debugging tab to see which image the browser has loaded). Running it in the browser via the file url using file:/// wont allow you to see which image is loaded via the network debugging tab.
<body>
<div class="wrapper">
<img
src="http://i.imgur.com/DoWeH0X.jpg?1"
srcset="http://i.imgur.com/QV9vace.jpg?1 1400w, http://i.imgur.com/ZqkR6Bk.jpg?1 800w, http://i.imgur.com/gltBZ06.jpg?1 300w"
alt="#"
>
</body>
</html>
You can use
var img = document.getElementById('resizeMe');
window.onresize = function() {
img.outerHTML = img.outerHTML;
}
Which will cause the HTML to be sent through the parser again, causing the browser to reload the image according to the srcset.
Of course you should probably include some logic to detect if the screen size has changed to a size outside of the current range so the image isn't reloaded every single time the user resizes the window slightly.
Or, you could clone the node, insert it before the current node, then remove the old node.
var img = document.getElementById('resizeMe');
window.onresize = function() {
var clone = img.cloneNode(true);
img.parentNode.insertBefore(clone, img);
img.remove();
}
Which will also cause the parse to re-render the html, but will consume more resources.
i found this to force a re-render
var img = document.getElementById('my-element');
img.srcset = img.srcset;

Crafty, adding sprite's

I'm experimenting with HTML5 games and found 'Crafty' API to make HTML5 Games
I looked up the documentation but my sprite's won't show up.
The path to the spritesheet is correct and so are the coordinations, so i should miss something.
Anyone have an idea?
This is my code now, when i open the page i have a blue screen. (Crafty.background)
Crafty.scene('Scene1', function() {
Crafty.background('rgb(150,215,255)');
Crafty.sprite('img/sprites.png',
{introbanner: [0, 0, 100, 100]});
var banner = Crafty.e('2D, DOM, introbanner');
banner.x = 20;
banner.y = 20;
});
Here are 3 things you can try:
Ensure your HTML is loaded from a web server. Locally loaded files have security restrictions when loading in a browser. If you see file: in your address bar, move your files onto a server and try again using http:
Try the full path to your image like so:
Crafty.sprite('http://www.domain.com/img/sprites.png',
Open up the developer console and see if the image is even being requested by your browser.

Twitter Bootstrap Image Gallery - creating automatic thumbnails

I thought the thumbnail component of Bootstrap automatically took an image, and cut out a specific size thumbnail to slap on the site. Either I'm using this feature wrong or this is completely false. Everytime I create class="thumbnail", I just get a slightly smaller version of the photo.
As a photographer, my photos are huge, and the "thumbnails" are taking up half the page! Certainly I could resize everything in Photoshop to a 200X200px size and upload these as thumbnails, but I feel like there must be a beter way of doing this.
I tried in the html itself just putting width="200" and height="200" after img src, but the problem here is that instead of cutting a 200X200 square out of the image, the image was scaled down proportionally using one dimension. I.e., the image fits in a 200X200 square, but rather than filling up the entire square (since that's not the original proportions), it fills up a 200X100 type area.
Can anyone help?
Bootstrap won't resize your images. It is a CSS framework, it can only add styles to your web page but you can't use it to do any backend work, like thumbnails creation. Setting the dimensions in the HTML img tag doesn't resize your image neither, it is still the same image that is sent to the browser. So in order to boost your website performance, you need to think of another solution, you don't want to send huge images through the network if you're only gonna show them with thumbnail size.
What kind of website are you running?
For example, Wordpress automatically handles the thumbnails creation when you upload files through the Media Manager. I'm pretty sure most of the CMS have this functionnality.
If you have a PHP website without a CMS, you could try using a library such as phpthumb, that would require some coding though.
If you have a static HTML website, then you have no other choice but to resize the images manually in Photoshop.
By the way, do you optimize your images too? (compression with tools such as tinypng or jpeg-optimizer
I've got a little code to generate thumb:
public function generateThumb($pathToImage, $pathToThumb, $extension, $maxDim)
{
//Create a new image according to "MimeType"
switch($extension){
case "gif":
$img = imagecreatefromgif("{$pathToImage}");
break;
case "jpeg":
$img = imagecreatefromjpeg("{$pathToImage}");
break;
case "png":
$img = imagecreatefrompng("{$pathToImage}");
break;
}
// load image and get image size
$width = imagesx($img);
$height = imagesy($img);
// calculate thumbnail size, vertical and horizontal orientation
$new_width = ($width > $height) ? $maxDim : floor($width * ( $maxDim / $height ));
$new_height = ($height > $width) ? $maxDim : floor($height * ( $maxDim / $width ));
// create a new temporary image
$tmp_img = imagecreatetruecolor($new_width, $new_height);
// copy and resize old image into new image
imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// save thumbnail into a file
imagejpeg($tmp_img, "{$pathToThumb}");
}
I'm sorry, but I can't remember where I found the original script (On SO and other website).
Using that you can generate a thumb each time you add a new image and then use this thumb in your thumbnail preview.
Nop, the Bootstrap will not resize files for You.
Even if You're the only user of the site u can make a file-upload form for yourself. Take a look at Paperclip - it's awesome. And do not forget to protect this form to disallow network users upload some ugly images on your site
Bookstrap is not for resizing api. You can use many of the Image Compression apps that are available.
I would recommend http://shrinkjpeg.com since it does not upload the images to server and compresses them locally in browser.

Save a html canvas image

I know there is probably an answer already to this question but I haven't been able to find it yet and there is a deadline on my project.
So I have made an html5 canvas and I would like to be able to do two things with one(or more) buttons.
I would like the user to be able to save what he has just done by clicking on the save button and ideally I would like the image to be downloaded (as opposed to having to right click and "Save image as". This is what I have been able to do so far).
I would also like the image to be saved (maybe to a database? or a server? I don't know how it works) so that a part of the drawing (or all of it, depending on the difficulty of the code) that has been done before is used the next time someone else logs on (not necessarily the same person with the same IP). Is this possible?
I am very new to code and self teaching myself so any extra comments on the code to help me understand would be extra-appreciated.
Regarding the first task, you can export the canvas content to an image with toDataUrl method supported by the canvas object.
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d"); // Get the context for the canvas.
var myImage = canvas.toDataURL("image/png"); // Get the data as an image.
}
var image = document.getElementById("image"); // Get the image object.
image.src = myImage;
As regarding the second task, after you saved the canvas to an image you can upload the resulted image into the database by using an ajax call. Here is a simple example for how to use it:
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
For a full example see these articles:
http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/
http://coursesweb.net/ajax/upload-images
You would probably need to use JavaScript and maybe PHP. I am not proficient in both of those so I can't help you, but you should look up tutorials on how to make a database on your website.
i think you might be interested to have a look on the html5 file api :
http://updates.html5rocks.com/2012/08/Integrating-input-type-file-with-the-Filesystem-API
It would allow you to deal with your issue with no server-side code.
(Rq : this will not solve all your issues.)