Skip to content

Instantly share code, notes, and snippets.

@balamuru
Created October 24, 2014 23:20
Show Gist options
  • Save balamuru/d48e90b74ce89b5ce580 to your computer and use it in GitHub Desktop.
Save balamuru/d48e90b74ce89b5ce580 to your computer and use it in GitHub Desktop.
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class GrayScaleImaging {
public static void main(String[] args)
throws IOException {
//works
final File inputFile = new File("/home/vinayb/Downloads/page1_color.tif");
final File outputFile = new File("/home/vinayb/Downloads/page1_color_mod.tif");
//doesn't work
// final File inputFile = new File("/home/vinayb/Downloads/page1_grayscale.tif");
// final File outputFile = new File("/home/vinayb/Downloads/page1_grayscale_mod.tif");
if (outputFile.exists()) {
outputFile.delete();
}
ImageReader imageReader = null;
ImageWriter imageWriter = null;
Graphics2D g = null;
try (final ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputFile);
final ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputFile);) {
//setup reader
imageReader = ImageIO.getImageReaders(imageInputStream).next();
imageReader.setInput(imageInputStream);
//read image
final BufferedImage bufferedImage = imageReader.read(0);
//prepare graphics for the output
g = bufferedImage.createGraphics();
//draw image
g.drawImage(bufferedImage, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), null);
//setup writer based on reader
imageWriter = ImageIO.getImageWriter(imageReader);
imageWriter.setOutput(imageOutputStream);
//write
imageWriter.write(null, new IIOImage(bufferedImage, null, imageReader.getImageMetadata(0)), imageWriter.getDefaultWriteParam());
} finally {
//cleanup
if (imageWriter != null) {
imageWriter.dispose();
}
if (imageReader != null) {
imageReader.dispose();
}
if (g != null) {
g.dispose();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment