[英]How to convert SVG to png or jpg
I've tried by using batik .我试过使用蜡染。 But I'm getting empty png file.但我得到了空的 png 文件。 I've also included all the required jars.我还包括了所有必需的罐子。
My code is我的代码是
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
public class TestSVG {
String filePath="";
TestSVG(String filePath) throws Exception {
this.filePath=filePath;
createImage();
}
public void createImage() throws Exception{
String svg_URI_input = new File("test.svg").toURL().toString();
TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);
//Step-2: Define OutputStream to PNG Image and attach to TranscoderOutput
OutputStream png_ostream = new FileOutputStream("chessboard.png");
TranscoderOutput output_png_image = new TranscoderOutput(png_ostream);
// Step-3: Create PNGTranscoder and define hints if required
PNGTranscoder my_converter = new PNGTranscoder();
// Step-4: Convert and Write output
System.out.println("It will print");
my_converter.transcode(input_svg_image, output_png_image);
System.out.println("It will not print");
png_ostream.flush();
png_ostream.close();
}
}
Please the sysout in the code.请在代码中使用系统输出。 Upto step 3 it is working fine.到第 3 步,它工作正常。
You have to use transcoding hints.您必须使用转码提示。 For example for PNG, you should set the pixel that is to be used.例如对于 PNG,您应该设置要使用的像素。
my_converter.addTranscodingHint(PNGTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER,0.084672F); my_converter.addTranscodingHint(PNGTranscoder.KEY_BACKGROUND_COLOR, Color.WHITE);
With your code, I can able to generate the PNG image,使用您的代码,我可以生成 PNG 图像,
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
public class TestSVG {
String filePath="";
TestSVG(String filePath) throws Exception {
this.filePath=filePath;
createImage();
}
public void createImage() throws Exception{
String svg_URI_input = new File("asf-logo.svg").toURL().toString();
TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);
//Step-2: Define OutputStream to PNG Image and attach to TranscoderOutput
OutputStream png_ostream = new FileOutputStream(filePath);
TranscoderOutput output_png_image = new TranscoderOutput(png_ostream);
// Step-3: Create PNGTranscoder and define hints if required
PNGTranscoder my_converter = new PNGTranscoder();
// Step-4: Convert and Write output
System.out.println("It will print");
my_converter.transcode(input_svg_image, output_png_image);
System.out.println("It will not print");
png_ostream.flush();
png_ostream.close();
}
public static void main(String[] args) throws Exception {
TestSVG svg = new TestSVG("asf-logo.png");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.