Example usage for org.apache.commons.imaging Imaging getImageInfo

List of usage examples for org.apache.commons.imaging Imaging getImageInfo

Introduction

In this page you can find the example usage for org.apache.commons.imaging Imaging getImageInfo.

Prototype

public static ImageInfo getImageInfo(final File file) throws ImageReadException, IOException 

Source Link

Document

Parses the "image info" of an image file.

Usage

From source file:com.imagesleuth.imagesleuthclient2.Poster.java

public String Post(final File imgFile) throws IOException, ImageReadException, InterruptedException {

    final ArrayList<String> idArray = new ArrayList<>();

    final CountDownLatch latch = new CountDownLatch(1);

    try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultHeaders(harray)
            .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(requestConfig).build()) {
        httpclient.start();/*from ww  w  . ja  v  a 2 s.  c  o  m*/
        final byte[] imageAsBytes = IOUtils.toByteArray(new FileInputStream(imgFile));
        final ImageInfo info = Imaging.getImageInfo(imageAsBytes);
        final HttpPost request = new HttpPost(urlval);
        String boundary = UUID.randomUUID().toString();
        HttpEntity mpEntity = MultipartEntityBuilder.create().setBoundary("-------------" + boundary)
                .addBinaryBody("file", imageAsBytes, ContentType.create(info.getMimeType()), imgFile.getName())
                .build();
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        mpEntity.writeTo(baoStream);
        request.setHeader("Content-Type", "multipart/form-data;boundary=-------------" + boundary);
        //equest.setHeader("Content-Type", "multipart/form-data");                               
        NByteArrayEntity entity = new NByteArrayEntity(baoStream.toByteArray(),
                ContentType.MULTIPART_FORM_DATA);
        request.setEntity(entity);
        httpclient.execute(request, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response) {
                int code = response.getStatusLine().getStatusCode();
                //System.out.println(" response code: " + code + " for image: " + imgFile.getName());
                if (response.getEntity() != null && code == 202) {
                    StringWriter writer = new StringWriter();
                    try {
                        IOUtils.copy(response.getEntity().getContent(), writer);
                        idArray.add(writer.toString());
                        writer.close();
                        //System.out.println(" response id: " + id + " for image "+ img.getName()); 
                        latch.countDown();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else {
                    System.out.println(" response code: " + code + " for image: " + imgFile.getName()
                            + " reason " + response.getStatusLine().getReasonPhrase());
                }
            }

            @Override
            public void failed(final Exception ex) {
                System.out.println(request.getRequestLine() + imgFile.getName() + "->" + ex);
                latch.countDown();
            }

            @Override
            public void cancelled() {
                System.out.println(request.getRequestLine() + " cancelled");
                latch.countDown();
            }

        });
        latch.await();
    }
    if (idArray.isEmpty()) {
        return null;
    } else {
        return idArray.get(0);
    }
}

From source file:adams.data.image.ImageMetaDataHelper.java

/**
 * Reads the meta-data from the file (Commons Imaging).
 *
 * @param file   the file to read the meta-data from
 * @return      the meta-data/* w  w  w.  j  av a 2  s.com*/
 * @throws Exception   if failed to read meta-data
 */
public static SpreadSheet commons(File file) throws Exception {
    SpreadSheet sheet;
    Row row;
    org.apache.commons.imaging.common.ImageMetadata meta;
    String[] parts;
    String key;
    String value;
    org.apache.commons.imaging.ImageInfo info;
    String infoStr;
    String[] lines;
    HashSet<String> keys;

    sheet = new DefaultSpreadSheet();

    // header
    row = sheet.getHeaderRow();
    row.addCell("K").setContent("Key");
    row.addCell("V").setContent("Value");

    keys = new HashSet<String>();

    // meta-data
    meta = Imaging.getMetadata(file.getAbsoluteFile());
    if (meta != null) {
        for (Object item : meta.getItems()) {
            key = null;
            value = null;
            if (item instanceof ImageMetadata.Item) {
                key = ((ImageMetadata.Item) item).getKeyword().trim();
                value = ((ImageMetadata.Item) item).getText().trim();
            } else {
                parts = item.toString().split(": ");
                if (parts.length == 2) {
                    key = parts[0].trim();
                    value = parts[1].trim();
                }
            }
            if (key != null) {
                if (!keys.contains(key)) {
                    keys.add(key);
                    row = sheet.addRow();
                    row.addCell("K").setContent(key);
                    row.addCell("V").setContent(fixDateTime(Utils.unquote(value)));
                }
            }
        }
    }

    // image info
    info = Imaging.getImageInfo(file.getAbsoluteFile());
    if (info != null) {
        infoStr = info.toString();
        lines = infoStr.split(System.lineSeparator());
        for (String line : lines) {
            parts = line.split(": ");
            if (parts.length == 2) {
                key = parts[0].trim();
                value = parts[1].trim();
                if (!keys.contains(key)) {
                    row = sheet.addRow();
                    row.addCell("K").setContent(key);
                    row.addCell("V").setContent(Utils.unquote(value));
                    keys.add(key);
                }
            }
        }
    }

    return sheet;
}

From source file:com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpRenderListener.java

private byte[] processImage(byte[] imageBytes, List<Rectangle> areasToBeCleaned) {
    if (areasToBeCleaned.isEmpty()) {
        return imageBytes;
    }/*from w  ww  . ja va 2 s  .  c o  m*/

    try {
        BufferedImage image = Imaging.getBufferedImage(imageBytes);
        ImageInfo imageInfo = Imaging.getImageInfo(imageBytes);
        cleanImage(image, areasToBeCleaned);

        // Apache can only read JPEG, so we should use awt for writing in this format
        if (imageInfo.getFormat() == ImageFormats.JPEG) {
            return getJPGBytes(image);
        } else {
            Map<String, Object> params = new HashMap<String, Object>();

            if (imageInfo.getFormat() == ImageFormats.TIFF) {
                params.put(ImagingConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_LZW);
            }

            return Imaging.writeImageToBytes(image, imageInfo.getFormat(), params);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.commons.imaging.examples.SampleUsage.java

@SuppressWarnings("unused")
public SampleUsage() {

    try {/* w  w w.j  a v  a  2s .  c  o  m*/
        // <b>Code won't work unless these variables are properly
        // initialized.
        // Imaging works equally well with File, byte array or InputStream
        // inputs.</b>
        final BufferedImage someImage = null;
        final byte someBytes[] = null;
        final File someFile = null;
        final InputStream someInputStream = null;
        final OutputStream someOutputStream = null;

        // <b>The Imaging class provides a simple interface to the library.
        // </b>

        // <b>how to read an image: </b>
        final byte imageBytes[] = someBytes;
        final BufferedImage image_1 = Imaging.getBufferedImage(imageBytes);

        // <b>methods of Imaging usually accept files, byte arrays, or
        // inputstreams as arguments. </b>
        final BufferedImage image_2 = Imaging.getBufferedImage(imageBytes);
        final File file = someFile;
        final BufferedImage image_3 = Imaging.getBufferedImage(file);
        final InputStream is = someInputStream;
        final BufferedImage image_4 = Imaging.getBufferedImage(is);

        // <b>Write an image. </b>
        final BufferedImage image = someImage;
        final File dst = someFile;
        final ImageFormat format = ImageFormats.PNG;
        final Map<String, Object> optionalParams = new HashMap<>();
        Imaging.writeImage(image, dst, format, optionalParams);

        final OutputStream os = someOutputStream;
        Imaging.writeImage(image, os, format, optionalParams);

        // <b>get the image's embedded ICC Profile, if it has one. </b>
        final byte iccProfileBytes[] = Imaging.getICCProfileBytes(imageBytes);

        final ICC_Profile iccProfile = Imaging.getICCProfile(imageBytes);

        // <b>get the image's width and height. </b>
        final Dimension d = Imaging.getImageSize(imageBytes);

        // <b>get all of the image's info (ie. bits per pixel, size,
        // transparency, etc.) </b>
        final ImageInfo imageInfo = Imaging.getImageInfo(imageBytes);

        if (imageInfo.getColorType() == ImageInfo.ColorType.GRAYSCALE) {
            System.out.println("Grayscale image.");
        }
        if (imageInfo.getHeight() > 1000) {
            System.out.println("Large image.");
        }

        // <b>try to guess the image's format. </b>
        final ImageFormat imageFormat = Imaging.guessFormat(imageBytes);
        imageFormat.equals(ImageFormats.PNG);

        // <b>get all metadata stored in EXIF format (ie. from JPEG or
        // TIFF). </b>
        final ImageMetadata metadata = Imaging.getMetadata(imageBytes);

        // <b>print a dump of information about an image to stdout. </b>
        Imaging.dumpImageFile(imageBytes);

        // <b>get a summary of format errors. </b>
        final FormatCompliance formatCompliance = Imaging.getFormatCompliance(imageBytes);

    } catch (final Exception e) {

    }
}

From source file:org.imaging.CommonsImagingVariousExamples.java

public CommonsImagingVariousExamples() {

    try {//w  w  w . ja va  2  s.  c  o m
        // <b>Code won't work unless these variables are properly
        // initialized.
        // Imaging works equally well with File, byte array or InputStream
        // inputs.</b>
        final BufferedImage someImage = null;
        final byte someBytes[] = null;
        final File someFile = null;
        final InputStream someInputStream = null;
        final OutputStream someOutputStream = null;

        // <b>The Imaging class provides a simple interface to the library.
        // </b>

        // <b>how to read an image: </b>
        final byte imageBytes[] = someBytes;
        final BufferedImage image_1 = Imaging.getBufferedImage(imageBytes);

        // <b>methods of Imaging usually accept files, byte arrays, or
        // inputstreams as arguments. </b>
        final BufferedImage image_2 = Imaging.getBufferedImage(imageBytes);
        final File file = someFile;
        final BufferedImage image_3 = Imaging.getBufferedImage(file);
        final InputStream is = someInputStream;
        final BufferedImage image_4 = Imaging.getBufferedImage(is);

        // <b>Write an image. </b>
        final BufferedImage image = someImage;
        final File dst = someFile;
        final ImageFormat format = ImageFormats.PNG;
        final Map<String, Object> optionalParams = new HashMap<String, Object>();
        Imaging.writeImage(image, dst, format, optionalParams);

        final OutputStream os = someOutputStream;
        Imaging.writeImage(image, os, format, optionalParams);

        // <b>get the image's embedded ICC Profile, if it has one. </b>
        final byte iccProfileBytes[] = Imaging.getICCProfileBytes(imageBytes);

        final ICC_Profile iccProfile = Imaging.getICCProfile(imageBytes);

        // <b>get the image's width and height. </b>
        final Dimension d = Imaging.getImageSize(imageBytes);

        // <b>get all of the image's info (ie. bits per pixel, size,
        // transparency, etc.) </b>
        final ImageInfo imageInfo = Imaging.getImageInfo(imageBytes);

        if (imageInfo.getColorType() == ImageInfo.ColorType.GRAYSCALE) {
            System.out.println("Grayscale image.");
        }
        if (imageInfo.getHeight() > 1000) {
            System.out.println("Large image.");
        }

        // <b>try to guess the image's format. </b>
        final ImageFormat imageFormat = Imaging.guessFormat(imageBytes);
        imageFormat.equals(ImageFormats.PNG);

        // <b>get all metadata stored in EXIF format (ie. from JPEG or
        // TIFF). </b>
        final ImageMetadata metadata = Imaging.getMetadata(imageBytes);

        // <b>print a dump of information about an image to stdout. </b>
        Imaging.dumpImageFile(imageBytes);

        // <b>get a summary of format errors. </b>
        final FormatCompliance formatCompliance = Imaging.getFormatCompliance(imageBytes);

    } catch (final Exception e) {
        e.printStackTrace();
    }
}