Output image becomes black after conversion from FileInputStream to Image - java

I am trying to merge two TIFF images which are in form of FileInputStream into a single Tiff image. Although the image is getting merged the output file is coming up as Black. While comparing the original image and the converted image I could see that the bit depth of the converted image changes to 1. Could anybody provide a solution to this?
The code that I am using is:
public class MergerTiffUsingBuffer {
public static void main(String[] args) {
File imageFile1 = new File("D:/Software/pdfbox-1.3.1.jar/tiff/FLAG_T24.TIF");
File imageFile2 = new File("D:/Software/pdfbox-1.3.1.jar/tiff/CCITT_3.TIF");
try {
FileInputStream fis1 = new FileInputStream(imageFile1);
FileInputStream fis2 = new FileInputStream(imageFile2);
List<BufferedImage> bufferedImages=new ArrayList<>();
List<FileInputStream> inputStreams=new ArrayList<>();
inputStreams.add(fis1);
inputStreams.add(fis2);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("tiff");
ImageReader reader = (ImageReader) readers.next();
for(FileInputStream inputStream:inputStreams){
ImageInputStream iis = ImageIO.createImageInputStream(inputStream);
reader.setInput(iis);
ImageReadParam param = reader.getDefaultReadParam();
Image image = reader.read(0, param);
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
OutputStream out = new FileOutputStream("D:/Software/pdfbox-1.3.1.jar/tiff/MergedTiff.TIF");
BufferedImage binarized = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),BufferedImage.TYPE_BYTE_BINARY);
ImageIO.write(binarized, "tiff", out);
bufferedImages.add(bufferedImage);
}
System.out.println(bufferedImages.size());
} catch (IOException e2) {
e2.printStackTrace();
}
}
}

You seem to be a little confused about how to copy image data. Simply creating a new, blank image, by passing the dimensions of another image, will not copy it... So a fully black image is what I would expect after running your code.
Replace your for loop with something like this:
for (FileInputStream inputStream : inputStreams) {
ImageInputStream iis = ImageIO.createImageInputStream(inputStream);
reader.setInput(iis);
BufferedImage image = reader.read(0, null); // a) BufferedImage is returned! b) null param is fine!
BufferedImage binarized = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
// The following 7 lines is the important part you were missing:
Graphics2D g = binarized.createGraphics();
try {
g.drawImage(image, 0, 0, null);
}
finally {
g.dispose();
}
OutputStream out = new FileOutputStream("D:/Software/pdfbox-1.3.1.jar/tiff/MergedTiff.TIF");
ImageIO.write(binarized, "tiff", out); // You probably want to check return value (true/false)!
bufferedImages.add(image);
}

Related

Compress an image without specifying the type of image

This code is to compress a jpeg image, but if I want to compress an image without specifying the type of image, how can I do that? , How do I modify the code ?
File originalImage = new File("C:\\Users\\Super\\Desktop\\man.jpg");
File compressedImage = new File("C:\\Users\\Super\\Desktop\\compressedImage.jpg");
try{
compressJPEGImage(originalImage, compressedImage,0.5f );
System.out.println("Done!");
}
catch(IOException e){
}
}
public static void compressJPEGImage(File originalImage , File compressedImage , float
compressionQuality) throws IOException{
RenderedImage image = ImageIO.read(originalImage);
ImageWriter jpegwriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam jpegWriteParam=jpegwriter.getDefaultWriteParam();
jpegWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegWriteParam.setCompressionQuality(compressionQuality);
try(ImageOutputStream output=ImageIO.createImageOutputStream(compressedImage)){
jpegwriter.setOutput(output);
IIOImage outputImage = new IIOImage(image,null,null);
jpegwriter.write(null,outputImage,jpegWriteParam);
}
jpegwriter.dispose();
}
Convert image to base64 or byte array of any type, then you can try for compressing it.

Convert an ImageIcon to a Base64 String and back to an ImageIcon without saving to disk?

I'm trying to store an imageIcon bas a Base64 String.
This is what I have so far:
public ImageIcon getImageIcon() {
if(imageIcon == null || imageIcon.isEmpty()){
return null;
} else {
try {
byte[] btDataFile = Base64.decodeBase64(imageIcon);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(btDataFile));
return new ImageIcon(image);
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
return null;
}
}
}
public void setImageIcon(ImageIcon imageIconIn) {
imageIcon = Base64.encodeBase64String(imageToByteArray(imageIconIn));
}
public static byte[] imageToByteArray(ImageIcon imageIn) {
try {
BufferedImage image = new BufferedImage(imageIn.getIconWidth(), imageIn.getIconHeight(),BufferedImage.TYPE_INT_RGB);
ByteArrayOutputStream b = new ByteArrayOutputStream();
// FIX
Graphics g;
g = image.createGraphics();
imageIn.paintIcon(null, g, 0,0);
// END FIX
ImageIO.write(image, "jpg", b );
g.dispose();
return b.toByteArray();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
return null;
}
}
I get a black rectangle instead of the image.
I'm using Java 1.8 on Ubuntu 16.04.
What am I doing wrong?
Thanks for your help.
******************************** . FIXED . ******************************
I found a working solution and updated the above code.
******************************** EDIT *********************************
Added g.dispose() after painting icon.
This code creates a brand new BufferedImage, with width & height same as the given image.
BufferedImage image = new BufferedImage(
imageIn.getIconWidth(),
imageIn.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Note that the image is empty. No content has been written to it. The bytes will all be zero, and RGB 0x000000 is black.
Then, you are writing the bytes of this black image to your ByteArrayOutputStream.
ByteArrayOutputStream b = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", b );
return b.toByteArray();
Of course, when you convert that byte buffer back to an image, it will be black.
You will want to draw/copy imageIn into your new image before you write out the bytes.
But if you don't mind using whatever the current image's format is, you could just write out that image instead of converting it to TYPE_INT_RGB...
Image image = imageIn.getImage();
// write image to ByteArrayOutputStream

Create Multi-Page Tiff with Java

I'm interested in taking a tif image and adding a layer to it that contains text with Java, preferably with the Twelve Monkeys image library if possible.
I can tweak the code from here to either add text to a tif or create a new tif of the same size with only text, but not save them as a multi-page tif. For example:
import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
public class ImageUtil {
public static void main(String[] args) throws Exception {
BufferedImage src = ImageIO.read(new File("/path/to/main.tif"));
BufferedImage text = createTextLayer(src);
BufferedImage[] images = new BufferedImage[]{src, text};
createMultiPage(images);
}
private static BufferedImage createTextLayer(BufferedImage src) {
int w = src.getWidth();
int h = src.getHeight();
BufferedImage img = new BufferedImage(
w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.setPaint(Color.red);
g2d.setFont(new Font("Serif", Font.BOLD, 200));
String s = "Hello, world!";
FontMetrics fm = g2d.getFontMetrics();
int x = img.getWidth() - fm.stringWidth(s) - 5;
int y = fm.getHeight() * 5;
g2d.drawString(s, x, y);
g2d.dispose();
return img;
}
private static void createMultiPage(BufferedImage[] images) throws IOException {
File tempFile = new File("/new/file/path.tif");
//I also tried passing in stream var below to the try, but also receive java.lang.UnsupportedOperationException: Unsupported write variant!
//OutputStream stream = new FileOutputStream(tempFile);
// Obtain a TIFF writer
ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
try (ImageOutputStream output = ImageIO.createImageOutputStream(tempFile)) {
writer.setOutput(output);
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
params.setCompressionType("None");
//error here: java.lang.UnsupportedOperationException: Unsupported write variant!
writer.prepareWriteSequence(null);
for (int i = 0; i < images.length; i++){
writer.writeToSequence(new IIOImage(images[i], null, null), params);
}
// We're done
writer.endWriteSequence();
}
}
}
Maven:
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-tiff</artifactId>
<version>3.2.1</version>
</dependency>
How can I create a multi-page tif from an image and the generated text-image?
I was able to get the following code to run for jpgs, but jpgs don't have layers.
public static void testWriteSequence() throws IOException {
BufferedImage[] images = new BufferedImage[] {
new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB),
new BufferedImage(110, 100, BufferedImage.TYPE_INT_RGB),
new BufferedImage(120, 100, BufferedImage.TYPE_INT_RGB),
new BufferedImage(130, 100, BufferedImage.TYPE_INT_RGB)
};
Color[] colors = {Color.BLUE, Color.GREEN, Color.RED, Color.ORANGE};
for (int i = 0; i < images.length; i++) {
BufferedImage image = images[i];
Graphics2D g2d = image.createGraphics();
try {
g2d.setColor(colors[i]);
g2d.fillRect(0, 0, 100, 100);
}
finally {
g2d.dispose();
}
}
//ImageWriter writer = createImageWriter();
ImageWriter writer = ImageIO.getImageWritersByFormatName("JPEG").next();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (ImageOutputStream output = ImageIO.createImageOutputStream(buffer)) {
writer.setOutput(output);
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writer.prepareWriteSequence(null);
params.setCompressionType("JPEG");
writer.writeToSequence(new IIOImage(images[0], null, null), params);
params.setCompressionType("JPEG");
writer.writeToSequence(new IIOImage(images[1], null, null), params);
params.setCompressionType("JPEG");
writer.writeToSequence(new IIOImage(images[2], null, null), params);
params.setCompressionType("JPEG");
writer.writeToSequence(new IIOImage(images[3], null, null), params);
writer.endWriteSequence();
File tempFile = new File("/path/to/new/file.jpg");
OutputStream out = new FileOutputStream(tempFile);
buffer.writeTo(out);
}
}
Thank you.
You can write multi-page images (in formats that supports it, like TIFF), using the standard ImageIO API. Now that Java ImageIO comes with a TIFF plugin bundled, starting from Java 9, the below should just work, with no extra dependencies. For Java 8 and earlier, you still need a TIFF plugin, like JAI or TwelveMonkeys as mentioned.
See for example the TIFFImageWriterTest.testWriteSequence method from the TwelveMonkeys ImageIO project's test cases, for an example of how to do it.
The important part:
BufferedImage[] images = ...
OutputStream stream = ... // May also use File here, as output
// Obtain a TIFF writer
ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
try (ImageOutputStream output = ImageIO.createImageOutputStream(stream)) {
writer.setOutput(output);
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// Compression: None, PackBits, ZLib, Deflate, LZW, JPEG and CCITT variants allowed
// (different plugins may use a different set of compression type names)
params.setCompressionType("Deflate");
writer.prepareWriteSequence(null);
for (BufferedImage image : images) {
writer.writeToSequence(new IIOImage(image, null, null), params);
}
// We're done
writer.endWriteSequence();
}
writer.dispose();

How to Read JPEG image into BufferedImage object using Java

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,

Java - Convert Image to Greyscale Using Array of Filenames

Is it possible to feed an array of image names into code which converts images to greyscale?
I am able to convert an image into greyscale by using this code:
public static void makeGrey() {
try{
//Read in original image.
BufferedImage image = ImageIO.read(new File("images\\012.jpg"));
//Obtain width and height of image.
double image_width = image.getWidth();
double image_height = image.getHeight();
BufferedImage bimg = null;
BufferedImage img = image;
//Draw the new image.
bimg = new BufferedImage((int)image_width, (int)image_height, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D gg = bimg.createGraphics();
gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
//Save new greyscale (output) image.
String temp = "_inverted";
File fi = new File("images\\" + temp + ".jpg");
ImageIO.write(bimg, "jpg", fi);
}
catch (Exception e){
System.out.println(e);
}
}
However, this code only works on a single file at a time and I would like to know how to go about getting it to work through all files located in the images directory?
I have created an array which goes through the images directory and stores the names of all of the files and I would like to know how to pass these filenames into my makeGrey() method?
static File dir = new File("images");
static File imgList[] = dir.listFiles();
public static void listFiles(String imageName) {
if(dir.isDirectory()){
for(File img : imgList){
if(img.isFile()){
MakeGrey.makeGrey();
}
}
}
Thank you.
Your makeGray() method should look like this:
public static void makeGrey(File image) {
try{
//Read in original image.
BufferedImage inputImage = ImageIO.read(image);
...
...
//Save new greyscale (output) image. (Or you'll rewrite same image all the time...)
File fi = new File("images\\inverted_" + image.getName()
...
...
and other part of the code should call it like this:
static File dir = new File("images");
static File imgList[] = dir.listFiles();
public static void listFiles(String imageName) {
if(dir.isDirectory()){
for(File img : imgList){
if(img.isFile()){
MakeGrey.makeGrey(img);
}
}
}

Categories

Resources