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()
}
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) {
}
Okay, I want to create a copy of an image I have in my resource folder, and put it onto the desktop pretty much. Example: My project has a resource folder with an image called apple.png. Since when I export my jar file it can't find it, I want to copy it to the desktop so it can find it from there. Here is what I tried doing:
try {
// retrieve image
BufferedImage bi = new BufferedImage(256, 256,
BufferedImage.TYPE_INT_RGB);
File outputfile = new File(
"C:/Users/Owner/Desktop/saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
}
}
This just created the buffered Image for me on my desktop. How do I take my res Image and copy it to it.
Any reason for loading it as an image? If you just want to copy resource to desktop without changing it:
InputStream resStream = getClass().getResourceAsStream("/image.png"));
//Improved creation of output path:
File path = new File(new File(System.getProperty("user.home")), "Desktop");
File outputFile = new File(path, "saved.png");
//now write it
Files.copy(resStream, outputFile);
You need to load the BufferedImage as the image file.
BufferedImage bi = ImageIO.read(new File(getClass().getResource("/apple.png"));));
All the other steps are the same.
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);
This is not a duplicated question here, because I've been searching for the solution for a long time in Google and StackOverflow, and still cannot find a solution.
I have these two images:
These are two images from the same website with same prefix and same format. The only difference is the size: the first is larger, while the second is smaller.
I downloaded both of the images to local folder and used Java to read them into BufferedImage objects. However, when I outputted the BufferedImages to local files, I found that the first image was almost red, while the second was normal(same as original). What's wrong with my code?
byte[] rawData = getRawBytesFromFile(imageFilePath); // some code to read raw bytes from image file
ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(rawData));
BufferedImage img = ImageIO.read(iis);
FileOutputStream fos = new FileOutputStream(outputImagePath, false);
ImageIO.write(img, "JPEG", fos);
fos.flush();
fos.close();
PS: I used GIMP to open the first image and detected that the Color Mode is 'sRGB', no alpha or other stuff.
This is apparently a know bug, I saw several suggestions (this is one) that suggest using Toolkit#createImage instead, which apparently ignores the color model.
I tested this and it seems to work fine.
public class TestImageIO01 {
public static void main(String[] args) {
try {
Image in = Toolkit.getDefaultToolkit().createImage("C:\\hold\\test\\13652375852388.jpg");
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(in)), "Yeah", JOptionPane.INFORMATION_MESSAGE);
BufferedImage out = new BufferedImage(in.getWidth(null), in.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = out.createGraphics();
g2d.drawImage(in, 0, 0, null);
g2d.dispose();
ImageIO.write(out, "jpg", new File("C:\\hold\\test\\Test01.jpg"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
nb- I used the JOptionPane to verify the incoming image. When using ImageIO it comes in with the red tinge, with Toolkit it looks fine.
Updated
And an explantation
I checked your code in netbeans and faced with your problem, then I changed the code as below that has no problem:
public class Test {
public static void main(String args[]) throws IOException {
byte[] rawData = getRawBytesFromFile(imageFilePath); // some code to read raw bytes from image file
// ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(rawData));
// BufferedImage img = ImageIO.read(iis);
FileOutputStream fos = new FileOutputStream(outputImagePath, false);
fos.write(rawData);
// ImageIO.write(img, "JPEG", fos);
fos.flush();
fos.close();
}
private static byte[] getRawBytesFromFile(String path) throws FileNotFoundException, IOException {
byte[] image;
File file = new File(path);
image = new byte[(int)file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(image);
return image;
}
}
Please check it and inform me of the result ;)
Good Luck
I suspect this solution might work just fine in the original poster's case.
String fileName = imageFilePath;
File inFile = new File(fileName);
BufferedImage img = ImageIO.read(inFile);
...
Best,
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.