Error converting PNG to TIFF-Java - java

HI I am working on the following snippet which is supposed to convert my png file to tiff.
String fileName = "4848970_1";
// String fileName = "color";
String inFileType = ".PNG";
String outFileType = ".TIFF";
File fInputFile = new File("C:\\Users\\abc\\Downloads\\image2.png");
InputStream fis = new BufferedInputStream(new FileInputStream(fInputFile));
ImageReaderSpi spi = new PNMImageReaderSpi();
ImageReader reader = spi.createReaderInstance();
ImageInputStream iis = ImageIO.createImageInputStream(fis);
reader.setInput(iis, true);
BufferedImage bi = reader.read(0);
int[] xi = bi.getSampleModel().getSampleSize();
for (int i : xi) {
System.out.println("bitsize " + i);
}
ImageWriterSpi tiffspi = new TIFFImageWriterSpi();
TIFFImageWriter writer = (TIFFImageWriter) tiffspi.createWriterInstance();
// TIFFImageWriteParam param = (TIFFImageWriteParam) writer.getDefaultWriteParam();
TIFFImageWriteParam param = new TIFFImageWriteParam(Locale.US);
String[] strings = param.getCompressionTypes();
for (String string : strings) {
System.out.println(string);
}
//param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
//param.setCompressionType("LZW");
File fOutputFile = new File("C:\\Users\\abc\\Downloads\\" + fileName + outFileType);
OutputStream fos = new BufferedOutputStream(new FileOutputStream(fOutputFile));
ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
writer.setOutput(ios);
writer.write(null, new IIOImage(bi, null, null), param);
ios.flush();
writer.dispose();
ios.close();
But this gives me following error
Exception in thread "main" java.lang.RuntimeException: What in the stream isn't a PNM image.
at com.sun.media.imageioimpl.plugins.pnm.PNMImageReader.readHeader(PNMImageReader.java:187)
at com.sun.media.imageioimpl.plugins.pnm.PNMImageReader.read(PNMImageReader.java:301)
at javax.imageio.ImageReader.read(Unknown Source)
at com.imageconv.TiffImage.main(TiffImage.java:40)
Is it that its unable to read the PNG file or it recognises it as a non png file.Am I wrong anywhere?

You are trying to read a PNG image as if it was a PNM image. These two file formats have nothing in common; hence the error.

Related

Corrupted PDF file after generating from ByteArrayOutputStream in Java

I am trying to read .rpt file and generate pdf using ReportClientDocument,ByteArrayInputStream and ByteArrayOutputStream. After generating the pdf file I am unable to open it. It is showing "It may be damaged or use a file format that Preview doesn’t recognise." My Source code is provided below
public static void generatePDFReport()
{
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
try {
ReportClientDocument rcd = new ReportClientDocument();
String rptPath="/Users/florapc/Desktop/Report/AcStatement.rpt";
String outputPath=String.format("/Users/florapc/Desktop/Report/%s.pdf",dtf.format(now));
File inputFile = new File(rptPath);
File outputFile = new File(outputPath);
rcd.open(rptPath, 0);
System.out.println(rptPath);
List<IParameterField> fld = rcd.getDataDefController().getDataDefinition().getParameterFields();
List<String> reportContent = new ArrayList<String>();
System.out.println(fld.size());
for (int i = 0; i < fld.size(); i++) {
System.out.println(fld.get(i).getDescription());
reportContent.add(fld.get(i).getDescription().replaceAll("[^a-zA-Z0-9]", " "));
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(reportContent);
byte[] bytes = bos.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
byte[] byteArray = new byte[byteArrayInputStream.available()];
int x = byteArrayInputStream.read(byteArray, 0, byteArrayInputStream.available());
System.out.println(x);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();;
byteArrayOutputStream.write(byteArray, 0, x);
byteArrayOutputStream.writeTo(fileOutputStream);
System.out.println(fileOutputStream);
System.out.println("File exported succesfully");
byteArrayInputStream.close();
byteArrayOutputStream.close();
fileOutputStream.close();
rcd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I can read .rpt file and print it in console. Please help me finding the best way to generate pdf properly.
I'm not familiar with ReportClientDocument. As far as I understand it's not a PDF document itself but a report that can be saved as PDF. ObjectOutputStream won't achieve this as it's Java specific format and has nothing to do with PDF.
It looks as if a PrintOutputController is needed for PDF export. Thus your code would look more like so:
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
InputStream is = rcd.getPrintOutputController().export(ReportExportFormat.PDF);
copy(is, fileOutputStream);
fileOutputStream.close();
...
void copy(InputStream source, OutputStream target) throws IOException {
byte[] buf = new byte[8192];
int length;
while ((length = source.read(buf)) > 0) {
target.write(buf, 0, length);
}
}
Note that no byte array streams are needed. They are a detour, slowing down your program and drive up memory consumption.

Java JPA retrieve blob from oracle database as its original file type

I am using java spring and jpa I have a query to retrieve the blob from an oracle db. I get the blob and if it is a text file it is downloading onto my local machine just fine - but if it is an image I have to go through a BufferedImage, and I am still working on PDF. So far I'm just seeing the extension of the file by getting it's original filename which is also stored in the DB, then filtering the string for the extension. When I get a PDF it says the file is corrupted or open in another window, which it is not.
So far, this is my code that tries to turn blob from DB into a file:
Blob blob = Service.retrieveBlob(ID);
if (blob == null){
return false;
}
String fileName = Service.getFileName(ID);
String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
System.out.println(extension);
if (extension.equals("jpg") || (extension.equals("png"))){
File file = new File("./DBPicture.png");
try(FileOutputStream outputStream = new FileOutputStream(file)) {
BufferedImage bufferedImage = ImageIO.read(blob.getBinaryStream());
ImageIO.write(bufferedImage, "png", outputStream);
System.out.println("Image file location: "+file.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
}
else {
InputStream ins = blob.getBinaryStream();
byte[] buffer = new byte[ins.available()];
ins.read(buffer);
File targetFile = new File("./" + fileName);
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
}
available is simply that. it is not necessarily the length of the stream.
Try something like
InputStream ins = blob.getBinaryStream();
File targetFile = new File("./" + fileName);
OutputStream outStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[8000];
int count = 0;
while ((count = ins.read(buffer)) != -1) {
outStream.write(buffer);
}
// then close your output
outStream.close ();

Unable to resize image on word document

We are getting image as a byte array and encode it into base64 string then writing this string into word doc but unable to change it's size.
PFB code:
worddocfile // stringbuilder
String encodedImage = new String(Base64.encodeBase64(fileType.getFileContent()), "UTF-8");
encodedImage = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
worddocfile.append("<img style='display:block; width:600px;height:600px;' id='base64image'")
.append(" src='data:image/jpeg;base64,")
.append(encodedImage)
.append("' /> ");
Can anyone suggest the solution because it's working on html page but not on word document.
We have already used background image tag but it's not working.
<p style="background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='); border: 1px solid black;background-repeat: no-repeat;background-size: contain;width:600px;height:597px;\>
Convert byte array into an image and place this image inside the WEB-INF folder.
Now re scale the converted image with the updated size and store it inside WEB-INF folder.
Now convert the re scaled image into byte array and write the bytes on the word doc.
PFB the code:
ByteArrayInputStream bis1 = new ByteArrayInputStream(fileType.getFileContent() );
Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
//ImageIO is a class containing static methods for locating ImageReaders
//and ImageWriters, and performing simple encoding and decoding.
ImageReader reader = (ImageReader) readers.next();
Object source1 = bis1;
ImageInputStream iis = ImageIO.createImageInputStream(source1);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
try{
Image image1 = reader.read(0, param);
//got an image file image1 -- image1.getWidth(null)
BufferedImage bufferedImage = new BufferedImage(650,950, BufferedImage.TYPE_INT_RGB);
//bufferedImage is the RenderedImage to be written
Graphics2D g2 = bufferedImage.createGraphics();
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, 650,950);
g2.drawImage(image1, 0,0,650,950, null);//
g2.dispose();
//mgpath can be WEB-INF folder
File imageFile = new File(imgpath+"UpdatedImg.jpg");
ImageIO.write(bufferedImage, "jpg", imageFile);
FileInputStream fisn = new FileInputStream(imageFile);
//create FileInputStream which obtains input bytes from a file in a file system
//FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
ByteArrayOutputStream bosn = new ByteArrayOutputStream();
byte[] bufn = new byte[1024];
try {
for (int readNum1; (readNum1 = fisn.read(bufn)) != -1;) {
//Writes to this byte array output stream
bosn.write(bufn, 0, readNum1);
System.out.println("read " + readNum1 + " bytes,");
}
} catch (IOException ex) {
}
byte[] outArray1 = bosn.toByteArray();
String encodedImage = new String(Base64.encodeBase64(outArray1), "UTF-8");
logger.debug("encodedImage" + encodedImage);
/// workbookDetails.append("<img src='data:image/png;base64," + encodedImage + "'/>");
workbookDetails.append("<img style='display:block; width:595px;height:609px;' id='base64image'")
.append(" src='data:image/jpeg;base64,")
.append(encodedImage)
.append("' /> ")
.append(" </p>")
.append(" </td>")
.append(" </tr>")
.append(" </tbody>")
.append("</table>");
.append("</table>");

How to convert PlanarConfiguration to separate

I convert my .tifs from uncompressed to PackBits compression... However I need to also change the PlanarConfiguration from Chunky to Separate, I do not know how to do this. It's not looking like there's anything on the web about it doing it in Java either. Only people saying to set PlanarConfiguration = 2; Here's my code for the .tif conversion so far...
public boolean packBitsConversionMove(File currentDirectory, File currentFile) throws IOException{
try{
InputStream fis = new BufferedInputStream(new FileInputStream(currentFile));
PNGImageReaderSpi spi = new PNGImageReaderSpi();
ImageReader reader = spi.createReaderInstance();
ImageInputStream iis = ImageIO.createImageInputStream(fis);
reader.setInput(iis, true);
BufferedImage bi = ImageIO.read(currentFile);
TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi();
ImageWriter writer = tiffspi.createWriterInstance();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("PackBits");
File fOutputFile = new File(currentDirectory.getPath() + "\\" + currentFile.getName());
ImageOutputStream ios = ImageIO.createImageOutputStream(fOutputFile);
writer.setOutput(ios);
writer.write(null, new IIOImage(bi, null, null), param);
} catch (IOException e){
return false;
}
return true;
}
My param variable doesn't have any setPlanarCompression function but I do not know a work around. Thanks for any advice!

Using ImageIO to write JPEG 2000 with layers (i.e. decomposition levels)

Ok, here is our issue:
We are trying to convert a series of black and white .tiff files into jpeg2000 .jpf files, using imageio. We are always getting viewable .jpf files, but they usually do not have the specified number of layers or decomposition levels for zooming.
Here is our code:
//Get the tiff reader
Iterator<ImageReader> readerIterator = ImageIO.getImageReadersByFormatName("tiff");
ImageReader tiffreader = readerIterator.next();
//make an ImageInputStream from our tiff file and have the tiff reader read it
ImageInputStream iis = ImageIO.createImageInputStream(itemFile);
tiffreader.setInput(iis);
//just pass empty params to the tiff reader
ImageReadParam tparam;
tparam = new TIFFImageReadParam();
IIOImage img = tiffreader.readAll(0, tparam);
//set up target file
File f = new File(itemTargetDirectory.getAbsolutePath() + "/" + destFileName);
//we have tried FILTER_97 as well as different ProgressionTypes and compression settings
J2KImageWriteParam param;
param = new J2KImageWriteParam();
param.setProgressionType("layer");
param.setFilter(J2KImageWriteParam.FILTER_53);
//Our problem is that this param is not always respected in the resulting .jpf
param.setNumDecompositionLevels(5);
//get the JPEG 2000 writer
Iterator<ImageWriter> writerIterator = ImageIO.getImageWritersByFormatName("JPEG 2000");
J2KImageWriter jp2kwriter = null;
jp2kwriter = (J2KImageWriter) writerIterator.next();
//write the jpf file
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
jp2kwriter.setOutput(ios);
jp2kwriter.write(null, img, param);
It has been an odd experience, as the same code has behaved differently on subsequent runs.
Any insights will be appreciated!
Do all the TIFF files have the same settings (color model)? J2KImageWriter.java shows the decomposition levels getting set (forced) to zero when indexed-color or multi-pixel packed source images are used as input.
Drew was on the right track, and here is the code that ended up sorting things out for us:
public void compressor(String inputFile, String outputFile) throws IOException {
J2KImageWriteParam iwp = new J2KImageWriteParam();
FileInputStream fis = new FileInputStream(new File(inputFile));
BufferedImage image = ImageIO.read(fis);
fis.close();
if (image == null)
{
System.out.println("If no registered ImageReader claims to be able to read the resulting stream");
}
Iterator writers = ImageIO.getImageWritersByFormatName("JPEG2000");
String name = null;
ImageWriter writer = null;
while (name != "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriter") {
writer = (ImageWriter) writers.next();
name = writer.getClass().getName();
System.out.println(name);
}
File f = new File(outputFile);
long s = System.currentTimeMillis();
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
writer.setOutput(ios);
J2KImageWriteParam param = (J2KImageWriteParam) writer.getDefaultWriteParam();
IIOImage ioimage = new IIOImage(image, null, null);
param.setSOP(true);
param.setWriteCodeStreamOnly(true);
param.setProgressionType("layer");
param.setLossless(false);
param.setCompressionMode(J2KImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("JPEG2000");
param.setCompressionQuality(0.1f);
param.setEncodingRate(1.01);
param.setFilter(J2KImageWriteParam.FILTER_97);
writer.write(null, ioimage, param);
System.out.println(System.currentTimeMillis() - s);
writer.dispose();
ios.flush();
ios.close();
image.flush();
}

Categories