use of javax.imageio.IIOImage in project tess4j by nguyenq.
the class ImageIOHelper method createTiffFiles.
/**
* Creates a list of TIFF image files from an image file. It basically
* converts images of other formats to TIFF format, or a multi-page TIFF
* image to multiple TIFF image files.
*
* @param imageFile input image file
* @param index an index of the page; -1 means all pages, as in a multi-page
* TIFF image
* @param preserve preserve compression mode
* @return a list of TIFF image files
* @throws IOException
*/
public static List<File> createTiffFiles(File imageFile, int index, boolean preserve) throws IOException {
List<File> tiffFiles = new ArrayList<File>();
String imageFileName = imageFile.getName();
String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
if (!readers.hasNext()) {
throw new RuntimeException(JAI_IMAGE_READER_MESSAGE);
}
ImageReader reader = readers.next();
ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
reader.setInput(iis);
// Read the stream metadata
// IIOMetadata streamMetadata = reader.getStreamMetadata();
// Set up the writeParam
TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
if (!preserve) {
// not preserve original sizes; decompress
tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);
}
// Get tif writer and set output to file
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
if (!writers.hasNext()) {
throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
}
ImageWriter writer = writers.next();
// Read the stream metadata
IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);
int imageTotal = reader.getNumImages(true);
for (int i = 0; i < imageTotal; i++) {
// all if index == -1; otherwise, only index-th
if (index == -1 || i == index) {
// BufferedImage bi = reader.read(i);
// IIOImage oimage = new IIOImage(bi, null, reader.getImageMetadata(i));
IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile);
writer.setOutput(ios);
writer.write(streamMetadata, oimage, tiffWriteParam);
ios.close();
tiffFiles.add(tiffFile);
}
}
writer.dispose();
reader.dispose();
return tiffFiles;
}
use of javax.imageio.IIOImage in project tess4j by nguyenq.
the class ImageIOHelper method mergeTiff.
/**
* Merges multiple images into one multi-page TIFF image.
*
* @param inputImages an array of <code>BufferedImage</code>
* @param outputTiff the output TIFF file
* @param compressionType valid values: LZW, CCITT T.6, PackBits
* @throws IOException
*/
public static void mergeTiff(BufferedImage[] inputImages, File outputTiff, String compressionType) throws IOException {
List<IIOImage> imageList = new ArrayList<IIOImage>();
for (BufferedImage inputImage : inputImages) {
imageList.add(new IIOImage(inputImage, null, null));
}
mergeTiff(imageList, outputTiff, compressionType);
}
use of javax.imageio.IIOImage in project tess4j by nguyenq.
the class TesseractTest method testDoOCR_List_Rectangle.
/**
* Test of doOCR method, of class Tesseract.
*
* @throws Exception while processing image.
*/
@Test
public void testDoOCR_List_Rectangle() throws Exception {
File imageFile = null;
String expResult = "The (quick) [brown] {fox} jumps!\nOver the $43,456.78 <lazy> #90 dog";
String result = "<empty>";
try {
logger.info("doOCR on a PDF document");
imageFile = new File(this.testResourcesDataPath, "eurotext.pdf");
List<IIOImage> imageList = ImageIOHelper.getIIOImageList(imageFile);
result = instance.doOCR(imageList, null);
logger.info(result);
assertEquals(expResult, result.substring(0, expResult.length()));
} catch (IOException e) {
logger.error("Exception-Message: '{}'. Imagefile: '{}'", e.getMessage(), imageFile.getAbsoluteFile(), e);
fail();
} catch (TesseractException e) {
logger.error("Exception-Message: '{}'. Imagefile: '{}'", e.getMessage(), imageFile.getAbsoluteFile(), e);
fail();
} catch (StringIndexOutOfBoundsException e) {
logger.error("Exception-Message: '{}'. Imagefile: '{}'", e.getMessage(), imageFile.getAbsoluteFile(), e);
fail();
}
}
use of javax.imageio.IIOImage in project bioformats by openmicroscopy.
the class JAIIIOServiceImpl method writeImage.
/* @see JAIIIOService#writeImage(OutputStream, BufferedImage, JPEG2000CodecOptions) */
@Override
public void writeImage(OutputStream out, BufferedImage img, JPEG2000CodecOptions options) throws IOException, ServiceException {
ImageOutputStream ios = ImageIO.createImageOutputStream(out);
IIORegistry registry = IIORegistry.getDefaultInstance();
Iterator<J2KImageWriterSpi> iter = ServiceLoader.load(J2KImageWriterSpi.class).iterator();
registry.registerServiceProviders(iter);
J2KImageWriterSpi spi = registry.getServiceProviderByClass(J2KImageWriterSpi.class);
J2KImageWriter writer = new J2KImageWriter(spi);
writer.setOutput(ios);
String filter = options.lossless ? J2KImageWriteParam.FILTER_53 : J2KImageWriteParam.FILTER_97;
IIOImage iioImage = new IIOImage(img, null, null);
J2KImageWriteParam param = (J2KImageWriteParam) writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("JPEG2000");
if (!options.lossless) {
param.setEncodingRate(options.quality);
}
param.setLossless(options.lossless);
param.setFilter(filter);
param.setCodeBlockSize(options.codeBlockSize);
param.setComponentTransformation(false);
if (options.tileWidth > 0 && options.tileHeight > 0) {
param.setTiling(options.tileWidth, options.tileHeight, options.tileGridXOffset, options.tileGridYOffset);
}
if (options.numDecompositionLevels != null) {
param.setNumDecompositionLevels(options.numDecompositionLevels.intValue());
}
writer.write(null, iioImage, param);
ios.close();
}
use of javax.imageio.IIOImage in project TrakEM2 by trakem2.
the class ImageSaver method saveAsJpeg.
/**
* Will not flush the given BufferedImage.
*/
public static final boolean saveAsJpeg(final BufferedImage bi, final String path, float quality, boolean as_grey) {
if (!checkPath(path))
return false;
if (quality < 0f)
quality = 0f;
if (quality > 1f)
quality = 1f;
synchronized (getPathLock(path)) {
ImageOutputStream ios = null;
ImageWriter writer = null;
BufferedImage grey = bi;
try {
writer = ImageIO.getImageWritersByFormatName("jpeg").next();
final ByteArrayOutputStream baos = new ByteArrayOutputStream(estimateJPEGFileSize(bi.getWidth(), bi.getHeight()));
ios = ImageIO.createImageOutputStream(baos);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
if (as_grey && bi.getType() != BufferedImage.TYPE_BYTE_GRAY) {
grey = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
// convert the original colored image to grayscale
// Very slow:
// ColorConvertOp op = new ColorConvertOp(bi.getColorModel().getColorSpace(), grey.getColorModel().getColorSpace(), null);
// op.filter(bi, grey);
// 9 times faster:
grey.createGraphics().drawImage(bi, 0, 0, null);
}
IIOImage iioImage = new IIOImage(grey, null, null);
writer.write(null, iioImage, param);
// Now write to disk
FileChannel ch = null;
try {
// Now write to disk in the fastest way possible
final RandomAccessFile ra = new RandomAccessFile(new File(path), "rw");
final ByteBuffer bb = ByteBuffer.wrap((byte[]) Bbuf.get(baos), 0, baos.size());
ch = ra.getChannel();
while (bb.hasRemaining()) {
ch.write(bb);
}
} finally {
if (null != ch)
ch.close();
ios.close();
}
} catch (Exception e) {
IJError.print(e);
return false;
} finally {
if (null != writer)
try {
writer.dispose();
} catch (Exception ee) {
}
// if (null != ios) try { ios.close(); } catch (Exception ee) {} // NOT NEEDED, it's a ByteArrayOutputStream
if (bi != grey)
try {
grey.flush();
/*release native resources*/
} catch (Exception ee) {
}
removePathLock(path);
}
}
return true;
}
Aggregations