簡體   English   中英

使用具有Alpha的PNG改進Java ImageIO讀/寫

[英]Improving Java ImageIO read/write with PNG that has alpha

我有一個大的PNG圖片(600x600),我的應用程序使該圖片不透明並寫出文件。 問題在於ImageIO的性能很差。 還有其他選擇嗎? 我要求圖像不透明。 以下是我在做什么:

    BufferedImage buf = ImageIO.read(localUrl);
    float[] scales = {1f, 1f, 1f, 1f};  // R, G, B, A
    float[] offsets = {0f, 0f, 0f, 1f};   // R, G, B, A
    RescaleOp rescaler = new RescaleOp(scales, offsets, null);
    BufferedImage opaque = rescaler.filter(buf, null);
    File outputfile = new File(localUrl.getPath());
    ImageIO.write(opaque, "png", outputfile);

如果您只是想擺脫透明性,那么在這里使用RescaleOp並不是完全必要的。 一個更簡單的解決方案是在背景上繪制圖像,如下所示:

Color bgColor = Color.WHITE;

BufferedImage foreground = ImageIO.read(localUrl);
int width = foreground.getWidth();
int height = foreground.getHeight();
BufferedImage background = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = background.createGraphics();
g.setColor(bgColor);
g.fillRect(0, 0, width, height);
g.drawImage(foreground, 0, 0, null);
g.dispose();
File outputfile = new File(localUrl.getPath());
ImageIO.write(background, "png", outputfile);

這似乎是一種更簡單的處理方法,並且可能需要更少的處理能力,但是我懷疑會存在巨大差異。 如果您對可以從硬盤驅動器讀取/寫入圖像的速度不滿意,那么您將無能為力。

使用PNGJ

private static void removeAlpha(File file1,File file2) {
    PngReaderByte reader = new PngReaderByte(file1);
    ImageInfo info = reader.imgInfo;
    PngWriter writer = new PngWriter(file2,info);
    writer.setFilterPreserve(true);
    writer.setCompLevel(6);
    writer.copyChunksFrom(reader.getChunksList(), ChunkCopyBehaviour.COPY_ALL_SAFE);
    if( info.bitDepth != 8 ||info.channels!=4) throw new RuntimeException("expected 8bits RGBA ");
    while(reader.hasMoreRows()) {
        ImageLineByte line = reader.readRowByte();
        byte [] buf = line.getScanlineByte();
        for(int i=0,j=3;i<info.cols;i++,j+=4)
            buf[j]=(byte)255;
        writer.writeRow(line);
    }
    reader.end();
    writer.end();
}

我不確定這是否會提高性能。 還要記住,這(與Parker Hoyes的回答相反)只會殺死alpha通道,但不會與某些背景顏色混合(因此,“原始”顏色將出現在先前透明的現在不透明的區域中)。

暫無
暫無

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

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