我在生成带有Alpha通道(透明度)的图像缩略图时遇到了问题。我使用的代码如下:
public void saveThumbnail(File file, String imageType) {
if (bufferedThumb == null) {
return;
}
if(bufferedImage.getColorModel().hasAlpha()) {
logger.debug("Original image has Alpha channel");
}
BufferedImage bi = new BufferedImage(bufferedThumb.getWidth(null), bufferedThumb.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
g.drawImage(bufferedThumb, 0, 0, null);
try {
ImageIO.write(bi, imageType, file);
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("Error occured saving thumbnail");
}
}
然而,如果我使用带有透明背景的GIF图像,最终总是会出现黑色或有色背景。
编辑:
这是从类中使用缩略图调用它的方式,上次我错过了getThuimbnail()方法的双参数版本:
Thumbnail th = new Thumbnail(file.getPath());
th.getThumbnail(100);
添加了用于获取图像的方法:
public Thumbnail(String fileName) {
try {
this.bufferedImage = ImageIO.read(new File(fileName));
} catch (IOException ex) {
logger.error("Failed to read image file: " + ex.getMessage());
}
}
public Image getThumbnail(int size) {
int dir = VERTICAL;
if (bufferedImage.getHeight() < bufferedImage.getWidth()) {
dir = HORIZONTAL;
}
return getThumbnail(size, dir);
}
/**
* Creates image with specifed max sized to a specified direction.
* Will use Image.SCALE_SMOOTH for scaling.
* @param size Maximum size
* @param dir Direction of maximum size - 0 = vertical, 1 = height.
* @return Resized image.
*/
public Image getThumbnail(int size, int dir) {
return getThumbnail(size, dir, Image.SCALE_SMOOTH);
}
/**
* Creates image with specified size.
* @param size Maximum size
* @param dir Direction of maximum size - 0 = vertical, 1 = height.
* @param scale Image.Scale to use for conversion.
* @return Resized image.
*/
public Image getThumbnail(int size, int dir, int scale) {
if (dir == HORIZONTAL) {
bufferedThumb = bufferedImage.getScaledInstance(size, -1, scale);
} else {
bufferedThumb = bufferedImage.getScaledInstance(-1, size, scale);
}
return bufferedThumb;
}
谢谢!