BufferedImageを別のBufferedImageに拡大縮小する方法
(# 一部のIndexColorModelタイプに対応できませんでした.)
以下のメソッドを使う.
http://ja.wikipedia.org/wiki/Portable_Network_Graphics
http://ja.wikipedia.org/wiki/JPEG
http://ja.wikipedia.org/wiki/Graphics_Interchange_Format
Java 6.0のImageIO#readで読み込んだ上記3つのURLの右上くらいにある画像に対しては,うまく動いた(ただし,動くgifは静止画になる)
それとは別にwebから適当に拾ってきた透過gifもOKだった.
public static BufferedImage rescale(BufferedImage srcImage, int nw, int nh) { BufferedImage dstImage = null; if( srcImage.getColorModel() instanceof IndexColorModel ) { dstImage = new BufferedImage(nw, nh, srcImage.getType(), (IndexColorModel)srcImage.getColorModel()); } else { if( srcImage.getType() == 0 ) { dstImage = new BufferedImage(nw, nh, BufferedImage.TYPE_4BYTE_ABGR_PRE); } else { dstImage = new BufferedImage(nw, nh, srcImage.getType()); } } double sx = (double) nw / srcImage.getWidth(); double sy = (double) nh / srcImage.getHeight(); AffineTransform trans = AffineTransform.getScaleInstance(sx, sy); if( dstImage.getColorModel().hasAlpha() && dstImage.getColorModel() instanceof IndexColorModel) { int transparentPixel = ((IndexColorModel) dstImage.getColorModel()).getTransparentPixel(); for(int i=0;i<dstImage.getWidth();++i) { for(int j=0;j<dstImage.getHeight();++j) { dstImage.setRGB(i, j, transparentPixel); } } } Graphics2D g2 = (Graphics2D)dstImage.createGraphics(); g2.drawImage(srcImage, trans, null); g2.dispose(); return dstImage; }
IndexColorModelの透過画像対策をしている.
AffineTransformOpクラスでも拡大縮小はできるのだけども,綺麗にできないのでGraphics2Dを使った.