首页 > 解决方案 > 保存图像时将其保存为黑色透明而不是真实图像

问题描述

当保存图像时,它会变成黑色方块而不是选择的图像,我希望能够从我的计算机中保存图像并将其保存在项目的文件夹中,以便在压缩和发送时他们可以查看我上传的图像。

我试过BufferedImage.TYPE_INT_ARGB了,但我不知道这是否是问题所在。

private void imageToArray(){
    int width = originalBI.getWidth();
    int height = originalBI.getHeight();

    newBI = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);

    pixels = new int[width][height];

    for(int i = 0; i<width;i++){
        for(int j = 0;j<height;j++){
            pixels[i][j]=originalBI.getRGB(i,j);
        }
    }
}

private void saveImage(){
    int returnValue = saveFileChooser.showSaveDialog(this);

    if(returnValue == JFileChooser.APPROVE_OPTION) {
        try{
            ImageIO.write(newBI, "png",saveFileChooser.getSelectedFile());
            lblMessage.setText("Image File Succesfully saved");

        }catch(IOException ex){
            lblMessage.setText("Failed to save image file");
        }
    }
    else{
        lblMessage.setText("No file Choosen");
    }
}

标签: javaimagetransparency

解决方案


不需要逐个像素地工作,这会很慢。

private void imageToArray(){
    int width = originalBI.getWidth();
    int height = originalBI.getHeight();

    newBI = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = newBI.createGraphics();
    g.drawImage(originalBI, 0, 0, width, height, null);
    g.dispose();

}

可以创建一个图形来绘制。

有多种方法,例如在图像的一部分透明时使用背景颜色。


推荐阅读