How to Get Total Page Count From Tiff - java

I have started to create a new method in our project to return total pages. We are using TIFFTweaker which can be referenced from the following URL - https://github.com/dragon66/icafe/blob/master/src/com/icafe4j/image/tiff/TIFFTweaker.java
In this class I found a method TIFFTweaker.getPageCount() which looks like it wants a RandomAccessInputStream object for their getPageCount().
I've been playing around with trying to get from my file object over to what they're looking for.
What would be the best way to approach this and return the total pages from the tiff?
I have looked over some java docs, stackOverflow and some random blogs but can't seem to figure out how to get from a file object to a randomaccessinputstream.
#Override
public Integer totalPages(File file) {
Integer numberOfPages = 0;
try{
//TIFFTweaker.getPageCount(); - How to pass the file and get the count? Problem is type is a random access input stream and I have a file type
FileInputStream fileInputStream = new FileInputStream(file);
String absolutePath = file.getAbsolutePath();
// return TIFFTweaker.getPageCount();
}catch(IOException e){
log.error("Error with Tiff File" + e);
}
return null;
}
I am expecting a numeric value returned which represents the total number of pages in the TIFF file I'm passing.

Here is what I got to work. #roeygol, thanks for your answer. I had tried to Maven import the dependency but something was broken in that version. Here is what I came up with.
#Override
public Integer totalPages(File file) {
try(
InputStream fis = new FileInputStream(file);
RandomAccessInputStream randomAccessInputStream = new
FileCacheRandomAccessInputStream(fis)
){
return TIFFTweaker.getPageCount(randomAccessInputStream);
}catch(IOException e){
log.error("Error with Tiff File" + e);
}
return null;
}

Try to use this code:
import java.io.File;
import java.io.IOException;
import java.awt.Frame;
import java.awt.image.RenderedImage;
import javax.media.jai.widget.ScrollingImagePanel;
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 MultiPageRead extends Frame {
ScrollingImagePanel panel;
public MultiPageRead(String filename) throws IOException {
setTitle("Multi page TIFF Reader");
File file = new File(filename);
SeekableStream s = new FileSeekableStream(file);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
System.out.println("Number of images in this TIFF: " +
dec.getNumPages()); //<< use this function to get the number of pages of your TIFF
// Which of the multiple images in the TIFF file do we want to load
// 0 refers to the first, 1 to the second and so on.
int imageToLoad = 0;
RenderedImage op =
new NullOpImage(dec.decodeAsRenderedImage(imageToLoad),
null,
OpImage.OP_IO_BOUND,
null);
// Display the original in a 800x800 scrolling window
panel = new ScrollingImagePanel(op, 800, 800);
add(panel);
}
public static void main(String [] args) {
String filename = args[0];
try {
MultiPageRead window = new MultiPageRead(filename);
window.pack();
window.show();
} catch (java.io.IOException ioe) {
System.out.println(ioe);
}
}
}
Prerequisites for this code is to use jai-codec:
https://mvnrepository.com/artifact/com.sun.media/jai-codec/1.1.3
The main function to be used for is getNumPages()

Related

How can I compile a Java class stored in a string, or using it's path with a given input?

I'm trying to make my own pretty print for java files, similar to JDoodle. How can I compile a java class, given either it's location as a string, or its content as a string, as well as do it given a text file for std inputs, all the while recording the output as a seperate string. Sorry if this seems troublesome. Any help is appreciated!
EDIT: I do know about the java.tools.ToolProvider and Tool, but even if it is the solution, I don't know what to do with it, as the documentation is too confusing for me, or too sparse.
OK, I got an answer. I used Eclipse's compiler(cause I dont have JDK in my school laptop) to compile and used processbuilder to run the produced .class file, redirected the output using redirectOutput to a file which I read to get the output. Thanks- Here is the code.
/*PRETTYPRINT*/
/*
* Code to HTML
* Uses highlightjs in order to create a html form for your code, you can also give inputs and outputs
* */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class PrettyPrint {
public static void main(String[] args) throws FileNotFoundException{
String javaFile = readFile(args[0]);
String commandLine = readFile(args[1]);
String output = readFile(args[2]);
String html = "<!DOCTYPE html>\n"
+"<html>\n"
+"<head>"
+"<link rel=\"stylesheet\" href=\"highlightjs/styles/a11y-dark.css\" media= \"all\">\r\n"
+"<script src=\"highlightjs/highlight.pack.js\"></script>\r\n"
+"<script>hljs.initHighlightingOnLoad();</script>"
+"<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js\" integrity=\"sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/\" crossorigin=\"anonymous\"></script>\r\n"
+"<script src=\"https://cdn.jsdelivr.net/npm/html2canvas#1.0.0-rc.5/dist/html2canvas.min.js\"></script>"
+"<meta charset=\"utf-8\">"
+"<style>code{overflow-x: visible;}body{background-color:#888888;color:#444444;}h1{text-align:center;color:#444444;}</style>"
+"</head>"
+"<body style=\"font-family: 'Consolas';\">\n"
+"<h1 style=\"text-align: center\">Java Code</h1>"
+"<pre><code class=\"java\" style=\"overflow-x:visible\">"
+toHTML(javaFile)
+"</code></pre>"
+"<br>\n"
+"<h1>Inputs</h1>"
+"<pre><code class = \"nohighlight hljs\" style=\"overflow-x:visible\">"
+toHTML(commandLine)
+"</code></pre>"
+"<br>\n"
+"<h1>Output</h1>"
+"<pre><code class = \"nohighlight hljs\" style=\"overflow-x:visible\">"
+toHTML(output)
+"</code></pre>"
+"</body>\n"
+"<script>"
+"console.log(document.body.innerHTML);"
//+String.format("function print(){const filename='%s';html2canvas(document.body).then(canvas=>{let pdf = new jsPDF('p','mm', 'a4');pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 1000, 1000);pdf.save(filename);});}print();",args[3].substring(args[3].lastIndexOf('/')+1, args[3].length()-4)+"pdf")
+ "</script>"
+"</html>\n";
//System.out.println(html);
try {
File file = new File("output.html");
PrintWriter fileWriter = new PrintWriter(file);
fileWriter.print(html);
fileWriter.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public static String toHTML(String str) {
String html = str;
html = html.replace("&","&");
html = html.replace("\"", """);
html = html.replace("\'", "&apos;");
html = html.replace("<", "<");
html = html.replace(">", ">");
//html = html.replace("\n", "<br>");
html = html.replace("\t", "  ");
html+= "<br>";
return html;
}
public static String readFile(String filePath)
{
String content = "";
try
{
content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
}
catch (IOException e)
{
e.printStackTrace();
}
return content;
}
}
/**PROCESSBUILDEREXAMPLE**/
import java.io.*;
import org.eclipse.jdt.core.compiler.CompilationProgress;
import org.eclipse.jdt.core.compiler.batch.BatchCompiler;
public class ProcessBuilderExample {
private static String JAVA_FILE_LOCATION;
public static void main(String args[]) throws IOException{
JAVA_FILE_LOCATION = args[0];
CompilationProgress progress = null;
BatchCompiler.compile(String.format("-classpath rt.jar %s",args[0]), new PrintWriter(System.out), new PrintWriter(System.err), progress);
Process process = new ProcessBuilder("java", "-cp",
JAVA_FILE_LOCATION.substring(0,JAVA_FILE_LOCATION.lastIndexOf("\\")),
JAVA_FILE_LOCATION.substring(JAVA_FILE_LOCATION.lastIndexOf("\\")+1,JAVA_FILE_LOCATION.length()-5))
.redirectInput(new File(args[1]))
.redirectOutput(new File(args[2])).start();
try {
process.waitFor();
PrettyPrint.main(args);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Keep these 2 in the same folder and run processbuilderexample with 3 arguments. The code's loc, the input file's loc, and the output file to write to.

using Java arraylist for storing data from scan from file

I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!

Tess4j jar file issue

import java.awt.image.RenderedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import net.sourceforge.tess4j.Tesseract;
public class Tess4JSample {
public static void main(String[] args) throws Exception{
URL imageURL = new URL("http://s4.postimg.org/e75hcme9p/IMG_20130507_190237.jpg");
RenderedImage img = ImageIO.read(imageURL);
File outputfile = new File("saved.png");
ImageIO.write(img, "png", outputfile);
try {
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
String result = instance.doOCR(outputfile);
System.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
for this program I have put the jar files tess4j-1.5.0 and jai_imageio-1.1. But still it shows error
The import net.sourceforge cannot be resolved
Can anyone tell me what is the necessary action needs to be taken care for error resolution? I taken this program from stack overflow itself. Thanks! in advance.

Reading QRCode with Zxing in Java

Some questions about using Zxing...
I write the following code to read barcode from an image:
public class BarCodeDecode
{
/**
* #param args
*/
public static void main(String[] args)
{
try
{
String tmpImgFile = "D:\\FormCode128.TIF";
Map<DecodeHintType,Object> tmpHintsMap = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
tmpHintsMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
tmpHintsMap.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
tmpHintsMap.put(DecodeHintType.PURE_BARCODE, Boolean.FALSE);
File tmpFile = new File(tmpImgFile);
String tmpRetString = BarCodeUtil.decode(tmpFile, tmpHintsMap);
//String tmpRetString = BarCodeUtil.decode(tmpFile, null);
System.out.println(tmpRetString);
}
catch (Exception tmpExpt)
{
System.out.println("main: " + "Excpt err! (" + tmpExpt.getMessage() + ")");
}
System.out.println("main: " + "Program end.");
}
}
public class BarCodeUtil
{
private static BarcodeFormat DEFAULT_BARCODE_FORMAT = BarcodeFormat.CODE_128;
/**
* Decode method used to read image or barcode itself, and recognize the barcode,
* get the encoded contents and returns it.
* #param whatFile image that need to be read.
* #param config configuration used when reading the barcode.
* #return decoded results from barcode.
*/
public static String decode(File whatFile, Map<DecodeHintType, Object> whatHints) throws Exception
{
// check the required parameters
if (whatFile == null || whatFile.getName().trim().isEmpty())
throw new IllegalArgumentException("File not found, or invalid file name.");
BufferedImage tmpBfrImage;
try
{
tmpBfrImage = ImageIO.read(whatFile);
}
catch (IOException tmpIoe)
{
throw new Exception(tmpIoe.getMessage());
}
if (tmpBfrImage == null)
throw new IllegalArgumentException("Could not decode image.");
LuminanceSource tmpSource = new BufferedImageLuminanceSource(tmpBfrImage);
BinaryBitmap tmpBitmap = new BinaryBitmap(new HybridBinarizer(tmpSource));
MultiFormatReader tmpBarcodeReader = new MultiFormatReader();
Result tmpResult;
String tmpFinalResult;
try
{
if (whatHints != null && ! whatHints.isEmpty())
tmpResult = tmpBarcodeReader.decode(tmpBitmap, whatHints);
else
tmpResult = tmpBarcodeReader.decode(tmpBitmap);
// setting results.
tmpFinalResult = String.valueOf(tmpResult.getText());
}
catch (Exception tmpExcpt)
{
throw new Exception("BarCodeUtil.decode Excpt err - " + tmpExcpt.toString() + " - " + tmpExcpt.getMessage());
}
return tmpFinalResult;
}
}
I try to read the following two images that contains code128 and QRCode.
It can work for the code128 but not for the QRCode.
Any one knows why...
Please go through this link for complete Tutorial. The author of this code is Joe. I have not developed this code, so I am just doing Copy paste to make sure this is available in case link is broken.
The author is using ZXing(Zebra Crossing Library) you can download it from here, for this tutorial.
QR Code Write and Read Program in Java:
package com.javapapers.java;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QRCode {
public static void main(String[] args) throws WriterException, IOException,
NotFoundException {
String qrCodeData = "Hello World!";
String filePath = "QRCode.png";
String charset = "UTF-8"; // or "ISO-8859-1"
Map<EncodeHintType, ErrorCorrectionLevel> hintMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
createQRCode(qrCodeData, filePath, charset, hintMap, 200, 200);
System.out.println("QR Code image created successfully!");
System.out.println("Data read from QR Code: "
+ readQRCode(filePath, charset, hintMap));
}
public static void createQRCode(String qrCodeData, String filePath,
String charset, Map hintMap, int qrCodeheight, int qrCodewidth)
throws WriterException, IOException {
BitMatrix matrix = new MultiFormatWriter().encode(
new String(qrCodeData.getBytes(charset), charset),
BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap);
MatrixToImageWriter.writeToFile(matrix, filePath.substring(filePath
.lastIndexOf('.') + 1), new File(filePath));
}
public static String readQRCode(String filePath, String charset, Map hintMap)
throws FileNotFoundException, IOException, NotFoundException {
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
new BufferedImageLuminanceSource(
ImageIO.read(new FileInputStream(filePath)))));
Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap,
hintMap);
return qrCodeResult.getText();
}
}
Maven dependency for the ZXing QR Code library:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
</dependency>
Curiously your code works for me, but I had to remove the follow hint.
tmpHintsMap.put(DecodeHintType.PURE_BARCODE, Boolean.FALSE);
When my image is not pure barcode, this hint broke my result.
Thank you!
This Code worked for me.
public static List<string> ScanForBarcodes(string path)
{
return ScanForBarcodes(new Bitmap(path));
}
public static List<string> ScanForBarcodes(Bitmap bitmap)
{
// initialize a new Barcode reader.
BarcodeReader reader = new BarcodeReader
{
TryHarder = true, // TryHarder is slower but recognizes more Barcodes
PossibleFormats = new List<BarcodeFormat> // in the ZXing There is an Enum where all supported barcodeFormats were contained
{
BarcodeFormat.CODE_128,
BarcodeFormat.QR_CODE,
//BarcodeFormat. ... ;
}
};
return reader.DecodeMultiple(bitmap).Select(result => result.Text).ToList(); // return only the barcode string.
// If you want the full Result use: return reader.DecodeMultiple(bitmap);
}
Did you use this (ZXing.Net) Lib?

JAR launches fine when run through Terminal, but not when double-clicked

So I'm trying to load a file using a jar. The file is outside of the jar, but in the same folder. When I run the jar form the terminal using java -jar Test.jar it works just fine, but if I run it by double clicking the jar it does not correctly load from the file. I can load external Images just fine with either method, but not a file I have created. This is running on Mac OSX. This problem also seems to exist on Ubuntu. On Windows, however, the File is loaded even more incorrectly.
The Path loaded from seems to be the same for both cases. When running from terminal, the output for numbers is correct. However, when running by double clicking, any number over 127 is loaded improperly. I have researched for hours for a solution, with no avail.
EDIT: This is my manifest
Main-Class: Test
I have created this simple application to demonstrate my problem.
This is what writes the file that will be read.
import java.io.*;
public class TestWriter{
public static void main(String[] args){
try{
// Create the file and FileWriter.
FileWriter out = new FileWriter(new File("test.map"));
// Write some test numbers.
for (int i = 0; i < 481; i += 30)
out.write(i);
// Flush the output (for good measure?)
out.flush();
// Close the output.
out.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
This is what loads the file.
import javax.swing.JComponent;
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
public class Run extends JComponent{
// Image to be drawn on screen
BufferedImage IMAGE;
// Output to be drawn on screen
String string = "";
// Loading a MAP file - includes loading a bmp image and a .map (txt file).
public Run(){
// MAP name
String map = "test";
System.out.println("Loading map: "+map);
// Get path
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = "";
// Decode path
try{
decodedPath = URLDecoder.decode(path, "UTF-8");
decodedPath = decodedPath.substring(0, decodedPath.lastIndexOf("/") + 1);
} catch (Exception e){
System.out.println("Could not decode path.");
e.printStackTrace();
System.exit(1);
}
// Add decoded path to output string
string += decodedPath;
try{
IMAGE = ImageIO.read(new File(decodedPath+"/"+map+".bmp"));
System.out.println("MAP image loaded.");
} catch (IOException e){
System.out.println("Could not load MAP image.");
e.printStackTrace();
System.exit(1);
}
try{
System.out.println("Loading MAP data.");
// Create a new reader
FileReader in = new FileReader(new File(decodedPath+"/"+map+".map"));
// While there is something left to be read
while (in.ready()){
// add the next input to the output string
string += ", "+in.read();
}
// Close the input (for good measure)
in.close();
System.out.println("Loaded MAP data.");
} catch (Exception e){
System.err.println("Could not load MAP data.");
e.printStackTrace();
System.exit(1);
}
// Repaint the screen to show our newly loaded image and string
repaint();
}
public void paint(Graphics g){
g.drawImage(IMAGE,0,0,null);
g.drawString(string,16,64);
}
}
This is the main method that creates the JFrame and adds the component Run()
import javax.swing.JFrame;
import javax.swing.JComponent;
public class Test{
public static void main(String[] args){
System.out.println("\nInitializing...");
JFrame frame = new JFrame("Test");
int frameWidth = 640;
int frameHeight = 200;
frame.setSize(frameWidth,frameHeight);
frame.setResizable(false);
frame.setLocation(240,60);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Run());
frame.setVisible(true);
System.out.println("Running...");
}
}

Categories

Resources