Tiff file not writing with ImageIO [duplicate] - java

I don't know what to do with TIFF images, but I can't read or write any of them using straight Java standard ImageIO library. Any thoughts?
Thanks.

If you don't like or can't use JAI for any reason I have written a TIFF ImageReader plugin for ImageIO, available on GitHub. It is pure Java and does not need any native installs, and comes with a very friendly open source license (BSD).
It supports any baseline TIFF option, along with a lot of standard extensions. From version 3.1 the TIFF plugin also has write support.
With the proper JARs in your class path, usage can be as simple as:
BufferedImage image = ImageIO.read(inputTIFF);
// ...modify image (compose, resize, sharpen, etc)...
ImageIO.write(image, "TIFF", outputTIFF);

According to JEP 262: TIFF Image I/O the TIFF plugin that used to be part of JAI will be available as part of the Java SE, starting from Java 9.
That means, using Java 9 or later, the following code will just work, without any extra imports or dependencies:
BufferedImage image = ImageIO.read(inputTIFF);
// ...modify image (compose, resize, sharpen, etc)...
ImageIO.write(image, "TIFF", outputTIFF);
I haven't yet been able to verify the support for non-baseline TIFF flavors in this plugin, but I assume at least baseline TIFFs should be fully supported.

I tried JAI, and it didn't work for me.
Where are you stuck? Does the following work for you?
import java.io.File;
import java.io.FileOutputStream;
import java.awt.image.RenderedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;
public class Main {
public static void main(String args[]) {
File file = new File("input.tif");
try {
SeekableStream s = new FileSeekableStream(file);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
RenderedImage op = new NullOpImage(dec.decodeAsRenderedImage(0),
null,
OpImage.OP_IO_BOUND,
null);
FileOutputStream fos = new FileOutputStream("output.jpg");
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(fos);
jpeg.encode(op.getData());
fos.close();
}
catch (java.io.IOException ioe) {
System.out.println(ioe);
}
}
}

Java supports TIFF format only from Java 9 release. If you are trying to use ImageIO for TIFF into older Java version it will give you exception.
If you want to use TIFF in earlier version as well, you Twelve Monkey plugin along with Java just by adding dependency of Twelve Monkey.
Maven Dependency for Twelve Monkey:
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-tiff</artifactId>
<version>3.5</version>
</dependency>*
I'm also giving example to merge the multiple images into Single TIFF with pages using Twelve Monkey,
BufferedImage b1 = null;
BufferedImage b2 = null;
TIFFImageReaderSpi SPI = new TIFFImageReaderSpi();
ImageReader imageReader1 = SPI.createReaderInstance();
ImageInputStream iis1 = ImageIO.createImageInputStream(new File("1.tif"));
imageReader1.setInput(iis1);
b1 = imageReader1.read(0);
ImageReader imageReader2 = SPI.createReaderInstance();
ImageInputStream iis2 = ImageIO.createImageInputStream(new File("2.tif"));
imageReader2.setInput(iis2);
b2 = imageReader2.read(0);
ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
writer.setOutput(ImageIO.createImageOutputStream(new File("3.tif")));
ImageWriteParam writeParam = writer.getDefaultWriteParam();
//writeParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
//writeParam.setCompressionType("Deflate");
writer.prepareWriteSequence(null);
IIOImage i1 = new IIOImage(b1, null, null);
IIOImage i2 = new IIOImage(b2, null, null);
writer.writeToSequence(i1, writeParam);
writer.writeToSequence(i2, writeParam);
writer.endWriteSequence();
writer.dispose();
The above code will work with Java8 and written to open two TIFF image and merge into single.
Also, you may use compression as needed. Just use comment lines to add compression.

Add Maven dependency :
<dependency>
<groupId>org.geotoolkit</groupId>
<artifactId>geotk-coverageio</artifactId>
<version>3.17</version>
</dependency>
Code example :
import org.geotoolkit.image.io.plugin.RawTiffImageReader;
IIORegistry registry = IIORegistry.getDefaultInstance();
registry.registerServiceProvider(new RawTiffImageReader.Spi());
String[] a = ImageIO.getReaderFileSuffixes();
for (int i=0; i<a.length; i++) {
System.out.println(a[i]);
}
BufferedImage image = ImageIO.read(new File("C:\\mypic.tiff"));
ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
ImageIO.write(image, "gif",new File("C:\\out.gif"));
ImageIO.write(image, "png",new File("C:\\out.png"));
ImageIO.write(image, "tif",new File("C:\\out.tiff"));

Related

Pink background colour in output TIFF when reading and writing some TIFF images with java ImageIO

I am attempting to merge a number of input TIFF files into a single multi-page output TIFF file using the open JDK 11 imageIO ImageReader and ImageWriter classes. My routine works correctly for almost all of my sample input files created from a number of different brands of scanning devices. These devices produce a variety of TIFF files using old and new JPEG compression. However, the TIFF files from one particular device result in an incorrect output that has a pink background. Even stranger, the TIFF produced with a portrait scan creates the correct output, while the TIFF produced with a landscape scan from the same device produces the incorrect output with a pink background. I can see no obvious difference between the 2 input files that would cause the difference in behaviour when processed by the ImageIO library.
I know that a pink background in the output usually indicates that there is a problem with transparency interpretation. I found a number of references to this issue when reading and writing JEPG images. However, I have not found any references to similar issues with TIFF images. When I walk through the ImageReader and ImageWriter in the debugger I can find no obvious difference between the input TIFF file that works and the file that produces the bad pink coloured output. Neither file has transparency. Both have the same YCbCr photometric interpretation, bands, and sub-sampling. The problematic TIFF file uses old JPEG compression, so the image write parameters explicitly specify new JPEG compression for ImageWriter. However, this is true for the similar portrait TIFF file that works correctly, so the problem must be more subtle than just the output compression.
Below is a simple command-line application that reproduces my issue.
package com.example;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataFormatImpl;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
public class Main {
private static final String TIFF_FORMAT = "tiff";
private static final String IMAGEIO_PLUGIN_PACKAGE = "com.sun.imageio.plugins.tiff";
//private static final String IMAGEIO_PLUGIN_PACKAGE = "com.github.jaiimageio.impl.plugins.tiff";
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("You must specify an input directory and output filename");
return;
}
File sourceDirectory = new File(args[0]);
if (!sourceDirectory.exists() || !sourceDirectory.isDirectory()) {
System.out.println(String.format("Source directory '%s' is invalid", args[0]));
}
File outputFile = new File(args[1]);
if (outputFile.exists()) {
outputFile.delete();
}
File inputFiles[] = sourceDirectory.listFiles();
mergeTiffFiles(inputFiles, outputFile);
}
/**
* Merge a list of TIFF files into a single output TIFF file using the Java ImageIO utilities.
*
* #param inputFilePaths list of input file paths to merge
* #param mergedFilePath destination path for the merged output file
*/
private static void mergeTiffFiles(
final File[] inputFilePaths,
final File mergedFilePath) {
ImageReader reader = null;
ImageWriter writer = null;
File inputFilePath = null;
try (
OutputStream outputStream = new FileOutputStream(mergedFilePath);
ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream)
) {
// Initialise the output writer
writer = getTiffWriter();
writer.setOutput(ios);
writer.prepareWriteSequence(null);
// Iterate through the source files appending the pages in order within and across files
reader = getTiffReader();
for (final File filePath : inputFilePaths) {
inputFilePath = filePath;
try (
FileInputStream inputFile = new FileInputStream(filePath);
ImageInputStream inputStream = ImageIO.createImageInputStream(inputFile)
) {
reader.setInput(inputStream);
int numImages = reader.getNumImages(true);
for (int j = 0; j < numImages; j++) {
IIOMetadata imageMetadata = reader.getImageMetadata(j); // 0, first image
ImageWriteParam writeParams = getTiffWriteParams(writer, imageMetadata);
BufferedImage image = reader.read(j);
writer.writeToSequence(new IIOImage(image, null, imageMetadata), writeParams);
}
}
}
inputFilePath = null;
// Finalize the output file
writer.endWriteSequence();
} catch (Exception e) {
if (inputFilePath != null) {
throw new IllegalStateException(String.format("Error while merging TIFF file: %s", inputFilePath), e);
} else {
throw new IllegalStateException("Failed to merge TIFFs files", e);
}
} finally {
// Cleanup the reader and writer
if (writer != null) {
writer.dispose();
}
if (reader != null) {
reader.dispose();
}
}
}
/**
* Get an TIFF reader used to read the source pages - ensure we use the imageIO plugin.
*
* #return an TIFF image reader.
* #throws IOException if an reader plugin cannot be found
*/
private static ImageReader getTiffReader() throws IOException {
ImageReader reader = null;
Iterator readers = ImageIO.getImageReadersByFormatName(TIFF_FORMAT);
if (readers.hasNext()) {
do {
reader = (ImageReader) readers.next();
} while (!reader.getClass().getPackage().getName().equals(IMAGEIO_PLUGIN_PACKAGE) && readers.hasNext());
}
if (reader == null) {
throw new IOException("No imageio readers for format: " + TIFF_FORMAT);
}
return reader;
}
/**
* Get a TIFF writer used to create the merged page - ensure we use the imageIO plugin
*
* #return a TIFF image writer
* #throws IOException if an writer plugin cannot be found
*/
private static ImageWriter getTiffWriter() throws IOException {
ImageWriter writer = null;
Iterator writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
if (writers.hasNext()) {
do {
writer = (ImageWriter) writers.next();
} while (!writer.getClass().getPackage().getName().equals(IMAGEIO_PLUGIN_PACKAGE) && writers.hasNext());
}
if (writer == null) {
throw new IOException("No imageio writers for format: " + TIFF_FORMAT);
}
return writer;
}
/**
* Get the appropriate TIFF write parameters to apply for an input with the given image meta-data.
* Check the source image compression. If possible use the same compression settings as those from the
* input image. However, the ImageIO library doesn't support the legacy JPEG compression format for TIFF
* images. Unfortunately, there are a number of devices that create scanned TIFF images of this type
* (Xerox, HP OXP). To support the merge operation explicitly force the new JPEG compression with a high
* quality value.
*
* #param writer TIFF image writer that will use the returned image parameters
* #param imageMetadata meta-data associated with the image to write
* #return the adjusted image write parameters
*/
private static ImageWriteParam getTiffWriteParams(ImageWriter writer, IIOMetadata imageMetadata) {
// Determine the source compression type
IIOMetadataNode root =
(IIOMetadataNode) imageMetadata.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
IIOMetadataNode compression =
(IIOMetadataNode) root.getElementsByTagName("CompressionTypeName").item(0);
String compressionName = compression.getAttribute("value");
ImageWriteParam writeParams = writer.getDefaultWriteParam();
if (compressionName.equalsIgnoreCase("Old JPEG")) {
// Convert to modern JPEG encoding if the source uses old JPEG compression.
writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParams.setCompressionType("JPEG");
double quality = 0.95;
quality = Math.max(0, Math.min(1, quality));
writeParams.setCompressionQuality((float) quality);
} else {
// Otherwise use the source image compression if possible
writeParams.setCompressionMode(ImageWriteParam.MODE_COPY_FROM_METADATA);
}
writeParams.setTilingMode(ImageWriteParam.MODE_COPY_FROM_METADATA);
return writeParams;
}
}
I expect the output of the similar landscape and portrait TIFFs to have the correct white background. I am obviously doing something wrong with the setup of the reading or writing procedure. However, there are not many options to try. The ImageReader only supports one image destination type for the TIFF files. The problem happens with the latest open JDK 11.0.4_11 version.
Okay, by inspecting the sample files, I think I have found the problem. And it's not in your code*.
When reading and writing TIFF with JPEG compression, the TIFF plugin will delegate decoding/encoding of the embedded JPEG stream to the JPEG plugin. In theory, this is simple, because the JPEG contains no color information, and the TIFF container contains the correct color information in the 262/PhotometricInterpretation tag.
In real life, this is much more complex, because sometimes the TIFF tag is missing or incorrect (especially in combination with 259/Compression tag with value 6 ("Old JPEG"). Or the JPEG encoder/decoder will make its own assumptions about color space (based on conventions for standalone JPEGs, typically JFIF or Exif), which is what I believe is the case here. The JPEG plugin bundled with the JRE uses the conventions documented here, and color space is inferred from the component ids in the SOFn marker.
For your files, we can see that the component ids differ.
Portrait file:
SOF0[ffc0, precision: 8, lines: 3520, samples/line: 2496,
components: [id: 1, sub: 1/1, sel: 0, id: 2, sub: 1/1, sel: 1, id: 3, sub: 1/1, sel: 1]]
Landscape file:
SOF0[ffc0, precision: 8, lines: 2496, samples/line: 3520,
components: [id: 0, sub: 1/1, sel: 0, id: 1, sub: 1/1, sel: 1, id: 2, sub: 1/1, sel: 1]]
The component ids in the portrait file are the normal 1, 2, and 3, while the landscape has ids 0, 1, and 2. Both files has no subsampling (ie. 1:1).
From the conventions:
If these values are 1-3 for a 3-channel image, then the image is assumed to be YCbCr [...]
Otherwise, 3-channel subsampled images are assumed to be YCbCr, 3-channel non-subsampled images are assumed to be RGB.
Because of this, the landscape image will be treated as already in RGB (and, incorrectly, not converted from YCbCr), resulting in the pinkish tint. Even though everything else in the TIFF container clearly indicates that it's YCbCr.
To fix this issue (and many other issues), I have created my own JPEG plugin that can be used as a drop-in replacement for the JRE plugin. It follows (the much simpler) conventions found in IJG's libJPEG, resulting in better color space consistency with other applications. In combination with the TIFF plugin from the same project, both your inputs are read correctly (white background). I have not tested it with the JRE TIFF plugin, but in theory, it should/could also work. Unfortunately, the TwelveMonkeys TIFF plugin does not (yet)
have the write capabilities you use (tiling) and has some limitations about what meta data it writes.
PS: As you seem to deal mainly with JPEGs that degrade in quality when re-encoding, you might want to look at merging TIFFs without decoding the image data. You can find an example of that in TIFFUtilities, written by Oliver Schmidtmer.
*) It is technically possible to work around the problem in your code, but it's kind of complex to handle all the cases correctly. If you want to implement this yourself, or are just curious I suggest you have a look at the source code for the TwelveMonkeys ImageIO JPEG plugin.

Convert svg image to png in java by servlet

Here, I am trying to send a SVG image to local server and in output I want to download that image in PNG / JPEG format.
While I have found some solutions but those are done by BATIK libraries, but in my Eclipse BATIK libraries are not supported , so I can't use the batik libraries.
Use batik library. Below is the code.
import java.io.*;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import java.nio.file.Paths;
import java.nio.file.Path;
public class svg2png {
public static void main(String[] args) throws Exception {
//Step -1: We read the input SVG document into Transcoder Input
//We use Java NIO for this purpose
String svg_URI_input = Paths.get("chessboard.svg").toUri().toURL().toString();
TranscoderInput input_svg_image = new TranscoderInput(svg_URI_input);
//Step-2: Define OutputStream to PNG Image and attach to TranscoderOutput
OutputStream png_ostream = new FileOutputStream("chessboard.png");
TranscoderOutput output_png_image = new TranscoderOutput(png_ostream);
// Step-3: Create PNGTranscoder and define hints if required
PNGTranscoder my_converter = new PNGTranscoder();
// Step-4: Convert and Write output
my_converter.transcode(input_svg_image, output_png_image);
// Step 5- close / flush Output Stream
png_ostream.flush();
png_ostream.close();
}
}
Hope it will help you.
Refer this: http://thinktibits.blogspot.com/2012/12/Batik-Convert-SVG-PNG-Java-Program-Example.html
You can also convert svg to png format without the use of Batik Transcoder.
BufferedImage input_image = null;
input_image = ImageIO.read(new File("Convert_to_PNG.svg")); //read svginto input_image object
File outputfile = new File("imageio_png_output.png"); //create new outputfile object
ImageIO.write(input_image, "PNG", outputfile);
By simply using the ImageIO library. Hope this will help!

Storing DPI and Paper Size information in a JPEG with Java

I have the following code:
ImageIO.write(originalImage, OUTPUT_TYPE, resultOutput);
This is an invocation of the following javax.imageio.ImageIO method:
public static boolean write(RenderedImage im,
String formatName,
File output)
throws IOException
This turns an original BMP image into a JGP output. Is it possible to also store DPI and Paper Size information in the JPEG to aid in printing operations?
I found this post for setting DPI on PNG Files. It pointed out that you should use 'metadata.mergeTree' to properly save your metadata.
With that in mind, here is some working groovy code that takes a BMP file and creates a JPG file at arbitrary DPI:
import java.awt.image.BufferedImage
import java.io.File
import java.util.Hashtable
import java.util.Map
import javax.imageio.*
import javax.imageio.stream.*
import javax.imageio.metadata.*
import javax.imageio.plugins.jpeg.*
import org.w3c.dom.*
File sourceFile = new File("sample.bmp")
File destinationFile = new File("sample.jpg")
dpi = 100
BufferedImage sourceImage = ImageIO.read(sourceFile)
ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(destinationFile);
imageWriter.setOutput(ios);
def jpegParams = imageWriter.getDefaultWriteParam();
IIOMetadata data = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(sourceImage), jpegParams);
Element tree = (Element)data.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0);
jfif.setAttribute("Xdensity", Integer.toString(dpi));
jfif.setAttribute("Ydensity", Integer.toString(dpi));
jfif.setAttribute("resUnits", "1"); // density is dots per inch
data.mergeTree("javax_imageio_jpeg_image_1.0",tree)
// Write and clean up
imageWriter.write(data, new IIOImage(sourceImage, null, data), jpegParams);
ios.close();
imageWriter.dispose();
Worked fine for me in that OSX's Preview app and Gimp both reported that the resulting image was 100 DPI. As to Paper Size...I imagine this is directly determined by DPI? I couldn't find any JPEG property that would set that particular value.
You may consider using Commons Sanselan, instead of ImageIO for this task.
See http://commons.apache.org/sanselan/whysanselan.html for more info.

Can't read and write a TIFF image file using Java ImageIO standard library

I don't know what to do with TIFF images, but I can't read or write any of them using straight Java standard ImageIO library. Any thoughts?
Thanks.
If you don't like or can't use JAI for any reason I have written a TIFF ImageReader plugin for ImageIO, available on GitHub. It is pure Java and does not need any native installs, and comes with a very friendly open source license (BSD).
It supports any baseline TIFF option, along with a lot of standard extensions. From version 3.1 the TIFF plugin also has write support.
With the proper JARs in your class path, usage can be as simple as:
BufferedImage image = ImageIO.read(inputTIFF);
// ...modify image (compose, resize, sharpen, etc)...
ImageIO.write(image, "TIFF", outputTIFF);
According to JEP 262: TIFF Image I/O the TIFF plugin that used to be part of JAI will be available as part of the Java SE, starting from Java 9.
That means, using Java 9 or later, the following code will just work, without any extra imports or dependencies:
BufferedImage image = ImageIO.read(inputTIFF);
// ...modify image (compose, resize, sharpen, etc)...
ImageIO.write(image, "TIFF", outputTIFF);
I haven't yet been able to verify the support for non-baseline TIFF flavors in this plugin, but I assume at least baseline TIFFs should be fully supported.
I tried JAI, and it didn't work for me.
Where are you stuck? Does the following work for you?
import java.io.File;
import java.io.FileOutputStream;
import java.awt.image.RenderedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;
public class Main {
public static void main(String args[]) {
File file = new File("input.tif");
try {
SeekableStream s = new FileSeekableStream(file);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
RenderedImage op = new NullOpImage(dec.decodeAsRenderedImage(0),
null,
OpImage.OP_IO_BOUND,
null);
FileOutputStream fos = new FileOutputStream("output.jpg");
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(fos);
jpeg.encode(op.getData());
fos.close();
}
catch (java.io.IOException ioe) {
System.out.println(ioe);
}
}
}
Java supports TIFF format only from Java 9 release. If you are trying to use ImageIO for TIFF into older Java version it will give you exception.
If you want to use TIFF in earlier version as well, you Twelve Monkey plugin along with Java just by adding dependency of Twelve Monkey.
Maven Dependency for Twelve Monkey:
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-tiff</artifactId>
<version>3.5</version>
</dependency>*
I'm also giving example to merge the multiple images into Single TIFF with pages using Twelve Monkey,
BufferedImage b1 = null;
BufferedImage b2 = null;
TIFFImageReaderSpi SPI = new TIFFImageReaderSpi();
ImageReader imageReader1 = SPI.createReaderInstance();
ImageInputStream iis1 = ImageIO.createImageInputStream(new File("1.tif"));
imageReader1.setInput(iis1);
b1 = imageReader1.read(0);
ImageReader imageReader2 = SPI.createReaderInstance();
ImageInputStream iis2 = ImageIO.createImageInputStream(new File("2.tif"));
imageReader2.setInput(iis2);
b2 = imageReader2.read(0);
ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
writer.setOutput(ImageIO.createImageOutputStream(new File("3.tif")));
ImageWriteParam writeParam = writer.getDefaultWriteParam();
//writeParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
//writeParam.setCompressionType("Deflate");
writer.prepareWriteSequence(null);
IIOImage i1 = new IIOImage(b1, null, null);
IIOImage i2 = new IIOImage(b2, null, null);
writer.writeToSequence(i1, writeParam);
writer.writeToSequence(i2, writeParam);
writer.endWriteSequence();
writer.dispose();
The above code will work with Java8 and written to open two TIFF image and merge into single.
Also, you may use compression as needed. Just use comment lines to add compression.
Add Maven dependency :
<dependency>
<groupId>org.geotoolkit</groupId>
<artifactId>geotk-coverageio</artifactId>
<version>3.17</version>
</dependency>
Code example :
import org.geotoolkit.image.io.plugin.RawTiffImageReader;
IIORegistry registry = IIORegistry.getDefaultInstance();
registry.registerServiceProvider(new RawTiffImageReader.Spi());
String[] a = ImageIO.getReaderFileSuffixes();
for (int i=0; i<a.length; i++) {
System.out.println(a[i]);
}
BufferedImage image = ImageIO.read(new File("C:\\mypic.tiff"));
ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
ImageIO.write(image, "gif",new File("C:\\out.gif"));
ImageIO.write(image, "png",new File("C:\\out.png"));
ImageIO.write(image, "tif",new File("C:\\out.tiff"));

Image transcoding (JPEG to PNG) with Java

In my Java application I would like to download a JPEG, transfer it to a PNG and do something with the resulting bytes.
I am almost certain I remember a library to do this exists, I cannot remember its name.
This is what I ended up doing, I was thinking toooo far outside of the box when I asked the question..
// these are the imports needed
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
// read a jpeg from a inputFile
BufferedImage bufferedImage = ImageIO.read(new File(inputFile));
// write the bufferedImage back to outputFile
ImageIO.write(bufferedImage, "png", new File(outputFile));
// this writes the bufferedImage into a byte array called resultingBytes
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOut);
byte[] resultingBytes = byteArrayOut.toByteArray();
ImageIO can be used to load JPEG files and save PNG files (also into a ByteArrayOutputStream if you don't want to write to a file).
javax.imageio should be enough.
Put your JPEG to BufferedImage, then save it with:
File file = new File("newimage.png");
ImageIO.write(myJpegImage, "png", file);
BufferedImage bufferGambar;
try {
bufferGambar = ImageIO.read(new File("ImagePNG.png"));
// pkai type INT karna bertipe integer RGB bufferimage
BufferedImage newBufferGambar = new BufferedImage(bufferGambar.getWidth(), bufferGambar.getHeight(), BufferedImage.TYPE_INT_RGB);
newBufferGambar.createGraphics().drawImage(bufferGambar, 0, 0, Color.white, null);
ImageIO.write(newBufferGambar, "jpg", new File("Create file JPEG.jpg"));
JOptionPane.showMessageDialog(null, "Convert to JPG succes YES");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}

Categories