简体   繁体   中英

BufferedImage to File with black background

I'm trying to save a BufferedImage (came from byte[]) to a File, but it's producing a black background without the image. I'm using the photoCam from primefaces.

This is my ManagedBean method:

public void webcamCapture(CaptureEvent captureEvent) {
        try {
            byte[] data = captureEvent.getData();
            InputStream in = new ByteArrayInputStream(data);
            BufferedImage fotoBuffered = ImageIO.read(in);
            String idImagem = ImagemHelper.getInstance().salvarImagemFromImageObject(fotoBuffered);
            paciente.getPessoaFisica().setFoto(idImagem);

        } catch (Exception e) {
            addErrorMessage("Erro ao capturar imagem da webcam");
            FacesContext.getCurrentInstance().validationFailed();
        }
    }

The method "salvarImagemFromImageObject" simple make a "ImageIO.write(image,"jpg",destFile)" to save a file, but this file don't have nothing, just a black background.

Primefaces PhotoCam component renders PNG images. PNG format is by design. If you want to work with another file format, you'll need to post-process the PNG image rendered by the PF component.

Refactor your salvarImagemFromImageObject function with a .png destFile:

ImageIO.write(fotoBuffered, "png", destFile);

EDIT

Writes the resulting png data to jpeg format:

//Converts PNG image to plain RGB format
BufferedImage newBufferedImage = new BufferedImage(fotoBuffered.getWidth(), fotoBuffered.getHeight(), BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(fotoBuffered , 0, 0, Color.WHITE, null);

//Then, writes to jpeg file
ImageIO.write(newBufferedImage, "jpg", destFile);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM