我有和你一样的需求,在这篇如何使颜色透明的帖子和网页上找到了很多帮助。
下面是我的最终代码:
public BufferedImage getTransparentScaledImage(BufferedImage originalImage, int finalWidth, int finalHeight) {
int originalWidth = originalImage.getWidth();
int originalHeight = originalImage.getHeight();
int newWidth;
int newHeight;
if (originalWidth == 0 || originalHeight == 0
|| (originalWidth == finalWidth && originalHeight == finalHeight)) {
return originalImage;
}
double aspectRatio = (double) originalWidth / (double) originalHeight;
double boundaryAspect = (double) finalWidth / (double) finalHeight;
if (aspectRatio > boundaryAspect) {
newWidth = finalWidth;
newHeight = (int) Math.round(newWidth / aspectRatio);
} else {
newHeight = finalHeight;
newWidth = (int) Math.round(aspectRatio * newHeight);
}
int xOffset = (finalWidth - newWidth) / 2;
int yOffset = (finalHeight - newHeight) / 2;
LoggerManager.getInstance().debug("frontoffice",
"Image Servlet: [" + xOffset + "] [" + yOffset + "] [" + newWidth + "] [" + newHeight + "] [" + originalWidth + "] [" + originalHeight + "] [" + finalWidth + "] [" + finalHeight + "]");
BufferedImage intermediateImage = new BufferedImage(finalWidth, finalHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D gi = intermediateImage.createGraphics();
gi.setComposite(AlphaComposite.SrcOver);
gi.setColor(Color.WHITE);
gi.fillRect(0, 0, finalWidth, finalHeight);
gi.drawImage(originalImage, xOffset, yOffset, xOffset + newWidth, yOffset + newHeight, 0, 0, originalWidth, originalHeight, Color.WHITE, null);
gi.dispose();
Image intermediateWithTransparentPixels = makeColorTransparent(intermediateImage, Color.WHITE);
BufferedImage finalImage = new BufferedImage(finalWidth, finalHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D gf = finalImage.createGraphics();
gf.setComposite(AlphaComposite.SrcOver);
gf.setColor(new Color(0, 0, 0, 0));
gf.fillRect(0, 0, finalWidth, finalHeight);
gf.drawImage(intermediateWithTransparentPixels, 0, 0, finalWidth, finalHeight, new Color(0, 0, 0, 0), null);
gf.dispose();
return finalImage;
}
public static Image makeColorTransparent(Image im, final Color color) {
ImageFilter filter = new RGBImageFilter() {
public int markerRGB = color.getRGB() | 0xFF000000;
public final int filterRGB(int x, int y, int rgb) {
if ((rgb | 0xFF000000) == markerRGB) {
return 0x00FFFFFF & rgb;
} else {
return rgb;
}
}
};
ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(ip);
}
new Color(int r, int g, int b, int a)
来设置 alpha 组件吗? - Eng.Fouadnew Color(0, 0, 0, 0)
。 - Eng.FouadBufferedImage.TYPE_INT_ARGB
作为图片类型。 - Eng.Fouad