Search This Blog

Wednesday, October 10, 2018

Java SVG Maker

Sick again at home and I decided to do the same program in Java!

Got to my last post for some background: Powershell SVG Maker

Here's the code...

import java.io.IOException;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.awt.image.BufferedImage;

public class SVGMaker {

    public static void main(String[] args) {
        String inFilePath = args[0]; // "LesleyatHonda.12.Dither.Part.White.png";
        String outFilePath = args[1]; //"LesleyatHonda.12.Dither.Part.White.svg";
        int SVGScale = 10;
        String newLine = System.lineSeparator();

        try {
            BufferedImage image = ImageIO.read(new File(inFilePath));
            File outFile = new File(outFilePath);
            FileOutputStream OutFOS = new FileOutputStream(outFile);
            OutputStreamWriter outOSW = new OutputStreamWriter(OutFOS,"UTF-8");
            outOSW.write("<xml version\"1.0\" encoding=\"UTF-8\"?>");outOSW.write(newLine);
            outOSW.write("<svg version\"1.1\" baseProfile=\"full\" width=\""+(image.getWidth()*SVGScale)+"\" height=\""+(image.getHeight()*SVGScale)+"\" xmlns=\"http://www.w3.org/2000/svg\">");outOSW.write(newLine);
            for (int ypos = 0 ; ypos < image.getHeight() ; ypos++ ) {
                for (int xpos = 0 ; xpos < image.getWidth() ; xpos++ ) {
                    int pixel = image.getRGB(xpos,ypos);
                    int pAlpha = (pixel>>24) & 0xff;
                    int pRed = (pixel>>16) & 0xff;
                    int pGreen = (pixel>>8) & 0xff;
                    int pBlue = pixel & 0xff;
                    outOSW.write("<rect Fill\"#"+String.format("%02X",pRed)+String.format("%02X",pGreen)+String.format("%02X",pBlue)+"\" x=\""+(xpos*SVGScale)+"\" y=\""+(ypos*SVGScale)+"\" width=\""+SVGScale+"\" height=\""+SVGScale+"\"/>");outOSW.write(newLine);
                }
            }
            outOSW.write("</svg>"");outOSW.write(newLine);
            outOSW.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}





Here's the run line...

java SVGMaker LesleyatHonda.12.Dither.Part.White.png LesleyatHonda.12.Dither.Part.White.svg


Producing...