ImageMagick在壓縮圖形品質上真的很不錯,而且也可以在很多平台及程式語言上使用
不過在使用上並不像大家熟識的java 的imageio有那麼多資源,
原本是使用BufferedImage的getWidth()及getHeight()來取得圖的長與寬
不過讀取的Image會存放在java VM 暫存中,不能自行釋放,所以有時讀大量讀時會out of memory,
這時可以利用第三方套件ImageMagick來代替BufferedImage
一般利用BufferedImage取得長寬的方式大概如下
BufferedImage srcBufferImage = ImageIO.read(fi); int width = srcBufferImage.getWidth(); int height = srcBufferImage.getHeight();
用JMagick則改寫成以下
if (System.getProperty("jmagick.systemclassloader") == null) { System.setProperty("jmagick.systemclassloader", "no"); } MagickImage magImage = null; try { java.io.File f = new java.io.File("圖檔名稱"); if (f.exists()) { ImageInfo info = new ImageInfo(f.getAbsolutePath()); magImage = new MagickImage(info);Dimension imageDim = magImage.getDimension(); int height = imageDim.height; int width = imageDim.width; } } finally { if (magImage != null) { magImage.destroyImages(); } }
或是寫成Function
public static int getWidth(String src) throws MagickException { MagickImage magImage = null; try { ImageInfo info = new ImageInfo(src ); magImage = new MagickImage(info); Dimension imageDim = magImage.getDimension(); return (int) imageDim.getWidth(); } finally { if (magImage != null) { magImage.destroyImages(); } } }public static int getHeight(String src) throws MagickException { MagickImage magImage = null; try { ImageInfo info = new ImageInfo(src ); magImage = new MagickImage(info); Dimension imageDim = magImage.getDimension(); return (int) imageDim.getHeight(); } finally { if (magImage != null) { magImage.destroyImages(); } } }
試用的結果還算滿意,最少out of memory已經沒有在出現了
參考資料