How to convert a block of rendered HTML code or a div into a PNG?
A few notes:
a) not an entire page, b) not from server side. c) rendered or "treated" HTML, for instance,
<table>
<tr><td width="5%"> <td>fact 1 </td> fact 2 </td> </tr>
</table>
desired results (for the PNG):
fact 1 fact 2
fact 3 fact 4
...
not
fact 1 fact 2
fact 3 fact 4
...
The <code> "sign开发者_StackOverflow"nbsp; </code> may be used to create white space but again it needs to be rendered.
Probably some javascript that first acts a ua (browser) to get the rendered data first and then transforms it into a bmp format that PNG supports... how? code sample would be much appreciated.
Many thanks.
What's wrong with generating it server-side?
EDIT: What's wrong with just using html+css? For the user it looks the same, prints the same AND it's faster, searchable and accessible AND you can easily manipulate it with Javascript. I fail to see why you would want to have the images in the first place.
This question's short answer is the same as from the other post: No, you cannot. There are many problems you have to overcome, including but not limited to:
You would need to correctly render HTML into a bitmap. This is infinitely more difficult than it seems.
Compressing an image using PNG is not trivial, and while it's technically possible to do that with JS, it's definitely a very bad idea.
Even if you somehow manage to get around these problems, you will end up with hacky and extremely brittle code that have nearly no chance of working cross-browser.
Doing this would be like needing some concrete and developing a Moon rocket to harvest lunar dust to make it instead of buying some at Home Depot.
- ceejayoz, on a similar topic
There are however alternatives (SVG, Canvas, server-side generation, ...) you might want to look at.
EDIT 2: Here's an example of images loaded directly from the HTML file
I used PHP to base64_encode those images. Here's the source:
<script type="text/javascript">
var i = 0;
var imgs = [];
<?php
$imgArray = array('angry.gif', 'pray.gif', 'think.gif');
$imgs = array_map(function ($d) {return base64_encode(file_get_contents($d));}, $imgArray);
$i=0;
foreach ($imgs as $img) {
echo 'imgs[' . $i++ . '] = "' . $img . "\";\n";
}
?>
function changeImg() {
i = (i+1) % imgs.length;
var img = document.getElementById('theImage');
img.src = 'data:image/gif;base64,' + imgs[i];
}
</script>
<body onload="changeImg()">
<input type="button" onclick="changeImg();" value="Change Image" /><br /><br />
<img src="" id="theImage" alt="" />
精彩评论