修复从svg+html5画布生成的base64 png文件的最大大小



问题出在这里,

我使用svg编辑器,用户可以处理大小"无限"的svg文件……但有时,我需要将svg文件转换为png图像。

问题是,对于较大的大小,png文件会变得太大。(>2Mo已经太大了)

我需要在某个地方设置我的png文件的最大大小。这个文件只用于打印a3页或a4页的图像,所以我真的不需要大分辨率。

以下是我如何从svg:中获取png文件

1.构建png文件的代码:

/*
svgContents -> is the whole svg code
name -> is the name of the output file
w -> the width i get from the svg container tag
h -> the height i get from the svg container tag
callback... (returns my conversion result, the file url)
*/
function buildPngFile(svgContents,name,w,h,callback){
var contents = svgContents;
var fname = name;
var myCanvas = document.getElementById("canvas");
myCanvas.setAttribute("width",w);
myCanvas.setAttribute("height",h);
var myCtxt = myCanvas.getContext("2d");
myCtxt.fillStyle="#FFFFFF";
myCtxt.fillRect(0,0,w,h);
drawInlineSVG(myCtxt,contents,function(){
$.ajax({ 
type : 'POST',
cache : false,
url : './createPngFile.php',
data : {'dataPng':myCanvas.toDataURL(),'map':map},
dataType : 'json',
error : function(response){
console.log("ERROR : "+response+"responsetext : "+response.responseText+"json : "+JSON.stringify(response));
},
success : function(response){
callback(response);
}
});
});
}

我认为手动设置,在上面的代码中,宽度&我画布的高度可以解决这个问题,但一点也不能。如果我修复它(例如1280/720),它只显示svg图像中与这些值相对应的部分。所以我在png文件上只得到了svg的一部分。这不起作用。

2.drawInlineSvg功能

function drawInlineSVG(ctx, rawSVG, callback) {
var svg = new Blob([rawSVG], {type:"image/svg+xml;charset=utf-8"}),
domURL = self.URL || self.webkitURL || self,
url = domURL.createObjectURL(svg),
img = new Image();
img.onload = function () {
ctx.drawImage(this, 0, 0);     
domURL.revokeObjectURL(url);
callback(this);
}
img.src = url;
}

这只是将svg绘制到画布中。。。

3.createPngFile.php

$name = $_POST['map'];
$data = $_POST['dataPng'];
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$file = fopen($_SERVER['DOCUMENT_ROOT'].'/png/'.$name.'.png','w');
fwrite($file,base64_decode($data));
fclose($file);
echo json_encode($_SERVER['DOCUMENT_ROOT'].'/png/'.$name.".png");

这将返回png文件的url。所有这些代码都运行良好,我需要的是将我的png图片大小限制在定义的最大宽度或最大高度,以避免获得超过2Mo的巨大.png文件(例如)

感谢阅读/帮助:)

您需要在调用ctx.drawImage(this, 0, 0);中提供其他参数

重用drawImageScaled函数中的逻辑,从缩放添加到画布的图像来缩放图像

最新更新