How to converting TIFF image file to Bitmap Android - java

I would like to convert images on SDcard to bitmap. I am using below code
String filepath = "/storage/emulated/0/Download/sample2.tif";
Bitmap bm = BitmapFactory.decodeFile(filepath);
This code is working fine for file with extension .jpg or .png but not for .tif or .tiff. For TIFF files bmbecomes null no exceptions nothing all file paths are valid.
Is there any limitation in Android BitmapFactory with respect to decoding TIFF images?
Also tried decodeByteArray and decodeStream, looks like limitation for me.
I am able to read TIFF image file as byte [] but conversion of byte[] or file input stream as bitmap is returning null
Please let me know any other way to convert TIFF Image file to Bitmap.

As VERT9x said TIFF files are not supported on android. But you can convert them back or forth using native android library like https://github.com/puelocesar/android-lib-magick . This is sample code to convert jpg to tif. Hope this helps.
MagickImage Image = new MagickImage(new ImageInfo(IMAGE_PATH));
// Image = Image.scaleImage(800, 800);
Image.setImageFormat("tif");
Image.setFileName(str);
ImageInfo localImageInfo = new ImageInfo(str);
localImageInfo.setMagick("tif");
Image.writeImage(localImageInfo);
// store as tif
byte[] blob = Image.imageToBlob(localImageInfo);
FileOutputStream localFileOutputStream = new FileOutputStream(str);
localFileOutputStream.write(blob);
localFileOutputStream.close();

To decode a simple color tif file go as below:
String taginfo="";String strVal=""; //These are Tiff Tags
FileInputStream fis;BufferedInputStream bis;DataInputStream dis;
path=Environment.getExternalStorageDirectory().getPath();
path=path+"/DCIM"+"/fileName.tif"; //whatever is your file-name.tif
try{
fis=new FileInputStream(path);
bis=new bufferedInputStream(fis);
dis=new DataInputStream(bis);
dis.skip(4); //skip 4 byte marker of TIFF+endian
ifd=myInt(dis.readInt()); //read the 4 byte IFD-location
txt="TIFF-IFD: "; //txt is the final text displayed in textView
txt=txt+ifd;
dis.skip(ifd-8);
entries=myShort(dis.readShort()); //read in your endian-style
txt=txt+"\nNo.OfEntries="+entries;
for(int i=0;i<=entries;i++)
{
tag=myShort( dis.readShort() );
taginfo=tagInfo(tag); //tagInfo function returns info associated
//with tag
type=myShort( dis.readShort() );
count=myInt( dis.readInt() );
value=myInt( dis.readInt() );
if(type==3)strVal="Value="; else strVal="Offset=";
if( strVal.equals("Offset=") )
{
if( taginfo.equals("StripOffsets") ) //image is stored as
{stripAt=value;stripCount=count;} // strips of rows
if( taginfo.equals("StripBytes") )
{stripBytesAt=value;}
}
if( taginfo.equals("width") ){cols=value;}
if( taginfo.equals("length") ){rows=value;}
txt=txt+"\ntag="+tag+"" + tagInfo(tag) + ",type=" + type +
",count=" + count + strVal + value;
}
dis.close();bis.close();fis.close();
}catch(Exception e) { txt = txt + "\nerror=" + e.toString(); }
txt=txt+"\nNo.OfStrips="+stripCount+",array of strip locations at:
"+stripAt+" and array of bytesPerStrip at "+stripBytesAt ;
extractBMP(); // a function you will define to combine all strips to
//bitmap image
}
public int myShort(short sh)
{ int i;
ByteBuffer shortBuff=ByteBuffer.allocate(4);
shortBuff.order(ByteOrder.BIG_ENDIAN);shortBuff.putShort(sh);shortBuff.rewind();
shortBuff.order(ByteOrder.LITTLE_ENDIAN);sh=shortBuff.getShort();
if(sh<0)i=(int)(sh+32768); else i=(int)sh;
return i;
}
public long myInt(int i)
{ long l=0L;
ByteBuffer intBuff=ByteBuffer.allocate(4);
intBuff.order(ByteOrder.BIG_ENDIAN);intBuff.putInt(i);intBuff.rewind();
intBuff.order(ByteOrder.LITTLE_ENDIAN); i=intBuff.getInt();
if(i<0)l=(long)(i+2147483648L); else l=(long)i;
return l;
}
public String tagInfo(int tag)
{ int i=0;
switch(tag)
{case 256: i=0;break;case 257: i=1;break;case 258: i=2;break;case 259: i=3;break;case 262: i=4;break;case 266: i=5;break;
case 273: i=6;break;case 277: i=7;break;case 278: i=8;break;case 279: i=9;break;case 282: i=10;break;case 283: i=11;break;
case 284: i=12;break;case 296: i=13;break;case 1496: i=14;break;case 0: i=15;break;
}
return info[i];
}
If you wish to see the full code then see here:
Decode Tiff Image in Android Java Code

TIFF files are not supported natively on Android. Check the list of supported media formats.
If you want to support TIFF files you'll have to decode them manually yourself or find a library that does it for you.

Try to use my lib. It support dirrect convert from tiff to jpg/png/bmp
https://github.com/Beyka/Android-TiffBitmapFactory

Related

Same Image, but different base64

I used the following function to create a base64 encoded string of my Gravatar image (https://www.gravatar.com/avatar/cd5415f97afbe0177ba35ae31fbfd0db):
final BASE64Encoder encoder = new BASE64Encoder();
String encoded = encoder.encode(inputStreamToByteArray(is));
encoded = encoded.replaceAll("\r?\n", "");
return encoded;
I ran the method a couple of days ago and got the following base64 encoded string:
/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2ODApLCBxdWFsaXR5ID0gOTAK/9sAQwADAgIDAgIDAwMDBAMDBAUIBQUEBAUKBwcGCAwKDAwLCgsLDQ4SEA0OEQ4LCxAWEBETFBUVFQwPFxgWFBgSFBUU/9sAQwEDBAQFBAUJBQUJFA0LDRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU/8AAEQgAUABQAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxM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f8/M2lzIl8LeCNY8QTTfb8nS1YLDfXFv5Es692EW4kf8Cxnr7VvXvwYtTG3karI67SvkzJwR6d69GbNQSZxXRHJcJCXPBNPybt92qIdVtWZ8pa18IPF3gG8lv9FRNQst5d9PcEDbnOVI6EcnH4jnp714D8ZyeLtAgmvIZbbUUQCSKcgsw9cjhvTI9u+a6t2IrktSspvD9019p6O+nyuHvLKLqP+mkYHf1UD1wDyretQoqm/el8/wDP/Mwcn0N+SQiqNxLwabFfxXao0UqTRSr5kMyEFZU9R7jIyO2R1BBMc4JNdMouO41K+p3axDFO8oEEEZHoasLEKf5dZXLsfKPxZ+GVlfeMrmxFjiBvmVjIAHZlJznPB5xgjGBWD4d+Gt5oeq2l5oms2cJjuFnitLpyQcbWYg9uADgAn5RwK+ivi9o8j6db6jbxgyxN5Urs+1VQ8hm4PAOfT72OQa86svDGm3FpHcXEz3+pO8bxf6RujR1fIaRVQuUGOQOoI46Gvgsfia2Aqypxdo9Pn/W/kdtOKnG57mgE0Ecisrh1DBk6HPce1RPHioPCt9HqOmsFuorp43OfLcNhTyue447MAeOlackXtX2uFrrE0IVVpdf8P+JxTg4yaMiWPFVJIyDWxLD7VTlhxXXcyOB8ReHrm0El3pTMil/Ne2QZ2SdfNjHqedydHBP8RO6Tw34ii8R2sn3Uu4CFmiU5APZl9VPb8R1BrsJIPSudj8H29p4kk1i3/cyTxGOeID5XOc7vY+v+JJovpYLH/9k=
Just today I executed the method again, using the same image. But instead of retrieving the same encoded string, I received:
/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBxdWFsaXR5ID0gOTAK/9sAQwADAgIDAgIDAwMDBAMDBAUIBQUEBAUKBwcGCAwKDAwLCgsLDQ4SEA0OEQ4LCxAWEBETFBUVFQwPFxgWFBgSFBUU/9sAQwEDBAQFBAUJBQUJFA0LDRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQ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OoI46Gvgsfia2Aqypxfu9PmdtOKmrnuaATQRyKyuHUMGToc9x7VE8eKg8K30eo6awW6iunjc58tw2FPK57j6MAeOlackXtX2uFrrE0Y1V1RxTg4yaMiWPFVJIyK2JYfaqcsOK67mRwXiLw9c2gku9KZkUv5r2yDOyTr5sY9TzuTo4J7k7n+G/EUXiO1k+6l3AQs0SnIB7Mvqp7fiOoNdhJB6VzsfhC3tPEkmsW/7mSeIxzxAfK5znd7HPX/Ek0X0sFj//2Q==
As you may notice, the first couple of characters are the same, but if you look at the end of the strings, you notice directly that they are completely different. Why is that? The image is still my Gravatar image (e.g., using http://codebeautify.org/base64-to-image-converter shows the same image for both strings).
Thanks for any hint, explanation! Is there anything wrong with my implementation? Is some of the implementation time or location dependent? How can I get the same base64 string for the same image?
PS: inputStreamToByteArray is implemented as follows:
public static byte[] inputStreamToByteArray(final InputStream is) {
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final byte[] data = new byte[16384];
try {
int nRead;
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
} catch (final IOException e) {
return null;
} finally {
try {
buffer.close();
} catch (final IOException e) {
// ignore
}
}
return buffer.toByteArray();
}
Converting both images back to .jpg, and using http://regex.info/exif.cgi, the following header comments appear:
One:
CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 90
Other:
CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90
(can't remember which order I converted the images in, but there is a version change either way)
As you can see, they have upgraded the JPEG compressor (or spec?) to a newer version, resulting in a different JPEG encoding, or at least difference in the comments.
So to answer your question, there does not seem to be an issue with your base64 converter, but just that the two images actually are different

Image Not converting properly from tiff to jpg [duplicate]

recently i'm facing problem when try to display an image file. Unfortunately, the image format is TIFF format which not supported by major web browser (as i know only Safari support this format). Due to certain constraint, i have to convert this format to others format that supported by major browser. However, it bring a lots of problem for me when i try to converting the format.
I had search through the web and although there been posted similar issue in this link How do I convert a TIF to PNG in Java?" but i can't have the result as it proposed..
Therefore i raise this Question again to wish that can have better explanation and guideline from you all..
There were few issue i'm faced during go through with the solution that proposed:
1) According to the answer that proposed by Jonathan Feinberg, it need to install JAI and JAI/ImageIO.
However, after i installed both of them i still couldn't import the file in Netbean 7.2. NetBean 7.2 remain propose import default imageIO library.
2) when i'm using default ImageIO library Read method, it will return NULL value and i cannot continue to proceed.
3) I also tried others method such as convert TIFF file to BIN File by using BufferedOutputStream method but the result file is greater than 11 MB which is too large to load and end up loading failed.
if (this.selectedDO != null) {
String tempDO = this.selectedDO.DONo;
String inPath = "J:\\" + tempDO + ".TIF";
String otPath = "J:\\" + tempDO + ".bin";
File opFile = new File(otPath);
File inFile = new File(inPath);
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(inPath), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(new FileOutputStream(otPath), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
try {
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Hence, hope that can get help and advise from you all so that i can convert TIFF format to other format such as JPEG/PNG.
Had gone through some study and testing, found a method to convert TIFF to JPEG and sorry for pending so long only uploaded this answer.
SeekableStream s = new FileSeekableStream(inFile);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
RenderedImage op = dec.decodeAsRenderedImage(0);
FileOutputStream fos = new FileOutputStream(otPath);
JPEGEncodeParam jpgparam = new JPEGEncodeParam();
jpgparam.setQuality(67);
ImageEncoder en = ImageCodec.createImageEncoder("jpeg", fos, jpgparam);
en.encode(op);
fos.flush();
fos.close();
otPath is the path that you would like to store your JPEG image.
For example: "C:/image/abc.JPG";
inFile is the input file which is the TIFF file
At least this method is workable to me. If there is any other better method, kindly share along with us.
EDIT: Just want to point out an editing in order to handle multipage tiff. Obviously you also have to handle the different names for the resulting images:
for (int page = 0; page < dec.getNumPages(); page++) {
RenderedImage op = dec.decodeAsRenderedImage(page );
...
}
Add dependency
<dependency>
<groupId>com.github.jai-imageio</groupId>
<artifactId>jai-imageio-core</artifactId>
<version>1.3.1</version> </dependency>
https://mvnrepository.com/artifact/com.github.jai-imageio/jai-imageio-core
https://mvnrepository.com/artifact/com.github.jai-imageio/jai-imageio-core/1.3.1
Coding
final BufferedImage tif = ImageIO.read(new File("test.tif"));
ImageIO.write(tif, "png", new File("test.png"));
In case of many pages, working following:
add dependency:
<dependency>
<groupId>com.github.jai-imageio</groupId>
<artifactId>jai-imageio-core</artifactId>
<version>1.4.0</version>
</dependency>
use following Java8 code
public void convertTiffToPng(File file) {
try {
try (InputStream is = new FileInputStream(file)) {
try (ImageInputStream imageInputStream = ImageIO.createImageInputStream(is)) {
Iterator<ImageReader> iterator = ImageIO.getImageReaders(imageInputStream);
if (iterator == null || !iterator.hasNext()) {
throw new RuntimeException("Image file format not supported by ImageIO: " + file.getAbsolutePath());
}
// We are just looking for the first reader compatible:
ImageReader reader = iterator.next();
reader.setInput(imageInputStream);
int numPage = reader.getNumImages(true);
// it uses to put new png files, close to original example n0_.tiff will be in /png/n0_0.png
String name = FilenameUtils.getBaseName(file.getAbsolutePath());
String parentFolder = file.getParentFile().getAbsolutePath();
IntStream.range(0, numPage).forEach(v -> {
try {
final BufferedImage tiff = reader.read(v);
ImageIO.write(tiff, "png", new File(parentFolder + "/png/" + name + v + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
If your target is Android, you could try this great Java library on Github that provides many utilities for handling, opening, and writing .tiff files.
A simple example from that Git showng how to convert TIFF to JPEG:
TiffConverter.ConverterOptions options = new TiffConverter.ConverterOptions();
//Set to true if you want use java exception mechanism
options.throwExceptions = false;
//Available 128Mb for work
options.availableMemory = 128 * 1024 * 1024;
//Number of tiff directory to convert;
options.readTiffDirectory = 1;
//Convert to JPEG
TiffConverter.convertTiffJpg("in.tif", "out.jpg", options, progressListener);
First, take a look to What is the best java image processing library/approach?. For your code you can use
javax.imageio.ImageIO.write(im, type, represFile);
like you can see in write an image to file example.

Issue with reading Tiff image metadata with imageIO

I'm writing a program that is supposed to taking in a bunch of tiff's and put them together. I got it to work for most of the image files I read in but a large batch of them throw out an error when I try to read them in.
Here is a snippet of code I have:
int numPages = 0;
inStream = ImageIO.createImageInputStream(imageFile);
reader.setInput(inStream);
while(true){
bufferedImages.add(reader.readAll(numPages, reader.getDefaultReadParam()));
numPages++;
}
Yes I catch the out of bounds exception so we don't have to worry about that. My problem is that I get the following error:
javax.imageio.IIOException: I/O error reading image metadata!
at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.readMetadata(TIFFImageReader.java:340)
at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.seekToImage(TIFFImageReader.java:310)
at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.prepareRead(TIFFImageReader.java:971)
at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.read(TIFFImageReader.java:1153)
at javax.imageio.ImageReader.readAll(ImageReader.java:1067)
at sel.image.appender.ImageAppender.mergeImages(ImageAppender.java:59)
at sel.imagenow.processor.AetnaLTCProcessor.processBatch(AetnaLTCProcessor.java:287)
at sel.imagenow.processor.AetnaLTCProcessor.processImpl(AetnaLTCProcessor.java:81)
at sel.processor.AbstractImageNowProcessor.process(AbstractImageNowProcessor.java:49)
at sel.RunConverter.main(RunConverter.java:37)
Caused by: java.io.EOFException
at javax.imageio.stream.ImageInputStreamImpl.readShort(ImageInputStreamImpl.java:229)
at javax.imageio.stream.ImageInputStreamImpl.readUnsignedShort(ImageInputStreamImpl.java:242)
at com.sun.media.imageioimpl.plugins.tiff.TIFFIFD.initialize(TIFFIFD.java:194)
at com.sun.media.imageioimpl.plugins.tiff.TIFFImageMetadata.initializeFromStream(TIFFImageMetadata.java:110)
at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.readMetadata(TIFFImageReader.java:336)
... 9 more
I did make sure to add in the right JAI lib and my reader is using the "TIFF" type so the reader (and writer) is correct but for some reason the metadata is wrong. Now I can open and view all these images normally in windows so they really aren't corrupted or anything. Java just doesn't want to read them in right. Since I'm just using the stream meatadata to write them out later I don't care that much about the metadata I just need it to read in the file to the list so I can append it. I did find a writer.replaceImageMetaData method on the writer but the TIFFwriter version of IOWriter doens't have code for it. I'm stuck, anyone anything? Is there maybe a way to read in parts of the metadata to see what is wrong and fix it?
For anyone that would like to know I ended up fixing my own issue. It seems the the image metadata was a bit screwed up. Since I was just doing a plain merge and since I knew each image was one page I was able to use a buffered image to read in the picture then make it a IIOImage with null metadata. I used the stream metadata (which worked) to merge the images. Here is my complete method I use to merge a list of images:
public static File mergeImages(List<File> files, String argID, String fileType, String compressionType) throws Exception{
//find the temp location of the image
String location = ConfigManager.getInstance().getTempFileDirectory();
logger_.debug("image file type [" + fileType + "]");
ImageReader reader = ImageIO.getImageReadersByFormatName(fileType).next();
ImageWriter writer = ImageIO.getImageWritersByFormatName(fileType).next();
//set up the new image name
String filePath = location + "\\" + argID +"." + fileType;
//keeps track of the images we copied from
StringBuilder builder = new StringBuilder();
List<IIOImage> bufferedImages = new ArrayList<IIOImage>();
IIOMetadata metaData = null;
for (File imageFile:files) {
//get the name for logging later
builder.append(imageFile.getCanonicalPath()).append("\n");
if (metaData == null){
reader.setInput(ImageIO.createImageInputStream(imageFile));
metaData = reader.getStreamMetadata();
}
BufferedImage image = ImageIO.read(imageFile);
bufferedImages.add(new IIOImage(image, null, null));
}
ImageWriteParam params = writer.getDefaultWriteParam();
if (compressionType != null){
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
params.setCompressionType(compressionType);
}
ImageOutputStream outStream = null;
try{
outStream = ImageIO.createImageOutputStream(new File(filePath));
int numPages = 0;
writer.setOutput(outStream);
for(IIOImage image:bufferedImages){
if (numPages == 0){
writer.write(metaData, image, params);
}
else{
writer.writeInsert(numPages, image, params);
}
numPages++;
}
}
finally{
if (outStream != null){
outStream.close();
}
}
//set up the file for us to use later
File mergedFile = new File(filePath);
logger_.info("Merged image into [" + filePath + "]");
logger_.debug("Merged images [\n" + builder.toString() + "] into --> " + filePath);
return mergedFile;
}
I hope this help someone else because I know there isn't much on this issue that I could find.

How to convert TIFF to JPEG/PNG in java

recently i'm facing problem when try to display an image file. Unfortunately, the image format is TIFF format which not supported by major web browser (as i know only Safari support this format). Due to certain constraint, i have to convert this format to others format that supported by major browser. However, it bring a lots of problem for me when i try to converting the format.
I had search through the web and although there been posted similar issue in this link How do I convert a TIF to PNG in Java?" but i can't have the result as it proposed..
Therefore i raise this Question again to wish that can have better explanation and guideline from you all..
There were few issue i'm faced during go through with the solution that proposed:
1) According to the answer that proposed by Jonathan Feinberg, it need to install JAI and JAI/ImageIO.
However, after i installed both of them i still couldn't import the file in Netbean 7.2. NetBean 7.2 remain propose import default imageIO library.
2) when i'm using default ImageIO library Read method, it will return NULL value and i cannot continue to proceed.
3) I also tried others method such as convert TIFF file to BIN File by using BufferedOutputStream method but the result file is greater than 11 MB which is too large to load and end up loading failed.
if (this.selectedDO != null) {
String tempDO = this.selectedDO.DONo;
String inPath = "J:\\" + tempDO + ".TIF";
String otPath = "J:\\" + tempDO + ".bin";
File opFile = new File(otPath);
File inFile = new File(inPath);
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(inPath), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(new FileOutputStream(otPath), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
try {
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Hence, hope that can get help and advise from you all so that i can convert TIFF format to other format such as JPEG/PNG.
Had gone through some study and testing, found a method to convert TIFF to JPEG and sorry for pending so long only uploaded this answer.
SeekableStream s = new FileSeekableStream(inFile);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
RenderedImage op = dec.decodeAsRenderedImage(0);
FileOutputStream fos = new FileOutputStream(otPath);
JPEGEncodeParam jpgparam = new JPEGEncodeParam();
jpgparam.setQuality(67);
ImageEncoder en = ImageCodec.createImageEncoder("jpeg", fos, jpgparam);
en.encode(op);
fos.flush();
fos.close();
otPath is the path that you would like to store your JPEG image.
For example: "C:/image/abc.JPG";
inFile is the input file which is the TIFF file
At least this method is workable to me. If there is any other better method, kindly share along with us.
EDIT: Just want to point out an editing in order to handle multipage tiff. Obviously you also have to handle the different names for the resulting images:
for (int page = 0; page < dec.getNumPages(); page++) {
RenderedImage op = dec.decodeAsRenderedImage(page );
...
}
Add dependency
<dependency>
<groupId>com.github.jai-imageio</groupId>
<artifactId>jai-imageio-core</artifactId>
<version>1.3.1</version> </dependency>
https://mvnrepository.com/artifact/com.github.jai-imageio/jai-imageio-core
https://mvnrepository.com/artifact/com.github.jai-imageio/jai-imageio-core/1.3.1
Coding
final BufferedImage tif = ImageIO.read(new File("test.tif"));
ImageIO.write(tif, "png", new File("test.png"));
In case of many pages, working following:
add dependency:
<dependency>
<groupId>com.github.jai-imageio</groupId>
<artifactId>jai-imageio-core</artifactId>
<version>1.4.0</version>
</dependency>
use following Java8 code
public void convertTiffToPng(File file) {
try {
try (InputStream is = new FileInputStream(file)) {
try (ImageInputStream imageInputStream = ImageIO.createImageInputStream(is)) {
Iterator<ImageReader> iterator = ImageIO.getImageReaders(imageInputStream);
if (iterator == null || !iterator.hasNext()) {
throw new RuntimeException("Image file format not supported by ImageIO: " + file.getAbsolutePath());
}
// We are just looking for the first reader compatible:
ImageReader reader = iterator.next();
reader.setInput(imageInputStream);
int numPage = reader.getNumImages(true);
// it uses to put new png files, close to original example n0_.tiff will be in /png/n0_0.png
String name = FilenameUtils.getBaseName(file.getAbsolutePath());
String parentFolder = file.getParentFile().getAbsolutePath();
IntStream.range(0, numPage).forEach(v -> {
try {
final BufferedImage tiff = reader.read(v);
ImageIO.write(tiff, "png", new File(parentFolder + "/png/" + name + v + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
If your target is Android, you could try this great Java library on Github that provides many utilities for handling, opening, and writing .tiff files.
A simple example from that Git showng how to convert TIFF to JPEG:
TiffConverter.ConverterOptions options = new TiffConverter.ConverterOptions();
//Set to true if you want use java exception mechanism
options.throwExceptions = false;
//Available 128Mb for work
options.availableMemory = 128 * 1024 * 1024;
//Number of tiff directory to convert;
options.readTiffDirectory = 1;
//Convert to JPEG
TiffConverter.convertTiffJpg("in.tif", "out.jpg", options, progressListener);
First, take a look to What is the best java image processing library/approach?. For your code you can use
javax.imageio.ImageIO.write(im, type, represFile);
like you can see in write an image to file example.

Java get image extension/type using BufferedImage from URL

I am familiar with working with images. I retrieve/read an image from a URL, where the URL does not have a file extension. Then I wish to write/save the image to the local storage, but I have to specify the image file extension (i.e. JPG, PNG, etc.), which I cannot retrieve its extension through the BufferedImage.
Could one please point out how it can be done?
Any other method will do.
Use ImageReader.getFormatName()
You can get the image readers for a file using ImageIO.getImageReaders(Object input).
I haven't tested it myself, but you can try this:
ImageInputStream iis = ImageIO.createImageInputStream(file);
Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
while (imageReaders.hasNext()) {
ImageReader reader = (ImageReader) imageReaders.next();
System.out.printf("formatName: %s%n", reader.getFormatName());
}
The suggestion to use ImageIO.createImageInputStream(obj) will not work if the object is a URL.
One alternative is to use the URLConnection.guessContentTypeFromStream(InputStream stream) method. This method guesses the content type by examining the first 12 bytes of a stream.
One complication with using this method is that it requires the given stream parameter to be mark supported, and the stream returned by java url.openStream() is not mark supported.
Additionally, if you want to be determine the content type and download the image to a BufferedImage, then it would be preferable if the solution only downloaded the content once (as opposed to making two passes, once to determine the content type and a second time to download the image).
One solution is to use the PushbackInputStream. The PushbackInputStream can be used to download the first initial bytes to determine content type. The bytes can then be pushed back on the stream so that the ImageIO.read(stream) can read the stream in its entirety.
Possible solution:
// URLConnection.guessContentTypeFromStream only needs the first 12 bytes, but
// just to be safe from future java api enhancements, we'll use a larger number
int pushbackLimit = 100;
InputStream urlStream = url.openStream();
PushbackInputStream pushUrlStream = new PushbackInputStream(urlStream, pushbackLimit);
byte [] firstBytes = new byte[pushbackLimit];
// download the first initial bytes into a byte array, which we will later pass to
// URLConnection.guessContentTypeFromStream
pushUrlStream.read(firstBytes);
// push the bytes back onto the PushbackInputStream so that the stream can be read
// by ImageIO reader in its entirety
pushUrlStream.unread(firstBytes);
String imageType = null;
// Pass the initial bytes to URLConnection.guessContentTypeFromStream in the form of a
// ByteArrayInputStream, which is mark supported.
ByteArrayInputStream bais = new ByteArrayInputStream(firstBytes);
String mimeType = URLConnection.guessContentTypeFromStream(bais);
if (mimeType.startsWith("image/"))
imageType = mimeType.substring("image/".length());
// else handle failure here
// read in image
BufferedImage inputImage = ImageIO.read(pushUrlStream);
If you get the image from a URL, that means you can access the image through an InputStream. From that you can use ImageIO to get the image type (format) and with the following code, create a BufferedImage at the same time.
public static BufferedImageWrapper getImageAndTypeFromInputStream(InputStream is) {
String format = null;
BufferedImage bufferedimage = null;
try (ImageInputStream iis = ImageIO.createImageInputStream(is);) {
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (readers.hasNext()) {
ImageReader reader = readers.next();
format = reader.getFormatName();
reader.setInput(iis);
bufferedimage = reader.read(0);
}
} catch (IOException e) {
logger.error("ERROR DETERMINING IMAGE TYPE!!!", e);
}
return new BufferedImageWrapper(format, bufferedimage);
}
public static class BufferedImageWrapper {
private final String imageType;
private final BufferedImage bufferedimage;
/**
* Constructor
*
* #param imageType
* #param bufferedimage
*/
public BufferedImageWrapper(String imageType, BufferedImage bufferedimage) {
this.imageType = imageType;
this.bufferedimage = bufferedimage;
}
public String getImageType() {
return imageType;
}
public BufferedImage getBufferedimage() {
return bufferedimage;
}
}
This works by feeding in a URL object (that is an image), and returning a file extension
It requires an initial download though, to the java tmp directory, and it is then deleted after the ImageReader attempts to get the gather the image type
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.ImageReader;
import java.util.Iterator;
public String getImageFileExtFromUrl(URL urlObject) throws URISyntaxException, IOException{
System.out.println("IN DOWNLOAD FILE FROM URL METHOD");
String tmpFolder = System.getProperty("java.io.tmpdir");
String tmpFileStr = tmpFolder + "/" + new Date().getTime();
Files.copy(urlObject.openStream(), Paths.get(tmpFileStr), StandardCopyOption.REPLACE_EXISTING);
File download = new File(tmpFileStr);
System.out.println("FILE DOWNLOAD EXISTS: " + download.exists() );
try{
ImageInputStream iis = ImageIO.createImageInputStream(download);
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
ImageReader reader = iter.next();
String formatName = reader.getFormatName();
System.out.println("FOUND IMAGE FORMAT :" + formatName);
iis.close();
return formatName;
}catch(Exception e){
e.printStackTrace();
}finally{
Files.delete(Paths.get(tmpFileStr));
}
return null;
}

Categories