BufferedImage调整大小会产生黑色边框

时间:2018-06-19 09:36:46

标签: java bufferedimage image-resizing

我有以下代码用于将图像调整为较小的尺寸。调整大小成功,但我的图像侧面有黑色边框。

有人可以帮忙吗?

byte[] photo = photoForm.getFilename().getBytes();

InputStream inputstream = new ByteArrayInputStream(photo);
BufferedImage originalImage = ImageIO.read(inputstream);
BufferedImage resizeImageJpg = resizeImage(originalImage, 
BufferedImage.TYPE_INT_RGB, IMG_WIDTH, IMG_HEIGHT);

private static BufferedImage resizeImage(BufferedImage originalImage, int type, int newWidth, int newHeight) {

    double thumbRatio = (double) newWidth / (double) newHeight;
    int imageWidth = originalImage.getWidth(null);
    int imageHeight = originalImage.getHeight(null);
    double aspectRatio = (double) imageWidth / (double) imageHeight;

    if (thumbRatio < aspectRatio) {
        newHeight = (int) (newWidth / aspectRatio);
    } else {
        newWidth = (int) (newHeight * aspectRatio);
    }

    BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, type);
    Graphics2D g = resizedImage.createGraphics();

    g.setComposite(AlphaComposite.Src);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
    g.dispose();

    return resizedImage;
}

0 个答案:

没有答案