简体   繁体   English

BufferedImage到带有黑色背景的文件

[英]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. 我正在尝试将BufferedImage(从byte []来)保存到文件中,但是它会产生没有图像的黑色背景。 I'm using the photoCam from primefaces. 我正在使用primefaces的photoCam。

This is my ManagedBean method: 这是我的ManagedBean方法:

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. 方法“ salvarImagemFromImageObject”可以简单地创建一个“ ImageIO.write(image,“ jpg”,destFile)”来保存文件,但是该文件没有任何内容,只有黑色背景。

Primefaces PhotoCam component renders PNG images. Primefaces PhotoCam组件可渲染PNG图像。 PNG format is by design. PNG格式是设计使然。 If you want to work with another file format, you'll need to post-process the PNG image rendered by the PF component. 如果要使用其他文件格式,则需要对PF组件渲染的PNG图像进行后处理。

Refactor your salvarImagemFromImageObject function with a .png destFile: .png destFile重构salvarImagemFromImageObject函数:

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

EDIT 编辑

Writes the resulting png data to jpeg format: 将生成的png数据写入jpeg格式:

//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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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