簡體   English   中英

旋轉圖像時背景為黑色

[英]Background is black when rotating an image

我正在嘗試使用以下代碼旋轉圖像:

File imgPath = new File("c:\\tmp\\7.jpg");
BufferedImage src = ImageIO.read(imgPath);
AffineTransform tx = new  AffineTransform();

int width = src.getWidth();
int height = src.getHeight();
tx.rotate(radiant ,width, height);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC);
BufferedImage out = op.filter(src, null);

File outFile = new File("c:\\tmp\\out.jpg");
ImageIO.write(out, "jpg", outFile);

由於某種原因,旋轉后的背景為黑色。 如何使背景白色或透明?

當您使用AffineTransformOp.filter(src, null)創建新圖像時,新圖像使用與源圖像相同的ColorModel

您輸入的圖像是jpeg,這意味着它不是透明的,因此目標圖像是RGB圖像,沒有alpha(透明)級別。

當以較小的角度旋轉時,圖像不再占據完全相同的邊界,因此背景在其邊緣可見,並且由於沒有alpha電平,因此背景為黑色是正常的。

但是,如果將其保存為支持gif或png等透明度的格式,則圖像將不再顯示黑色背景。

ImageIO.write(out, "gif", outFile);

完整代碼:

    try {
        File imgPath = new File("d:\\downloads\\about.jpg");
        BufferedImage src = ImageIO.read(imgPath);
        AffineTransform tx = new AffineTransform();

        int width = src.getWidth();
        int height = src.getHeight();
        tx.rotate(0.02050493823247637, width, height);
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC);
        BufferedImage out = op.filter(src, null);

        File outFile = new File("d:\\downloads\\about0.gif");
        ImageIO.write(out, "gif", outFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

看看這個以獲得更多信息和技巧。

這是我旋轉到gif后的圖像: 旋轉后的gif圖像

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM