Search code examples
javaimagetransparency

When saving image it saves it as black transparent instead of the real image


When saving the image in it turns into a black square instead of the chosen image, I want to be able to save images from my computer and save it in folder in the project so when zipped and sent they can view the image I uploaded.

I have tried BufferedImage.TYPE_INT_ARGB but I don't know if that is the problem.

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");
    }
}

Solution

  • One does not need to work pixel by pixel, which would be slow.

    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();
    
    }
    

    One can create a Graphics to draw with.

    There are various methods, like using a background color should part of the image be transparent.