//生成svg
DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
SVGDocument doc = (SVGDocument) domImpl.createDocument(svgNS, "svg", null);
// Create a converter for this document.
SVGGraphics2D g2d = new SVGGraphics2D(doc);
// get the root element (the svg element)
Element svgRoot = doc.getDocumentElement();
// set the width and height attribute on the svg root element
svgRoot.setAttributeNS(null, "width", "500");
svgRoot.setAttributeNS(null, "height", "600");
Element group = doc.createElementNS(svgNS, "g");
Element rect = doc.createElementNS(svgNS, "rect");
rect.setAttributeNS(null, "x", "0");
rect.setAttributeNS(null, "y", "0");
rect.setAttributeNS(null, "width", "100%");
rect.setAttributeNS(null, "height", "100%");
group.appendChild(rect);
//插入背景图
Element image = doc.createElementNS(svgNS, "image");
image.setAttributeNS(null, "xlink:href", ImageToBase64Util.getPrefix(back) + base64str);
image.setAttributeNS(null, "x", "0");
image.setAttributeNS(null, "y", "0");
image.setAttributeNS(null, "width", String.valueOf(styleInnerPO.getWidth()));
image.setAttributeNS(null, "height", String.valueOf(styleInnerPO.getHeight()));
group.appendChild(image);
//插入文本
Element textE = doc.createElementNS(svgNS, "text");
textE.setAttributeNS(null, "style", "fill:#000000;text-anchor: middle;font-size:50px;font-family:SimHei;");
textE.setAttributeNS(null, "x", 100);
textE.setAttributeNS(null, "y", 200);
textE.setTextContent(text);//text 是传进来的中文字符
group.appendChild(textE);
ImageTranscoder transcoder = new JPEGTranscoder();
TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(baos.toString().getBytes("utf-8")));
// Create the transcoder output
ByteArrayOutputStream baos_1 = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(baos_1);
//转换
transcoder.transcode(input, output);
DateFormat format = new SimpleDateFormat("yyyyMMdd");
String date = format.format(new Date());
String fileName = UUID.randomUUID().toString() + ".jpg";
//上传华为云OBS
String url = huaweiObsService.pushObject(date, fileName, new ByteArrayInputStream(baos_1.toByteArray()));
这段程序在本地(ubuntu系统)跑起来转换正常,在华为云服务器上转换图片显示正常,但是图片上的文字乱码。
如下图
tomcat远程debug了,发现text是中文,转换成svg xml code也是正常的中文。
猜测是jpg的生成代码跟系统的字符集有关。是不是华为云的系统字符集没有中文字体导致这个问题的?
安装中文支持包language-pack-zh-hans:
sudo apt-get install language-pack-zh-hans
修改/etc/environment(在文件的末尾追加):
LANG="zh_CN.UTF-8"
LANGUAGE="zh_CN:zh:en_US:en"
再修改/var/lib/locales/supported.d/local(没有这个文件就新建,同样在末尾追加):
en_US.UTF-8 UTF-8
zh_CN.UTF-8 UTF-8
zh_CN.GBK GBK
zh_CN GB2312
执行命令:
sudo locale-gen
对于中文乱码是空格的情况,安装中文字体解决。
sudo apt-get install fonts-droid-fallback ttf-wqy-zenhei ttf-wqy-microhei fonts-arphic-ukai fonts-arphic-uming
再次请求转换正常了,如下图