WMF EMF SVG PNG Java图片处理

这篇博客介绍了在Java中处理图像,特别是转换难度较高的EMF格式到SVG,以及SVG到PNG的过程。博主分享了使用freehep库进行转换的代码示例,并表示如有需求,读者可以留言联系。
摘要由CSDN通过智能技术生成
代码就示例贴点

工作需要转换难度大的就是EMF的转换了

使用的是freehep包

有需要的话可留言,联系我
EMF2SVG

public class EmfToSVG extends EMFConverter {
public static void main(String[] args) {
String[] file = new String[2];
file[0] = "D:\\input.emf";

if (file == null || file.length == 0 || file[0] == null || file[0].length() == 0) {
System.out.println("usage: EMF2SVG imput.emf [output.svg]");
return;
}
export(ImageConstants.SVG, file[0], file.length > 1 ? file[1] : null);
}

protected static void export(String type, String srcFileName, String destFileName) {
try {
List exportFileTypes = ExportFileType.getExportFileTypes(type);
if (exportFileTypes == null || exportFileTypes.size() == 0) {
System.out.println(
type + " library is not available. check your classpath!");
return;
}

ExportFileType exportFileType = (ExportFileType) exportFileTypes.get(0);

// read the EMF file
EMFRenderer emfRenderer = new EMFRenderer(
new EMFInputStream(
new FileInputStream(srcFileName)));

// create the destFileName,
// replace or add the extension to the destFileName
if (destFileName == null || destFileName.length() == 0) {
// index of the beginning of the extension
int lastPointIndex = srcFileName.lastIndexOf(".");

// to be sure that the point separates an extension
// and is not part of a directory name
int lastSeparator1Index = srcFileName.lastIndexOf("/");
int lastSeparator2Index = srcFileName.lastIndexOf("\\");

if (lastSeparator1Index > lastPointIndex ||
lastSeparator2Index > lastPointIndex) {
destFileName = srcFileName + ".";
} else if (lastPointIndex > -1) {
destFileName = srcFileName.substring(
0, lastPointIndex + 1);
}

// add the extension
destFileName += type.toLowerCase();
}

// TODO there is no possibility to use Constants of base class!
/* create SVG properties*/
Properties p = new Properties();
p.put(SVGGraphics2D.EMBED_FONTS, Boolean.toString(false));
p.put(SVGGraphics2D.CLIP, Boolean.toString(true));
p.put(SVGGraphics2D.COMPRESS, Boolean.toString(false));
p.put(SVGGraphics2D.TEXT_AS_SHAPES, Boolean.toString(false));
p.put(SVGGraphics2D.FOR, "Freehep EMF2SVG");
p.put(SVGGraphics2D.TITLE, srcFileName);

EMFPanel emfPanel = new EMFPanel();
emfPanel.setRenderer(emfRenderer);

// TODO why uses this classes components?!
exportFileType.exportToFile(
new File(destFileName),
emfPanel,
emfPanel,
p,
"Freehep EMF converter");
} catch (Exception e) {
e.printStackTrace();
}
}


WmfToSvg


/**
* @author LiJie
* 将wmf转换为svg格式的
*
*
*/
public class WmfToSvg {
public void converter(byte[] wmfBytes, String dest) throws Exception {
InputStream in = new ByteArrayInputStream(wmfBytes);
WmfParser parser = new WmfParser();
final SvgGdi gdi = new SvgGdi(false);
parser.parse(in, gdi);
Document doc = gdi.getDocument();
OutputStream out = new FileOutputStream(dest);
if (dest.endsWith(".svgz")) {
out = new GZIPOutputStream(out);
}
output(doc, out,dest);
}
public void convert(String file,String dest) throws Exception{
InputStream in = new FileInputStream(file);
WmfParser parser = new WmfParser();
final SvgGdi gdi = new SvgGdi(false);
parser.parse(in, gdi);
Document doc = gdi.getDocument();
OutputStream out = new FileOutputStream(dest);
if (dest.endsWith(".svgz")) {
out = new GZIPOutputStream(out);
}
output(doc, out,dest);
}
public byte[] encodeConvert() {
return null;
}

private void output(Document doc, OutputStream out,String dest) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"-//W3C//DTD SVG 1.0//EN");
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");
transformer.transform(new DOMSource(doc), new StreamResult(out));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(doc), new StreamResult(bos));
out.flush();
out.close();
//将svg直接转为jpg
/*JPEGTranscoder it = new JPEGTranscoder();
ByteArrayOutputStream jpg = new ByteArrayOutputStream();
it.transcode(new TranscoderInput(new ByteArrayInputStream(bos.toByteArray())), new TranscoderOutput(jpg));
String jpgFile=dest.replaceAll("svg","jpg");
FileOutputStream jpgOut=new FileOutputStream(jpgFile);
jpgOut.write(jpg.toByteArray());
jpgOut.flush();*/
}
}


SvgToImg

/**
* @author LiJie
* 将svg转换为jpg,png格式的
*
*
*/
public class SvgToImg {
public void convert2JPEG(String file) throws TranscoderException, IOException {
/*InputStream in = new FileInputStream(file);
JPEGTranscoder transcoder = new JPEGTranscoder();
transcoder.addTranscodingHint(JPEGTranscoder.KEY_XML_PARSER_CLASSNAME,
"org.apache.crimson.parser.XMLReaderImpl");
transcoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,new Float(1.0));
TranscoderInput input = new TranscoderInput(in);
OutputStream ostream = new FileOutputStream(file.substring(0,file.lastIndexOf("."))+".jpg");
TranscoderOutput output = new TranscoderOutput(ostream);
transcoder.transcode(input, output);
ostream.close();
ostream.flush();*/
JPEGTranscoder t = new JPEGTranscoder();
InputStream in = new FileInputStream(file);
TranscoderInput input = new TranscoderInput(in);
FileOutputStream outputStream = new FileOutputStream(new File(
file.substring(0,file.lastIndexOf("."))+".jpg"));
TranscoderOutput output = new TranscoderOutput(outputStream);
t.transcode(input, output);
outputStream.flush();
outputStream.close();

}
/* public void convert2GIF(String file) throws TranscoderException, IOException{
GIFTranscoder t = new GIFTranscoder();
TranscoderInput input = new TranscoderInput(new FileInputStream(file));
OutputStream ostream = new FileOutputStream(file.substring(0,file.lastIndexOf("."))+".gif");
TranscoderOutput output = new TranscoderOutput(ostream);
t.transcode(input, output);
ostream.flush();
ostream.close();
}*/
public void convert2PNG(String file) {
try {
PNGTranscoder t = new PNGTranscoder();
InputStream in = new FileInputStream(file);
TranscoderInput input = new TranscoderInput(in);
FileOutputStream outputStream = new FileOutputStream(new File(
file.substring(0,file.lastIndexOf("."))+".png"));
TranscoderOutput output = new TranscoderOutput(outputStream);
t.transcode(input, output);
outputStream.flush();
outputStream.close();

} catch (Exception ex) {
ex.printStackTrace();
}
}

/**
* 将svg字符串转换为png
*
* @param svgCode svg代码
* @param pngFilePath 保存的路径
* @throws TranscoderException svg代码异常
* @throws IOException io错误
*/
public static void convertToPng(String svgCode, String pngFilePath) throws IOException,
TranscoderException {

File file = new File(pngFilePath);

FileOutputStream outputStream = null;
try {
file.createNewFile();
outputStream = new FileOutputStream(file);
convertToPng(svgCode, outputStream);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 将svgCode转换成png文件,直接输出到流中
*
* @param svgCode svg代码
* @param outputStream 输出流
* @throws TranscoderException 异常
* @throws IOException io异常
*/
public static void convertToPng(String svgCode, OutputStream outputStream)
throws TranscoderException, IOException {
try {
byte[] bytes = svgCode.getBytes("utf-8");
PNGTranscoder t = new PNGTranscoder();
TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(bytes));
TranscoderOutput output = new TranscoderOutput(outputStream);
t.transcode(input, output);
outputStream.flush();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String[] args) {
try {
convertToPng("D:\\input.svg", "D:\\output.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TranscoderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要将WMF转换为SVG并设置stroke-width,可以使用Java的Apache Batik库。Apache Batik是一个用于处理SVGJava库,它提供了将WMF转换为SVG的功能。 以下是一个将WMF转换为SVG并设置stroke-width的示例代码: ```java // 读取WMF文件 InputStream is = new FileInputStream("example.wmf"); // 创建转换器 WMFTranscoder transcoder = new WMFTranscoder(); // 设置转换参数 TranscodingHints hints = new TranscodingHints(); hints.put(ImageTranscoder.KEY_WIDTH, (float) 400); hints.put(ImageTranscoder.KEY_HEIGHT, (float) 300); transcoder.setTranscodingHints(hints); // 执行转换 TranscoderInput input = new TranscoderInput(is); ByteArrayOutputStream os = new ByteArrayOutputStream(); TranscoderOutput output = new TranscoderOutput(os); transcoder.transcode(input, output); // 将转换后的SVG字符串解析为DOM对象 String svgString = os.toString("UTF-8"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource isource = new InputSource(new StringReader(svgString)); Document doc = builder.parse(isource); // 设置stroke-width Element root = doc.getDocumentElement(); NodeList pathNodes = root.getElementsByTagName("path"); for (int i = 0; i < pathNodes.getLength(); i++) { Element path = (Element) pathNodes.item(i); path.setAttribute("stroke-width", "2"); } // 将DOM对象写入文件 Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(doc), new StreamResult(new File("example.svg"))); ``` 在上面的代码中,首先读取WMF文件并创建WMFTranscoder对象。然后设置转换参数并执行转换,将转换后的SVG字符串解析为DOM对象。接着,遍历所有的path元素并设置stroke-width属性的值为2。最后,将DOM对象写入SVG文件。 注意:在上面的代码中,设置的stroke-width值为2,可以根据需要进行修改。另外,还需要在代码中添加异常处理
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值