java.awt.Image转 com.lowagie.text.Image
生活随笔
收集整理的這篇文章主要介紹了
java.awt.Image转 com.lowagie.text.Image
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在生成條形碼時,因為Barcode128返回的是java.awt.Image,但是我們使用的是itext的包,所以在image轉換是出現了一些問題。雖然在com.lowagie.text.Image中提供了一個getInstance(java.awt.Image?image,?java.awt.Color?color),但是在我使用時無法正常使用,可能是調用姿勢不對,也沒有繼續深究問題,所以我將java.awt.Image轉成了byte[]進行轉換類型,代碼如下:
Barcode128 code = new Barcode128();code.setCode("1234");java.awt.Image image = code.createAwtImage(Color.black, Color.white);ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ImageIO.write(toBufferedImage(image), "jpg", outputStream);public static BufferedImage toBufferedImage(Image image) throws Exception{if (image instanceof BufferedImage) {return (BufferedImage)image;}image = new ImageIcon(image).getImage();BufferedImage bimage = null;GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();try {int transparency = Transparency.OPAQUE;GraphicsDevice gs = ge.getDefaultScreenDevice();GraphicsConfiguration gc = gs.getDefaultConfiguration();bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);} catch (HeadlessException e) {throw new Exception("轉換BufferedImage異常", e);}if (bimage == null) {int type = BufferedImage.TYPE_INT_RGB;bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);}Graphics g = bimage.createGraphics();g.drawImage(image, 0, 0, null);g.dispose();return bimage;}參考:https://segmentfault.com/q/1010000013282377/a-1020000013286100
總結
以上是生活随笔為你收集整理的java.awt.Image转 com.lowagie.text.Image的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Rafy 框架 - 幽灵插件(假删除)
- 下一篇: 利用python生成一个导出数据库的ba