convert svg to png lost fill pattern images - javascript

I am generating an svg with dynamically filled images as patterns. When I export this to png, I get a blank svg without any fill images. I have tried javascript as well as c# code.
Javascript code:
var svg = document.querySelector('#element3 svg');
var data1 = (new XMLSerializer()).serializeToString(svg);
var encodedData = window.btoa(data1);
var data = 'data:image/svg+xml;base64,' + encodedData;
image.src = data;
$('[id$=objimage]').attr('data', data);
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
var a = document.createElement('a');
a.download = "image.png";
a.href = canvas.toDataURL('image/png');
document.body.appendChild(a);
a.click();
C# code:
var byteArray = Encoding.ASCII.GetBytes(input.ImageData);
using (var stream = new MemoryStream(byteArray))
{
var svgDocument = SvgDocument.Open(stream);
var bitmap = svgDocument.Draw();
bitmap.Save(HttpContext.Current.Server.MapPath("~/Images/Pattern/UserPattern/testimg.png"), ImageFormat.Png);
}
Can anyone please help in this?

Related

Convert s3 Image to Canvas

Code:
var myCanvas = document.createElement('canvas');
myCanvas.width = 596;
myCanvas.height = 350;
var ctx = myCanvas.getContext('2d');
var img = new Image();
img.crossOrigin = "Anonymous";
img.src = url;
img.onload = function(){
ctx.drawImage(img,0,0);
};
let dt = myCanvas.toDataURL('image/jpg');
var aLink = document.createElement('a');
aLink.href = dt;
aLink.download = 'fixed_photo.jpg';
aLink.click();
Result:
It Downloads an empty Canvas instead of the image from the url. my guess it has something to do with s3 permission, i am using the getObject of S3 aws-sdk.
Try opening the developer tools in your web browser and check the network tab. It should let you know if the request failed and the status code.

jsPDF addImage not working

I am using jsPDF to create a PDF by looping through some HTML code to find the values it needs. I am able to get the values just fine, but when I try to insert the header_img it does not work. I have found many solutions on Google but the one I am working with now is the only one that does not throw an error.
This is the code being used to get take the url that is provided via the loop, convert it to a DataURL, and then insert the image into the PDF. It does not give me any errors, but all that is in the PDF is the black border and no image. Any ideas?
function getDataUri(url, cb) {
var image = new Image();
image.setAttribute('crossOrigin', 'anonymous'); //getting images from external domain
image.onload = function () {
console.log(url);
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
//next three lines for white background in case png has a transparent background
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff'; /// set white fill style
ctx.fillRect(0, 0, canvas.width, canvas.height);
canvas.getContext('2d').drawImage(this, 0, 0);
cb(canvas.toDataURL('image/jpeg'));
};
image.src = url;
}
var pdf = new jsPDF('p', 'in', 'letter');
var left_margin = .5;
var top_margin =.5;
var height = 2.313;
var width = 3.25;
var header_img_height = 1;
//Draw border
pdf.setLineWidth(1/92);
pdf.setDrawColor(0, 0, 0);
pdf.rect(left_margin, top_margin, width, height);
//example image
var header_img = 'http://www.quotehd.com/imagequotes/authors24/jeff-olsen-quote-two-clicks-and-its-broke.jpg';
let logo = null;
//callback to get DataURL
getDataUri(header_img, function(dataUri) {
logo = dataUri;
console.log("logo=" + logo);
//Add image to PDF
pdf.addImage(logo, 'JPEG', left_margin, top_margin, header_img_height, width);
});
pdf.output('save', 'test.pdf');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.debug.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I ended up solving the issue by writing a PHP script that would convert the image to Base64.
$img_src = urldecode($_GET['url']);
$img_str = base64_encode(file_get_contents($img_src));
echo 'data:' . getimagesize($img_src)['mime'] . ';base64,' . $img_str;
Then using jQuery, I passed the url to the PHP script and got the Base64 data in return:
function getBase64(url) {
var out = '';
$.ajax({
url: 'get-dataurl.php?url=' + encodeURI(url),
async: false,
dataTye: 'text',
success: function(data) {
out = data;
}
});
return out;
}
Certainly was not ideal, but it works.
You can encode the image to base64, you would use this tool or any similar and replace it on your code.

Creating and saving to file new png image in JavaScript

I am trying to create new empty image with width and height and save it as png to file.
This is what i got:
var myImage = new Image(200, 200);
myImage.src = 'picture.png';
window.URL = window.webkitURL || window.URL;
var contentType = 'image/png';
var pngFile = new Blob([myImage], {type: contentType});
var a = document.createElement('a');
a.download = 'my.png';
a.href = window.URL.createObjectURL(pngFile);
a.textContent = 'Download PNG';
a.dataset.downloadurl = [contentType, a.download, a.href].join(':');
document.body.appendChild(a);
I am trying to get transparent image with given width and height in var myImage new Image(200, 200) as the output on the download.
The Image element can only load an existing image. To create a new image you will have to use canvas:
var canvas = document.createElement("canvas");
// set desired size of transparent image
canvas.width = 200;
canvas.height = 200;
// extract as new image (data-uri)
var url = canvas.toDataURL();
Now you can set url as href source for the a-link. You can specify a mime-type but without any it will always default to PNG.
You can also extract as blob using:
// note: this is a asynchronous call
canvas.toBlob(function(blob) {
var url = (URL || webkitURL).createObjectURL(blob);
// use url here..
});
Just be aware of that IE does not support toBlob() and will need a polyfill, or you can use navigator.msSaveBlob() (IE does neither support the download attribute so this will kill two birds with one stone in the case of IE).
Thank you K3N for replying to my question but i did not have time to wrap my head around your answer.
Your answer was just what i needed!
Here is what i got:
var canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 200;
var url = canvas.toDataURL();
var a = document.createElement('a');
a.download = 'my.png';
a.href = url;
a.textContent = 'Download PNG';
document.body.appendChild(a);
var canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 200;
var url = canvas.toDataURL();
var a = document.createElement('a');
a.download = 'my.png';
a.href = url;
a.textContent = 'Download PNG';
document.body.appendChild(a);

Issue Textpath svg to png

I'm working on an SVG graphic export (with d3.js library) to PNG. The problem is the label textPath. When exporting to PNG, the text does not appear. Does anyone know if there is solution for this problem?
The code I'm using to do the conversion is:
var svgString = new XMLSerializer().serializeToString(document.querySelector('#svg'));
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
var png = canvas.toDataURL("image/png");
var a = document.createElement("a");
a.download = "grafico.png";
a.href = png;
a.click();
DOMURL.revokeObjectURL(png);
};
img.src = url;
Thank you very much to all.
A greeting,
Sonia
Fixed. I've solved with attributes in the css style-sheet such as:
font-size: 16px;
color: black;
fill: none;
Same issue here. It seems that this method of conversion is not getting the body's font-size. However, dumping the generated SVG into a .svg file and opening that file in the browser renders correctly.

Resize the canvas output image to a specific size (width/height)

I have a big canvas (5000x5000) and I want to take a picture of it and create a thumbnail on client side. I can capture the image using canvas.toDataURL but how do i re-size it? Do i have to create an new $("<canvas></canvas>") element and then put that image inside and run the canvas2.toDataURL(); Can anyone help me with this? I can't get my head around it how to do it.
var canvas = document.getElementById("main");
var ctx = canvas.getContext("2d");
var tumbnail64 = null;
var image = new Image();
image.src = canvas.toDataURL();
image.onload = function() {
$c2 = $("<canvas></canvas>");
$c2[0].width=100;
$c2[0].height=100;
$c2[0].getContext("2d");
$c2[0].drawImage(image, 0, 0,100,100);
tumbnail64 = $c2[0].toDataURL();
};
Something like this should work, given you don't have security restrictions on the original canvas element:
var resizedCanvas = document.createElement("canvas");
var resizedContext = resizedCanvas.getContext("2d");
resizedCanvas.height = "100";
resizedCanvas.width = "200";
var canvas = document.getElementById("original-canvas");
resizedContext.drawImage(canvas, 0, 0, 200, 100);
var myResizedData = resizedCanvas.toDataURL();

Categories

Resources