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);
Related
I wonder if there is a way in java to put a gif image over png image at particular location (say at particular value of x,y). If so please help me through this.
This is the case :
I have a base Image which is of png type. and I have gif images of size 62*62. I wanted to put several such gif images on png image and I need to render the png image on front end at every 5 seconds..
To extract image from GIF file.. This save the first image into png file from GIF.
try {
ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
ImageInputStream stream = ImageIO.createImageInputStream(new File("c:/aaa.gif");
reader.setInput(stream);
int count = reader.getNumImages(true);
if(count>0){
BufferedImage frame = reader.read(0);
ImageIO.write(frame, "png", new File(filePath+fileName+".png"));
System.out.println("Donesss");
}
} catch (IOException ex) {
}
I have made a program in java that accepts a color image and converts it into gray scale image. The image is read as a BufferedImage, the RGB components are extracted and modified and set into the same image to display on the console window created. But I want the output as a separate jpeg or png file. Can someone tell me how to do this?
EDIT:
public static void saveToFile(BufferedImage img)throws FileNotFoundException, IOException
{
File outputfile = new File("E:\\Java\\Sample.jpg");
ImageIO.write(img, "jpg", outputfile);
}
This was the method I was hoping to use .Here img was the image I was using(editing upon, i.e. changing pixel values).And the path where I want to store my output was E:\Java . Please Someone help..
use this way:
{
File outputfile = new File("E:\\Java\\Sample.jpg");
FileOutputStream fos = new FileOutputStream(outputfile);
ImageIO.write(img, "jpg", outputfile);
fos.flush();
fos.close()
}
I try to draw an image from a bufferedImage into a PDF using PDFBox but fails, and I get black images and Acrobat Reader warns whith errors like "Out of memory" (but PDF is display).
I use a bufferedImage because I need to draw a JavaFX Image object (with came from call to Funciones.crearImagenDesdeTexto(), is a function which converts a text into an Image) into PDF. Rest of images works well without using bufferedimage.
PDPixelMap img = null;
BufferedImage bi;
try {
//If item has id, I try to get image with that id (image it's shows OK on PDF)
img = new PDPixelMap(documento, read(getClass().getResourceAsStream("/com/img/" + item.getId() + ".png")));
}
catch (Exception e) {
//If item has not id or fails load image, I create image on the fly (which contains item name. This not work on PDF, shows black images)
bi = new BufferedImage(alto, ancho, BufferedImage.TYPE_INT_ARGB);
bi.createGraphics().drawImage(SwingFXUtils.fromFXImage(Funciones.crearImagenDesdeTexto(item.getNombre()), null), ancho, alto, null);
img = new PDPixelMap(documento, bi);
}
finally {
contenedor.drawXObject(img, x, y, alto, ancho);
}
NOTE: crearImagenDesdeTexto() returns a JavaFX Image Object that is create on the fly (I try this function in other parts of the program and works well, function is take from other stackOverflow response).
Your code is confusing, you have three "new PDJpeg" and one of them is in a catch (which should just handle the error). And what does "read()" do? Does it pass a stream or a BufferedImage? If it is a stream, then it is wrong, because PDJpeg is for JPEGs, not for PNG.
The second one
img = new PDJpeg(documento, (getClass().getResourceAsStream("/com/img/" + Byte.toString(item.getId()) + ".png")));
is definitively wrong for the same reason: PDJPeg is not for PNG files / streams.
If you want to create an image from a PNG file / stream, use PDPixelMap.
It is possible to create a PDJpeg object from a BufferedImage, but this is recommended only if the image wasn't encoded before. Because if you would read a BufferedImage from a JPEG, and then use PDJPeg for this, you'll have a slight loss of quality as the image is decoded and encoded again (JPEG is a "lossy" compression format).
If my advice doesn't help, please upload the JPEG file and the PDF somewhere.
Also make sure that you're using the latest version, which is 1.8.7.
Update after comments:
the parameters to createGraphics.drawImage() should be 0, 0 and not width, height. The two parameters are a location, not a size.
Finally, I find a solution (thanks also to Tilman Hausherr):
private void dibujarImagen(Item i, int x, int y, int alto, int ancho) throws IOException {
PDPixelMap img = null;
try {
img = new PDPixelMap(documento, read(getClass().getResourceAsStream("/com/img/" + i.getId() + ".png")));
}
catch (IllegalArgumentException e) {
img = new PDPixelMap(documento, SwingFXUtils.fromFXImage(Funciones.crearImagenDesdeTexto(i.getNombre()),null));
}
finally {
contenedor.drawXObject(img, x, y, alto, ancho);
}
}
I am using an Applet to save image from clipboard. The image is saved but something happened with its format. It is darken and lost colors.
here's how I am doing it:
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
//create clipboard object
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//Get data from clipboard and assign it to an image.
//clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
BufferedImage image = (BufferedImage) clipboard.getData(DataFlavor.imageFlavor);
//file that we'll save to disk.
File file = new File("/tmp/clipboard.jpg");
//class to write image to disk. You specify the image to be saved, its type,
// and then the file in which to write the image data.
ImageIO.write(image, "jpg", file);
//getData throws this.
} catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
return "Não tem imagem na área de transferência";
} catch (Exception ioe){
ioe.printStackTrace();
}
return null;
}
}
);
I read that Mac uses a different image format but I did not find how to convert it to a format I could save. I imagined that java should have taken care of that.
So, how can I convert the image from clipboard to jpg?
PS. I tried using png instead of jpg, got a worse result: black image
To solve the issue on Mac, I used the solution proposed on The nightmares of getting images from the Mac OS X clipboard using Java.
I pass the retrieved BufferedImage to method that redraws it to new BufferedImage, returning a valid image. Here follows the code from that page:
public static BufferedImage getBufferedImage(Image img) {
if (img == null) return null;
int w = img.getWidth(null);
int h = img.getHeight(null);
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage bufimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufimg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, w, h, null);
g2.dispose();
return bufimg;
}
And how I use it:
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//Get data from clipboard and assign it to an image.
//clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
BufferedImage image = (BufferedImage) clipboard.getData(DataFlavor.imageFlavor);
if (isMac()) {
image = getBufferedImage(image);
}
PNG is the preferred image format for Macs. You might want to try saving as that and then converting to a JPG if needed afterwards.
I'm having problems converting a simple PNG into a JPEG format.
I'm using the following code:
...
File png = new File(filePath);
try {
SeekableStream s = new FileSeekableStream(png);
PNGDecodeParam pngParams = new PNGDecodeParam();
ImageDecoder dec = ImageCodec.createImageDecoder("png", s, pngParams);
RenderedImage pngImage = dec.decodeAsRenderedImage();
JPEGEncodeParam jparam = new JPEGEncodeParam();
jparam.setQuality(0.50f); // e.g. 0.25f
File jpeg = new File("jpeg.jpeg");
FileOutputStream out = new FileOutputStream(jpeg);
ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, jparam);
encoder.encode(pngImage);
s.close();
} catch (IOException e) {
ok = false;
e.printStackTrace();
}
return ok;
}
...
I end up with an JAI exception ->
java.lang.RuntimeException: Only 1, or 3-band byte data may be written.
at com.sun.media.jai.codecimpl.JPEGImageEncoder.encode(JPEGImageEncoder.java:148) ...
Ran out of options. Any suggestion?
It might be easier to use ImageIO to read the PNG into a BufferedImage and write the image out in JPEG format.
Addendum: In this approach, the conversion is handled transparently by the writer's ImageTranscoder.
BufferedImage img = ImageIO.read(new File("image.png"));
ImageIO.write(img, "jpg", new File("image.jpg"));
you probably have alpha channel in the png that you need to get rid of before trying to write the jpg.
Create a new BufferedImage with type TYPE_INT_RGB (not TYPE_INT_ARGB), and then write your source image (pngImage) onto the new blank image.
Something like this (warning, not tested code):
BufferedImage newImage = new BufferedImage( pngImage.getWidth(), pngImage.getHeight(), BufferedImage.TYPE_INT_RGB);
newImage.createGraphics().drawImage( pngImage, 0, 0, Color.BLACK, null);
I also found that reading a PNG image into a BufferedImage with ImageIO (Java 6) and writing it out to a JPG "format name" corrupted the image. The image was there, but the colors looked "solarized" and almost inverted. The JPG file was much smaller than the PNG file for sure, so a lot of compression was done. I don't see how you might control the compression or color depth.
I had corrupted file after conversion with other solutions but this method worked for me:
public static void formatConverter(String pngFile, String jpgFile) {
try {
File input = new File(pngFile);
File output = new File(jpgFile);
BufferedImage image = ImageIO.read(input);
BufferedImage result = new BufferedImage(
image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_INT_RGB);
result.createGraphics().drawImage(image, 0, 0, Color.WHITE, null);
ImageIO.write(result, "jpg", output);
} catch (IOException e) {
e.printStackTrace();
}
}
I suppse that JAI reads the PNG image with an indexed colour model and is only able to write 8-bit grayscale or 24-bit colour images as JPEG files.
If you are not required to use JAI for this task, you should be able to use ImageIO instead:
ImageIO.write(ImageIO.read(new File("in.png")), "JPEG", new File("out.jpg"));
I was getting the following message in a slightly different context. Getting rid of the alpha channel solved the problem
javax.imageio.IIOException: Sample size must be <= 8
at com.sun.imageio.plugins.jpeg.JPEGImageWriter.write(JPEGImageWriter.java:435)
at javax.imageio.ImageWriter.write(ImageWriter.java:580)
at com.twelvemonkeys.imageio.plugins.jpeg.JPEGImageWriter.write(Unknown Source)
at net.sf.basedb.util.ImageTools.tiffToJpg(ImageTools.java:98)
at net.sf.basedb.util.ImageTools.main(ImageTools.java:118)
see Converting transparent gif / png to jpeg using java
Have a look at the solution that redraws with the graphics environment posted by harmanjd. The solution with the DirectColorModel doesn't compile and should be wiped away. I don't have enough rep points to comment directly there.