2012-04-27 79 views
2

我目前正在使用ZXing生成QR碼作爲圖像的應用程序。下面是一個簡單的例子:使用Java將QR代碼生成爲可縮放的EPS

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 

import com.google.zxing.BarcodeFormat; 
import com.google.zxing.MultiFormatWriter; 
import com.google.zxing.WriterException; 
import com.google.zxing.client.j2se.MatrixToImageWriter; 
import com.google.zxing.common.BitMatrix; 

public class MyQREncoder { 

    /** 
    * @param args 
    * @throws WriterException 
    * @throws IOException 
    * @throws FileNotFoundException 
    */ 
    public static void main(String[] args) throws WriterException, FileNotFoundException, IOException { 
     String text = "Some text to encode"; 
     int width = 300; 
     int height = 300; 
     BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE,width,height); 
     String file = "plop.png"; 
     String format = "png"; 
     MatrixToImageWriter.writeToStream(bitMatrix, format, new FileOutputStream(new File(file))); 
    } 

} 

這產生了擦寫QRCODE說:「一些文本編碼」的PNG文件。

我的問題是,如果我嘗試將格式更改爲eps,那麼我會得到一個空文件。目前我們使用的解決方案是通過imagemagick轉換實用程序將png文件轉換爲eps。但是,給定的EPS只是嵌入原始圖像,並且不能很好地縮放(特別是在打印時)。

是否有人知道是否有任何開源解決方案(使用Zxing或其他)來構建可擴展Eps文件? (或例如任何矢量格式)

回答

3

編輯:這是在Java中一個完整的工作方案:約剛剛生成的PS文件自己

PrintStream psFile = /* Open file */; 

final int blockSize = 4; 

psFile.println("%!PS-Adobe-3.0 EPSF-3.0"); 
psFile.println("%%BoundingBox: 0 0 " + bitMatrix.getWidth() * blockSize + " " + bitMatrix.getHeight() * blockSize); 

psFile.print("/bits ["); 
for(int y = 0; y < bitMatrix.getHeight(); ++y) { 
    for(int x = 0; x < bitMatrix.getWidth(); ++x) { 
     psFile.print(bitMatrix.get(x, y) ? "1 " : "0 "); 
    }   
} 
psFile.println("] def"); 

psFile.println("/width " + bitMatrix.getWidth() + " def"); 
psFile.println("/height " + bitMatrix.getHeight() + " def"); 

psFile.println(
     "/y 0 def\n" + 
     blockSize + " " + blockSize + " scale\n" + 
     "height {\n" + 
     " /x 0 def\n" + 
     " width {\n" + 
     "  bits y width mul x add get 1 eq {\n" + 
     "   newpath\n" + 
     "   x y moveto\n" + 
     "   0 1 rlineto\n" + 
     "   1 0 rlineto\n" + 
     "   0 -1 rlineto\n" + 
     "   closepath\n" + 
     "   fill\n" + 
     "  } if\n" + 
     "  /x x 1 add def\n" + 
     " } repeat\n" + 
     " /y y 1 add def\n" + 
     "} repeat\n"); 
psFile.close(); 

什麼?事情是這樣的:

%!PS-Adobe-3.0 EPSF-3.0 
%%BoundingBox: 0 0 288 288 

/bits [0 0 1 0 1 0 1 1 0 1 1 0 1 1 0 0] def 

/width 4 def 
/height 4 def 
/y 0 def 

72 72 scale 

height { 
    /x 0 def 
    width { 
     bits y width mul x add get 1 eq { 
     newpath 
     x y moveto 
     0 1 rlineto 
     1 0 rlineto 
     0 -1 rlineto 
     closepath 
     fill 
     } if 
     /x x 1 add def 
    } repeat 
    /y y 1 add def 
} repeat 

(如果你當然會在與自己的價值觀上填寫DEFS,通過BitMatrix迭代和打印1和0的填寫bitsps file output

+0

聽起來很很好,非常感謝。但在使用之前,我必須將我的BitMatrix縮小到像素大小。不錯,我會試一試。 ;) – Nicocube 2012-04-28 15:06:39