Java Code Examples for javax.imageio.IIOImage

The following examples show how to use javax.imageio.IIOImage. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: tools-ocr   Source File: CommUtils.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public static byte[] imageToBytes(BufferedImage img) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    MemoryCacheImageOutputStream outputStream = new MemoryCacheImageOutputStream(byteArrayOutputStream);
    try {
        Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
        ImageWriter writer = (ImageWriter) iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(IMAGE_QUALITY);
        writer.setOutput(outputStream);
        IIOImage image = new IIOImage(img, null, null);
        writer.write(null, image, iwp);
        writer.dispose();
        byte[] result = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        outputStream.close();
        return result;
    } catch (IOException e) {
        StaticLog.error(e);
        return new byte[0];
    }
}
 
Example 2
Source Project: openjdk-jdk9   Source File: LUTCompareTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 3
Source Project: jdk1.8-source-analysis   Source File: GIFImageWriter.java    License: Apache License 2.0 6 votes vote down vote up
public void write(IIOMetadata sm,
                  IIOImage iioimage,
                  ImageWriteParam p) throws IOException {
    if (stream == null) {
        throw new IllegalStateException("output == null!");
    }
    if (iioimage == null) {
        throw new IllegalArgumentException("iioimage == null!");
    }
    if (iioimage.hasRaster()) {
        throw new UnsupportedOperationException("canWriteRasters() == false!");
    }

    resetLocal();

    GIFWritableStreamMetadata streamMetadata;
    if (sm == null) {
        streamMetadata =
            (GIFWritableStreamMetadata)getDefaultStreamMetadata(p);
    } else {
        streamMetadata =
            (GIFWritableStreamMetadata)convertStreamMetadata(sm, p);
    }

    write(true, true, streamMetadata, iioimage, p);
}
 
Example 4
public byte[] createPNGThumbnailFromByteArray(byte[] img) throws Exception {
	ByteArrayInputStream byteIn = new ByteArrayInputStream(img);
	ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
	try {
		BufferedImage buffImg = ImageIO.read(byteIn);
		BufferedImage thumbImg = createThumbnail(buffImg);
		try (ImageOutputStream ios = ImageIO.createImageOutputStream(byteOut)) {
			ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();
			writer.setOutput(ios);
			writer.write(null, new IIOImage(thumbImg, null, null), writer.getDefaultWriteParam());
			ios.flush();
			writer.dispose();
		}
	} catch (IOException e) {
		logger.error("Error reading image from byte array", e);
	}
	return byteOut.toByteArray();
}
 
Example 5
Source Project: jdk8u-dev-jdk   Source File: GIFImageWriter.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void writeToSequence(IIOImage image, ImageWriteParam param)
  throws IOException {
    if (stream == null) {
        throw new IllegalStateException("output == null!");
    }
    if (image == null) {
        throw new IllegalArgumentException("image == null!");
    }
    if (image.hasRaster()) {
        throw new UnsupportedOperationException("canWriteRasters() == false!");
    }
    if (!isWritingSequence) {
        throw new IllegalStateException("prepareWriteSequence() was not invoked!");
    }

    write(!wroteSequenceHeader, false, theStreamMetadata,
          image, param);

    if (!wroteSequenceHeader) {
        wroteSequenceHeader = true;
    }

    this.imageIndex++;
}
 
Example 6
Source Project: openjdk-8   Source File: LUTCompareTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 7
public void writeToSequence(IIOImage image, ImageWriteParam param)
  throws IOException {
    if (stream == null) {
        throw new IllegalStateException("output == null!");
    }
    if (image == null) {
        throw new IllegalArgumentException("image == null!");
    }
    if (image.hasRaster()) {
        throw new UnsupportedOperationException("canWriteRasters() == false!");
    }
    if (!isWritingSequence) {
        throw new IllegalStateException("prepareWriteSequence() was not invoked!");
    }

    write(!wroteSequenceHeader, false, theStreamMetadata,
          image, param);

    if (!wroteSequenceHeader) {
        wroteSequenceHeader = true;
    }

    this.imageIndex++;
}
 
Example 8
Source Project: lams   Source File: ResizePictureUtil.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
    * Reads the original image, creates a resized copy of it and returns its input stream. largestDimension is the
    * largest dimension of the resized image, the other dimension is scaled accordingly.
    *
    * @param image
    *            original image
    * @param largestDimension
    *            the largest dimension of the resized image, the other dimension is scaled accordingly
    * @return
    * @throws IOException
    * @throws UploadImageGalleryFileException
    */
   private static InputStream resize(BufferedImage image, int largestDimension) throws IOException {

//resize to 150 pixels max
BufferedImage outImage = Scalr.resize(image, Method.QUALITY, largestDimension);

//set jpeg compression quality explicitly
ImageWriter imageWriter = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam jpgWriteParam = imageWriter.getDefaultWriteParam();
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpgWriteParam.setCompressionQuality(.95f);

// buffer all data in a circular buffer of infinite sizes
CircularByteBuffer outputBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
ImageOutputStream ios = ImageIO.createImageOutputStream(outputBuffer.getOutputStream());
imageWriter.setOutput(ios);
IIOImage outputImage = new IIOImage(outImage, null, null);
imageWriter.write(null, outputImage, jpgWriteParam);
imageWriter.dispose();
outputBuffer.getOutputStream().close();

return outputBuffer.getInputStream();

   }
 
Example 9
public void writeToSequence(IIOImage image, ImageWriteParam param)
  throws IOException {
    if (stream == null) {
        throw new IllegalStateException("output == null!");
    }
    if (image == null) {
        throw new IllegalArgumentException("image == null!");
    }
    if (image.hasRaster()) {
        throw new UnsupportedOperationException("canWriteRasters() == false!");
    }
    if (!isWritingSequence) {
        throw new IllegalStateException("prepareWriteSequence() was not invoked!");
    }

    write(!wroteSequenceHeader, false, theStreamMetadata,
          image, param);

    if (!wroteSequenceHeader) {
        wroteSequenceHeader = true;
    }

    this.imageIndex++;
}
 
Example 10
Source Project: olat   Source File: ImageHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Can change this to choose a better compression level as the default
 * 
 * @param image
 * @param scaledImage
 * @return
 */
private static boolean writeTo(BufferedImage image, File scaledImage, Size scaledSize, String outputFormat) {
    try {
        if (!StringHelper.containsNonWhitespace(outputFormat)) {
            outputFormat = OUTPUT_FORMAT;
        }

        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(outputFormat);
        if (writers.hasNext()) {
            ImageWriter writer = writers.next();
            ImageWriteParam iwp = getOptimizedImageWriteParam(writer, scaledSize);
            IIOImage iiOImage = new IIOImage(image, null, null);
            ImageOutputStream iOut = new FileImageOutputStream(scaledImage);
            writer.setOutput(iOut);
            writer.write(null, iiOImage, iwp);
            writer.dispose();
            iOut.flush();
            iOut.close();
            return true;
        } else {
            return ImageIO.write(image, outputFormat, scaledImage);
        }
    } catch (IOException e) {
        return false;
    }
}
 
Example 11
Source Project: JuiceboxLegacy   Source File: HeatChart.java    License: MIT License 6 votes vote down vote up
private void saveGraphicJpeg(BufferedImage chart, File outputFile, float quality) throws IOException {
    // Setup correct compression for jpeg.
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = iter.next();
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(quality);

    // Output the image.
    FileImageOutputStream output = new FileImageOutputStream(outputFile);
    writer.setOutput(output);
    IIOImage image = new IIOImage(chart, null, null);
    writer.write(null, image, iwp);
    writer.dispose();

}
 
Example 12
Source Project: sc2gears   Source File: ImageConverter.java    License: Apache License 2.0 6 votes vote down vote up
private static void convertImages( final File file ) throws Exception {
	if ( file.isDirectory() ) {
		for ( final File childFile : file.listFiles() )
			convertImages( childFile );
	}
	else {
		final BufferedImage bi = ImageIO.read( file );
		
		// Default quality is not sufficient!
		// ImageIO.write( bi, "JPG", new File( file.getPath().replace( ".png", ".jpg" ) ) );
		
		final ImageWriter     iw  = ImageIO.getImageWritersByFormatName( "jpg" ).next();
		final ImageWriteParam iwp = iw.getDefaultWriteParam();
		
		iwp.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
		iwp.setCompressionQuality( 0.9f );
		
		iw.setOutput( new FileImageOutputStream( new File( file.getPath().replace( ".png", ".jpg" ) ) ) );
		iw.write( null, new IIOImage( bi , null, null ), iwp );
		iw.dispose();
	}
}
 
Example 13
Source Project: jdk8u-jdk   Source File: LUTCompareTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 14
Source Project: scrimage   Source File: GifWriter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public void write(AwtImage image, ImageMetadata metadata, OutputStream out) throws IOException {

        javax.imageio.ImageWriter writer = ImageIO.getImageWritersByFormatName("gif").next();
        ImageWriteParam params = writer.getDefaultWriteParam();

        if (progressive) {
            params.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
        } else {
            params.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
        }

        try (MemoryCacheImageOutputStream output = new MemoryCacheImageOutputStream(out)) {
            writer.setOutput(output);
            writer.write(null, new IIOImage(image.awt(), null, null), params);
            writer.dispose();
        }

//        IOUtils.closeQuietly(out);
    }
 
Example 15
Source Project: MyBox   Source File: ImageGifFile.java    License: Apache License 2.0 6 votes vote down vote up
public static void writeGifImageFile(BufferedImage image,
        ImageAttributes attributes, String outFile) {
    try {
        ImageWriter writer = getWriter();
        ImageWriteParam param = getPara(attributes, writer);
        IIOMetadata metaData = getWriterMeta(attributes, image, writer, param);

        try ( ImageOutputStream out = ImageIO.createImageOutputStream(new File(outFile))) {
            writer.setOutput(out);
            writer.write(metaData, new IIOImage(image, null, metaData), param);
            out.flush();
        }
        writer.dispose();

    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
Example 16
Source Project: openjdk-jdk9   Source File: GIFImageWriter.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void write(IIOMetadata sm,
                  IIOImage iioimage,
                  ImageWriteParam p) throws IOException {
    if (stream == null) {
        throw new IllegalStateException("output == null!");
    }
    if (iioimage == null) {
        throw new IllegalArgumentException("iioimage == null!");
    }
    if (iioimage.hasRaster()) {
        throw new UnsupportedOperationException("canWriteRasters() == false!");
    }

    resetLocal();

    GIFWritableStreamMetadata streamMetadata;
    if (sm == null) {
        streamMetadata =
            (GIFWritableStreamMetadata)getDefaultStreamMetadata(p);
    } else {
        streamMetadata =
            (GIFWritableStreamMetadata)convertStreamMetadata(sm, p);
    }

    write(true, true, streamMetadata, iioimage, p);
}
 
Example 17
Source Project: openjdk-jdk8u   Source File: LUTCompareTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

    ios.flush();
    ios.close();

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example 18
public void write(IIOMetadata sm,
                  IIOImage iioimage,
                  ImageWriteParam p) throws IOException {
    if (stream == null) {
        throw new IllegalStateException("output == null!");
    }
    if (iioimage == null) {
        throw new IllegalArgumentException("iioimage == null!");
    }
    if (iioimage.hasRaster()) {
        throw new UnsupportedOperationException("canWriteRasters() == false!");
    }

    resetLocal();

    GIFWritableStreamMetadata streamMetadata;
    if (sm == null) {
        streamMetadata =
            (GIFWritableStreamMetadata)getDefaultStreamMetadata(p);
    } else {
        streamMetadata =
            (GIFWritableStreamMetadata)convertStreamMetadata(sm, p);
    }

    write(true, true, streamMetadata, iioimage, p);
}
 
Example 19
@Override
public void writeImageFile(OutputStream outStream, String format, ByteBuffer imageData, int width, int height) throws IOException {
    BufferedImage awtImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
    Screenshots.convertScreenShot2(imageData.asIntBuffer(), awtImage);

    ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next();
    ImageWriteParam writeParam = writer.getDefaultWriteParam();

    if (format.equals("jpg")) {
        JPEGImageWriteParam jpegParam = (JPEGImageWriteParam) writeParam;
        jpegParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpegParam.setCompressionQuality(0.95f);
    }

    awtImage = verticalFlip(awtImage);
    
    ImageOutputStream imgOut = new MemoryCacheImageOutputStream(outStream);
    writer.setOutput(imgOut);
    IIOImage outputImage = new IIOImage(awtImage, null, null);
    try {
        writer.write(null, outputImage, writeParam);
    } finally {
        imgOut.close();
        writer.dispose();
    }
}
 
Example 20
Source Project: openjdk-jdk9   Source File: TIFFImageWriter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void writeInsert(int imageIndex,
                        IIOImage image,
                        ImageWriteParam param) throws IOException {
    int currentImageCached = currentImage;
    try {
        insert(imageIndex, image, param, true);
    } catch (Exception e) {
        throw e;
    } finally {
        currentImage = currentImageCached;
    }
}
 
Example 21
private void writeInternal(BufferedImage image, MediaType contentType, OutputStream body)
		throws IOException, HttpMessageNotWritableException {

	ImageOutputStream imageOutputStream = null;
	ImageWriter imageWriter = null;
	try {
		Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(contentType.toString());
		if (imageWriters.hasNext()) {
			imageWriter = imageWriters.next();
			ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
			process(iwp);
			imageOutputStream = createImageOutputStream(body);
			imageWriter.setOutput(imageOutputStream);
			imageWriter.write(null, new IIOImage(image, null, null), iwp);
		}
		else {
			throw new HttpMessageNotWritableException(
					"Could not find javax.imageio.ImageWriter for Content-Type [" + contentType + "]");
		}
	}
	finally {
		if (imageWriter != null) {
			imageWriter.dispose();
		}
		if (imageOutputStream != null) {
			try {
				imageOutputStream.close();
			}
			catch (IOException ex) {
				// ignore
			}
		}
	}
}
 
Example 22
public void writeToSequence(IIOImage image, ImageWriteParam param)
    throws IOException {
    setThreadLock();
    try {
        cbLock.check();

        if (sequencePrepared == false) {
            throw new IllegalStateException("sequencePrepared not called!");
        }
        // In the case of JPEG this does nothing different from write
        write(null, image, param);
    } finally {
        clearThreadLock();
    }
}
 
Example 23
Source Project: jdk1.8-source-analysis   Source File: JPEGImageWriter.java    License: Apache License 2.0 5 votes vote down vote up
public void writeToSequence(IIOImage image, ImageWriteParam param)
    throws IOException {
    setThreadLock();
    try {
        cbLock.check();

        if (sequencePrepared == false) {
            throw new IllegalStateException("sequencePrepared not called!");
        }
        // In the case of JPEG this does nothing different from write
        write(null, image, param);
    } finally {
        clearThreadLock();
    }
}
 
Example 24
Source Project: geopackage-java   Source File: ImageUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Compress and write the image to bytes in the provided format and quality
 * 
 * @param image
 *            buffered image
 * @param formatName
 *            image format name
 * @param quality
 *            quality between 0.0 and 1.0
 * @return compressed image bytes
 * @since 1.1.2
 */
public static byte[] compressAndWriteImageToBytes(BufferedImage image,
		String formatName, float quality) {

	byte[] bytes = null;

	Iterator<ImageWriter> writers = ImageIO
			.getImageWritersByFormatName(formatName);
	if (writers == null || !writers.hasNext()) {
		throw new GeoPackageException(
				"No Image Writer to compress format: " + formatName);
	}
	ImageWriter writer = writers.next();
	ImageWriteParam writeParam = writer.getDefaultWriteParam();
	writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
	writeParam.setCompressionQuality(quality);

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ImageOutputStream ios = null;
	try {
		ios = ImageIO.createImageOutputStream(baos);
		writer.setOutput(ios);
		writer.write(null, new IIOImage(image, null, null), writeParam);
		writer.dispose();

		bytes = baos.toByteArray();

	} catch (IOException e) {
		throw new GeoPackageException(
				"Failed to compress image to format: " + formatName
						+ ", with quality: " + quality, e);
	} finally {
		closeQuietly(ios);
		closeQuietly(baos);
	}

	return bytes;
}
 
Example 25
Source Project: PixelFlow   Source File: DwFrameCapture.java    License: MIT License 5 votes vote down vote up
public void save(){
      try {
        
        BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(filename));
        
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();

        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(jpeg_compression);
        
        writer.setOutput(ImageIO.createImageOutputStream(output));
        writer.write(null, new IIOImage(img, null, null), param);
        writer.dispose();
        output.flush();
        output.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      
//      try {
//        BufferedOutputStream imageOutputStream = new BufferedOutputStream(new FileOutputStream(filename));
//        ImageIO.write(img, "JPG", imageOutputStream);
//        imageOutputStream.close();
//      } catch (IOException e) {
//        e.printStackTrace();
//      }
    }
 
Example 26
Source Project: webp-imageio   Source File: WebPWriter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void write( IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param ) throws IOException {
  if ( param == null ) {
    param = getDefaultWriteParam();
  }

  WebPWriteParam writeParam = (WebPWriteParam) param;

  ImageOutputStream output = ( ImageOutputStream ) getOutput();
  RenderedImage ri = image.getRenderedImage();

  byte[] encodedData = WebP.encode(writeParam, ri);
  output.write( encodedData );
}
 
Example 27
Source Project: tess4j   Source File: Tesseract.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Performs OCR operation.
 *
 * @param imageList a list of <code>IIOImage</code> objects
 * @param filename input file name. Needed only for training and reading a
 * UNLV zone file.
 * @param rect the bounding rectangle defines the region of the image to be
 * recognized. A rectangle of zero dimension or <code>null</code> indicates
 * the whole image.
 * @return the recognized text
 * @throws TesseractException
 */
@Override
public String doOCR(List<IIOImage> imageList, String filename, Rectangle rect) throws TesseractException {
    init();
    setTessVariables();

    try {
        StringBuilder sb = new StringBuilder();
        int pageNum = 0;

        for (IIOImage oimage : imageList) {
            pageNum++;
            try {
                setImage(oimage.getRenderedImage(), rect);
                sb.append(getOCRText(filename, pageNum));
            } catch (IOException ioe) {
                // skip the problematic image
                logger.error(ioe.getMessage(), ioe);
            }
        }

        if (String.valueOf(TRUE).equals(prop.getProperty("tessedit_create_hocr"))) {
            sb.insert(0, htmlBeginTag).append(htmlEndTag);
        }

        return sb.toString();
    } finally {
        dispose();
    }
}
 
Example 28
public void writeToSequence(IIOImage image, ImageWriteParam param)
    throws IOException {
    setThreadLock();
    try {
        cbLock.check();

        if (sequencePrepared == false) {
            throw new IllegalStateException("sequencePrepared not called!");
        }
        // In the case of JPEG this does nothing different from write
        write(null, image, param);
    } finally {
        clearThreadLock();
    }
}
 
Example 29
Source Project: webp-imageio   Source File: WebPWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test method tests {@link WebPWriter} with image resize options.
 *
 * @throws IOException
 *            the test fails.
 */
@Test(dataProvider = "createImagesWithScaleOptions", enabled = true)
public void testImageWriterScale(final RenderedImage image, final float xScale,
      final float yScale, final String outputName) throws IOException {
   final String extension = outputName.substring(outputName.lastIndexOf(".") + 1);

   // Scale the image.
   final RenderedOp scaledImage = ScaleDescriptor.create(image, xScale, yScale, 0f, 0f,
         Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2), null);

   // get writer
   final ImageWriter imgWriter = ImageIO.getImageWritersByFormatName(extension).next();
   final ImageWriteParam imgWriteParams = new WebPWriteParam(null);
   final String testName = "ScaleOptions";
   final File file = createOutputFile(testName, outputName);
   final ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(file);
   try {
      imgWriter.setOutput(imageOutputStream);
      imgWriter.write(null, new IIOImage(scaledImage, null, null), imgWriteParams);
      final int length = (int) imageOutputStream.length();
      assertTrue(length > 0);
   } finally {
      try {
         imageOutputStream.close();
      } catch (final IOException e) {
      }
   }
}
 
Example 30
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 5 votes vote down vote up
private static List<BufferedImage> loadFromStream(ImageInputStream imageStream) throws IOException {
  Iterable<ImageReader> it = () -> ImageIO.getImageReaders(imageStream);
  ImageReader reader = StreamSupport.stream(it.spliterator(), false)
      .filter(MainPanel::checkGifFormat)
      .findFirst()
      .orElseThrow(() -> new IOException("Can not read image format!"));
  reader.setInput(imageStream, false, false);
  List<BufferedImage> list = new ArrayList<>();
  for (int i = 0; i < reader.getNumImages(true); i++) {
    IIOImage frame = reader.readAll(i, null);
    list.add((BufferedImage) frame.getRenderedImage());
  }
  reader.dispose();
  return list;
}