Example usage for javax.imageio ImageIO createImageInputStream

List of usage examples for javax.imageio ImageIO createImageInputStream

Introduction

In this page you can find the example usage for javax.imageio ImageIO createImageInputStream.

Prototype

public static ImageInputStream createImageInputStream(Object input) throws IOException 

Source Link

Document

Returns an ImageInputStream that will take its input from the given Object .

Usage

From source file:net.filterlogic.util.imaging.ToTIFF.java

/**
 * Convert multipage TIFF to single page TIFF.
 * @param srcFiles Array of source files to convert.
 * @param destPath Folder to store single page TIFFs in.
 * @param archivePath Path to move source TIFF files to after single page TIFFs created.
 * @param pattern Pattern of single page TIFF file names.  Java NumberFormatter used with page number to create file name.
 * @param multipage Set to true if source TIFFs should be coverted to multi-page TIFF.
 * @param dpi DPI to set TIFFs to./*from ww  w.java2s.  c  o  m*/
 * @return Returns a list of files in destination path.
 * @throws net.filterlogic.util.imaging.OpenCaptureImagingException
 */
public static List toTIFF(String[] srcFiles, String destPath, String archivePath, String pattern,
        boolean multipage, int dpi) throws OpenCaptureImagingException {
    String pathSep = System.getProperty("file.separator");
    boolean jaiSupport = true;

    int pageCount = 0;
    int fileNameCount = 0;

    byte[] imageData = null;

    // make sure destpath has trailing slash.
    if (destPath.lastIndexOf(pathSep) != destPath.length() - 1)
        destPath += pathSep;

    // create path if doesn't exist
    if (!Path.ValidatePath(destPath))
        if (!Path.createPath(destPath))
            throw new OpenCaptureImagingException(
                    "Unable to create destination path for imported images [" + destPath + "]");

    // make sure archivePath has trailing slash
    if (archivePath.lastIndexOf(pathSep) != archivePath.length() - 1)
        archivePath += pathSep;

    if (!Path.ValidatePath(archivePath))
        if (!Path.createPath(archivePath))
            throw new OpenCaptureImagingException(
                    "Unable to create archive path for imported images [" + archivePath + "]");

    // set a default pattern if one not passed.
    if (pattern.trim().length() < 1)
        pattern = "#";

    NumberFormat formatter = new DecimalFormat(pattern);

    ArrayList<String> list = new ArrayList<String>();

    for (int i = 0; i < srcFiles.length; i++) {
        try {

            File f = new File(srcFiles[i]);
            imageData = null;

            ImageIO.setUseCache(false);
            ImageInputStream imageInputStream = ImageIO.createImageInputStream(f);
            java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream);

            ImageReader reader1 = null;

            if (readers.hasNext()) {
                reader1 = (ImageReader) readers.next();
                jaiSupport = true;
            } else
                jaiSupport = false;

            if (jaiSupport) {
                //ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f));
                reader1.setInput(imageInputStream);

                pageCount = reader1.getNumImages(true);
            } else {
                String newFileName = bigEndian2LittleEndian(f.getAbsolutePath());

                if (imageInputStream != null) {
                    imageInputStream.flush();
                    imageInputStream.close();

                    reader1.setInput(imageInputStream);
                    pageCount = reader1.getNumImages(true);

                }

                imageInputStream = ImageIO.createImageInputStream(new File(newFileName));

                readers = ImageIO.getImageReaders(imageInputStream);

            }
            //                Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
            //                ImageWriter writer = (ImageWriter)writers.next();

            //ImageWriteParam param = writer.getDefaultWriteParam();

            //param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

            //String[] legalTypes = param.getCompressionTypes();

            //param.setCompressionType("PackBits");

            //ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ImageOutputStream ios = null;
            BufferedImage img = null;

            // break out each page to single file
            for (int t = 0; t < pageCount; t++) {

                // format filenumber
                String tifName = destPath + formatter.format(fileNameCount) + ".tif";

                while (new File(tifName).exists()) {
                    tifName = destPath + formatter.format(++fileNameCount) + ".tif";
                }

                FileOutputStream file = new FileOutputStream(new File(tifName));

                if (jaiSupport) {
                    img = reader1.read(t);
                    IIOImage iioimg = reader1.readAll(t, null);
                    //ios = ImageIO.createImageOutputStream(file);
                    //IIOMetadata iiom = getMetadata(writer, img, null, 200);
                } else {
                    img = loadTIFF(imageData, t);
                }
                TIFFEncodeParam tep = setEncoder(TIFFEncodeParam.COMPRESSION_PACKBITS, 200);

                ImageEncoder encoder = ImageCodec.createImageEncoder("TIFF", file, tep);

                encoder.encode(img);
                //boolean ok = ImageIO.write(img, "tiff", ios);
                //writer.setOutput(ios);
                //writer.write(iiom, iioimg, null);

                img.flush();

                //ios.flush();
                //ios.close();
                // ios = null;
                //iioimg = null;
                //iiom = null;
                img = null;
                //writer.dispose();
                //byteOut.flush();
                file.close();

                file = null;

                //System.out.println("Add file!");

                list.add(tifName);
            }

            if (jaiSupport) {
                reader1.dispose();
            }

            readers = null;

            //                writer.dispose();
            //                writers = null;

            imageInputStream.flush();
            imageInputStream.close();
            imageInputStream = null;

            f = null;

            // move file with overwrite
            if (!net.filterlogic.io.FileAccess.Move(srcFiles[i], archivePath, true))
                throw new Exception("Unable to move input file to archive path [" + srcFiles[i] + "] to ["
                        + archivePath + "]");

        } catch (Exception e) {
            throw new OpenCaptureImagingException(e.toString());
        }
    }

    return list;
}

From source file:nl.b3p.viewer.print.PrintInfo.java

/**
 * Load image dimensions, ideally without decoding the entire image.
 *//* w  w w .j  a v a 2s .  co m*/
private static Dimension getImageDimension(InputStream image) throws IOException {
    // http://stackoverflow.com/questions/1559253/java-imageio-getting-image-dimension-without-reading-the-entire-file

    ImageInputStream in = ImageIO.createImageInputStream(image);
    try {
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ImageReader reader = readers.next();
            try {
                reader.setInput(in);
                return new Dimension(reader.getWidth(0), reader.getHeight(0));
            } finally {
                reader.dispose();
            }
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
    return null;
}

From source file:openthinks.others.htmlunit.PageKeeper.java

private StringBuffer keepStyleReference(String styleCtx) {
    Matcher matcher = RESOURCE_STYLE_REFERENCE_PATTERN.matcher(styleCtx);
    File refDir = new File(keepDir, RESOURCE_STYLE_REFERENCE_DIR);
    if (!refDir.exists())
        refDir.mkdirs();/*from  w  w w .j  av  a  2  s.  c o  m*/
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String relativeURL = matcher.group(1);
        String styleRefUrl = getFullyQualifiedUrl(relativeURL);
        String styleRefName = getResourceName(styleRefUrl);
        String styleRefCtx = "";
        File keepFile = new File(refDir, styleRefName);
        WebResponse wrp = null;
        try {
            checkIfAlreadExist(keepFile);
            wrp = getResourceResponse(styleRefUrl);
            if (wrp.getContentType().startsWith("image") || wrp.getContentType().startsWith("IMAGE")) {
                ImageInputStream iis = ImageIO.createImageInputStream(wrp.getContentAsStream());
                Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
                ImageReader imageReader = iter.next();
                imageReader.setInput(iis);
                ImageIO.write(imageReader.read(0), imageReader.getFormatName(), keepFile);
            } else {
                styleRefCtx = wrp.getContentAsString("UTF-8");
                store(styleRefCtx, keepFile);
            }
            matcher.appendReplacement(sb, "url(" + RESOURCE_STYLE_REFERENCE_URL + "/" + styleRefName + ")");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            matcher.appendReplacement(sb, "url(" + RESOURCE_STYLE_REFERENCE_URL + "/" + styleRefName + ")");
        } catch (NoSuchElementException e) {
            if (wrp != null) {
                styleRefCtx = wrp.getContentAsString("UTF-8");
                store(styleRefCtx, keepFile);
                matcher.appendReplacement(sb, "url(" + RESOURCE_STYLE_REFERENCE_URL + "/" + styleRefName + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    matcher.appendTail(sb);
    return sb;
}

From source file:org.gmdev.pdftrick.utils.CustomExtraImgReader.java

/**
 * Read a png image with if all other method fails
 * @param ref/* w w w  . j a  v a  2s.  co m*/
 * @param resultFile
 * @return The BufferedImage obj
 * @throws IOException
 * @throws ImageReadException
 */
public static BufferedImage readIndexedPNG(int ref, String resultFile) throws IOException, ImageReadException {

    PdfReader reader = new PdfReader(resultFile);
    PRStream stream = (PRStream) reader.getPdfObject(ref);
    PdfDictionary dic = stream;
    byte[] content = PdfReader.getStreamBytesRaw(stream);

    int width = dic.getAsNumber(PdfName.WIDTH).intValue();
    int height = dic.getAsNumber(PdfName.HEIGHT).intValue();
    int pngBitDepth = dic.getAsNumber(PdfName.BITSPERCOMPONENT).intValue();

    PdfObject colorspace = dic.getDirectObject(PdfName.COLORSPACE);
    PdfArray decode = dic.getAsArray(PdfName.DECODE);
    PdfArray carray = (PdfArray) colorspace;
    PdfObject id2 = carray.getDirectObject(3);

    byte[] palette = null;
    if (id2 instanceof PdfString) {
        palette = ((PdfString) id2).getBytes();
    } else if (id2 instanceof PRStream) {
        palette = PdfReader.getStreamBytes(((PRStream) id2));
    }

    Map<PdfName, FilterHandlers.FilterHandler> handlers = new HashMap<PdfName, FilterHandlers.FilterHandler>(
            FilterHandlers.getDefaultFilterHandlers());
    byte[] imageBytes = PdfReader.decodeBytes(content, dic, handlers);

    int stride = (width * pngBitDepth + 7) / 8;
    ByteArrayOutputStream ms = new ByteArrayOutputStream();
    PngWriter png = new PngWriter(ms);

    if (decode != null) {
        if (pngBitDepth == 1) {
            // if the decode array is 1,0, then we need to invert the image
            if (decode.getAsNumber(0).intValue() == 1 && decode.getAsNumber(1).intValue() == 0) {
                int len = imageBytes.length;
                for (int t = 0; t < len; ++t) {
                    imageBytes[t] ^= 0xff;
                }
            } else {
                // if the decode array is 0,1, do nothing.  It's possible that the array could be 0,0 or 1,1 - but that would be silly, so we'll just ignore that case
            }
        } else {
            // todo: add decode transformation for other depths
        }
    }
    int pngColorType = 0;
    png.writeHeader(width, height, pngBitDepth, pngColorType);

    if (palette != null) {
        png.writePalette(palette);
    }
    png.writeData(imageBytes, stride);
    png.writeEnd();

    imageBytes = ms.toByteArray();

    InputStream in = new ByteArrayInputStream(imageBytes);
    ImageInputStream ima_stream = ImageIO.createImageInputStream(in);

    BufferedImage buffImg = null;
    BufferedImage buffPic = ImageIO.read(ima_stream);

    // check if image contains a mask image ... experimental for this type of image
    BufferedImage buffMask = null;
    PRStream maskStream = (PRStream) dic.getAsStream(PdfName.SMASK);
    if (maskStream != null) {
        PdfImageObject maskImage = new PdfImageObject(maskStream);
        buffMask = maskImage.getBufferedImage();

        Image img = PdfTrickUtils.TransformGrayToTransparency(buffMask);
        buffImg = PdfTrickUtils.ApplyTransparency(buffPic, img);
    } else {
        buffImg = buffPic;
    }

    reader.close();
    ms.close();
    in.close();
    return buffImg;
}

From source file:com.crimelab.service.PolygraphServiceImpl.java

@Override
public XWPFDocument create(Polygraph polygraph, HttpSession session) {
    XWPFDocument document = null;//from  ww  w.j  a  v a  2  s  .c  om

    //Insert into dbase
    //        polygraphDAO.polygraphInfo(polygraph);
    try {
        //Blank Document
        InputStream inpDocx = session.getServletContext()
                .getResourceAsStream("/WEB-INF/templates/Polygraph.docx");
        document = new XWPFDocument(inpDocx);

        //create Paragraph
        XWPFParagraph subjectNo = document.createParagraph();
        XWPFRun r1 = subjectNo.createRun();
        r1.setText("POLYGRAPH SUBJECT NO: " + polygraph.getSubjectNo());
        subjectNo.setAlignment(ParagraphAlignment.CENTER);
        r1.setBold(true);
        ;

        //create table
        XWPFTable table = document.createTable();
        //width 
        CTTbl tableFix = table.getCTTbl();
        CTTblPr pr = tableFix.getTblPr();
        CTTblWidth tblW = pr.getTblW();
        tblW.setW(BigInteger.valueOf(4800));
        tblW.setType(STTblWidth.PCT);
        pr.setTblW(tblW);
        tableFix.setTblPr(pr);

        //create first row
        XWPFTableRow tableRowOne = table.getRow(0);
        XWPFTableCell headerCell = tableRowOne.getCell(0);
        XWPFParagraph headerParagraph = headerCell.getParagraphs().get(0);
        XWPFRun hRun = headerParagraph.createRun();
        headerCell.setColor("CDCDB4");
        hRun.setText("PERSONAL INFORMATION");
        tableRowOne.addNewTableCell().setText(null);

        headerParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFTableCell photoHeaderCell = tableRowOne.getCell(1);
        XWPFParagraph photoHeaderParagraph = photoHeaderCell.getParagraphs().get(0);
        XWPFRun pRun = photoHeaderParagraph.createRun();
        photoHeaderCell.setColor("CDCDB4");
        pRun.setText("PHOTO");
        photoHeaderParagraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFTableRow tableRowTwo = table.createRow();
        XWPFTableCell cell = tableRowTwo.getCell(0);
        XWPFParagraph personalInfo = cell.getParagraphs().get(0);
        XWPFRun r2 = personalInfo.createRun();
        r2.setText("Name");
        r2.addTab();
        r2.addTab();
        r2.setText(": " + polygraph.getName());
        r2.addBreak();
        r2.setText("Gender");
        r2.addTab();
        r2.addTab();
        r2.setText(": " + polygraph.getGender());
        r2.addBreak();
        r2.setText("Age");
        r2.addTab();
        r2.addTab();
        r2.setText(": " + polygraph.getAge());
        r2.addBreak();
        r2.setText("Date of Birth");
        r2.addTab();
        r2.setText(": " + polygraph.getBirthdate());
        r2.addBreak();
        r2.setText("Civil Status");
        r2.addTab();
        r2.setText(": " + polygraph.getCivilStatus());
        r2.addBreak();
        r2.setText("ID Presented");
        r2.addTab();
        r2.setText(": " + polygraph.getIdPresented());
        r2.addBreak();
        r2.setText("Address");
        r2.addTab();
        r2.setText(": " + polygraph.getAddress());

        //Adding the picture
        XWPFTableCell pictureCell = tableRowTwo.getCell(1);
        XWPFParagraph pictureHolder = pictureCell.getParagraphs().get(0);
        XWPFRun pictureRun = pictureHolder.createRun();
        FileInputStream getPhoto = new FileInputStream(polygraph.getPhotoLocation());
        FileInputStream getImage = new FileInputStream(polygraph.getPhotoLocation());
        ImageInputStream imageInput = ImageIO.createImageInputStream(getPhoto);
        BufferedImage bi = ImageIO.read(imageInput);
        pictureHolder.setAlignment(ParagraphAlignment.RIGHT);
        pictureRun.addPicture(getImage, XWPFDocument.PICTURE_TYPE_JPEG, null, Units.toEMU(120),
                Units.toEMU(120));

        XWPFParagraph spacing = document.createParagraph();
        XWPFRun spacingRun = spacing.createRun();

        //create table
        XWPFTable otherTable = document.createTable();
        //width 
        CTTbl tableFixTwo = otherTable.getCTTbl();
        CTTblPr prTwo = tableFixTwo.getTblPr();
        CTTblWidth tblWTwo = prTwo.getTblW();
        tblWTwo.setW(BigInteger.valueOf(4800));
        tblWTwo.setType(STTblWidth.PCT);
        prTwo.setTblW(tblWTwo);
        tableFixTwo.setTblPr(prTwo);

        XWPFTableRow examInfoHeader = otherTable.createRow();
        XWPFTableCell cellInfo = examInfoHeader.getCell(0);
        XWPFParagraph examInfo = cellInfo.getParagraphs().get(0);
        XWPFRun r3 = examInfo.createRun();
        cellInfo.setColor("CDCDB4");
        r3.setText("EXAM INFORMATION");
        examInfo.setAlignment(ParagraphAlignment.CENTER);

        XWPFTableRow examInfoRow = otherTable.createRow();
        XWPFTableCell cellRowInfo = examInfoRow.getCell(0);
        XWPFParagraph examInfoRowP = cellRowInfo.getParagraphs().get(0);
        XWPFRun examRun = examInfoRowP.createRun();
        examRun.setText("Case Number");
        examRun.addTab();
        examRun.addTab();
        examRun.setText(": " + polygraph.getCaseNo());
        examRun.addBreak();
        examRun.setText("Requesting Party");
        examRun.addTab();
        examRun.setText(": " + polygraph.getRequestingParty());
        examRun.addBreak();
        examRun.setText("Time/Date Received");
        examRun.addTab();
        examRun.setText(": " + polygraph.getTimeDateReceived());
        examRun.addBreak();
        examRun.setText("Nature of Case");
        examRun.addTab();
        examRun.addTab();
        examRun.setText(": " + polygraph.getNatureOfCase());
        examRun.addBreak();
        examRun.setText("Exam Location");
        examRun.addTab();
        examRun.addTab();
        examRun.setText(": " + polygraph.getExamLocation());
        examRun.addBreak();
        examRun.setText("Exam Date");
        examRun.addTab();
        examRun.addTab();
        examRun.setText(": " + polygraph.getExamDate());

        otherTable.removeRow(0);

        XWPFParagraph purposeOfExamination = document.createParagraph();
        XWPFRun r4 = purposeOfExamination.createRun();
        r4.setUnderline(UnderlinePatterns.SINGLE);
        r4.addBreak();
        r4.setText("SECTION 1: PURPOSE OF EXAMINATION");
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();
        r4.addTab();

        XWPFParagraph purposeOfExaminationContents = document.createParagraph();
        XWPFRun r4Contents = purposeOfExaminationContents.createRun();
        r4Contents.setText(polygraph.getPurpose());

        XWPFParagraph preTestInterview = document.createParagraph();
        XWPFRun r5 = preTestInterview.createRun();
        r5.setUnderline(UnderlinePatterns.SINGLE);
        r5.setText("SECTION 2: PRE-TEST INTERVIEW");
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();
        r5.addTab();

        XWPFParagraph preTestInterviewContents = document.createParagraph();
        XWPFRun r5Contents = preTestInterviewContents.createRun();
        r5Contents.setText(polygraph.getPreTest());

        XWPFParagraph inTestPhase = document.createParagraph();
        XWPFRun r6 = inTestPhase.createRun();
        r6.setUnderline(UnderlinePatterns.SINGLE);
        r6.setText("SECTION 3: IN-TEST PHASE");
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();
        r6.addTab();

        XWPFParagraph inTestPhaseContents = document.createParagraph();
        XWPFRun r6Contents = inTestPhaseContents.createRun();
        r6Contents.setText(polygraph.getInTest());

        XWPFParagraph result = document.createParagraph();
        XWPFRun r7 = result.createRun();
        r7.setUnderline(UnderlinePatterns.SINGLE);
        r7.setText("SECTION 4: RESULT");
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();
        r7.addTab();

        XWPFParagraph resultContents = document.createParagraph();
        XWPFRun r7Contents = resultContents.createRun();
        r7Contents.setText(polygraph.getResult());

        XWPFParagraph postTestInterview = document.createParagraph();
        XWPFRun r8 = postTestInterview.createRun();
        r8.setUnderline(UnderlinePatterns.SINGLE);
        r8.setText("SECTION 5: POST-TEST INTERVIEW");
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();
        r8.addTab();

        XWPFParagraph postTestInterviewContents = document.createParagraph();
        XWPFRun r8Contents = postTestInterviewContents.createRun();
        r8Contents.setText(polygraph.getPostTest());

        XWPFParagraph remarks = document.createParagraph();
        XWPFRun r9 = remarks.createRun();
        r9.setUnderline(UnderlinePatterns.SINGLE);
        r9.setText("REMARKS:");
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();
        r9.addTab();

        XWPFParagraph remarksContents = document.createParagraph();
        XWPFRun r9Contents = remarksContents.createRun();
        r9Contents.setText(polygraph.getRemarks());

        XWPFParagraph timeDateCompleted = document.createParagraph();
        XWPFRun r10 = timeDateCompleted.createRun();
        r10.setUnderline(UnderlinePatterns.SINGLE);
        r10.setText("TIME AND DATE COMPLETED:");
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();
        r10.addTab();

        XWPFParagraph timeDateCompletedContents = document.createParagraph();
        XWPFRun r10Contents = timeDateCompletedContents.createRun();
        r10Contents.setText(polygraph.getTimeDateCompleted());

        XWPFParagraph examinedBy = document.createParagraph();
        XWPFRun r11 = examinedBy.createRun();
        r11.setUnderline(UnderlinePatterns.SINGLE);
        r11.setText("EXAMINED BY:");
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();
        r11.addTab();

        XWPFParagraph examinedByContents = document.createParagraph();
        XWPFRun r11Contents = examinedByContents.createRun();
        r11Contents.setText(polygraph.getExaminerName());
        r11Contents.addBreak();
        r11Contents.setText(polygraph.getExaminerRank());
        r11Contents.addBreak();
        r11Contents.setText(polygraph.getExaminerPosition());

        XWPFParagraph approvedBy = document.createParagraph();
        XWPFRun r12 = approvedBy.createRun();
        r12.setUnderline(UnderlinePatterns.SINGLE);
        r12.setText("APPROVED BY:");
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();
        r12.addTab();

        XWPFParagraph approvedByContents = document.createParagraph();
        XWPFRun r12Contents = approvedByContents.createRun();
        //            r12Contents.setText(polygraph.getApprovedName());
        //            r12Contents.addBreak();
        //            r12Contents.setText(polygraph.getApprovedRank());
        //            r12Contents.addBreak();
        //            r12Contents.setText(polygraph.getApprovedPosition());
        //            r12Contents.addBreak();

        XWPFParagraph notedBy = document.createParagraph();
        XWPFRun r13 = notedBy.createRun();
        r13.setUnderline(UnderlinePatterns.SINGLE);
        r13.setText("NOTED BY:");
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();
        r13.addTab();

        XWPFParagraph notedByContents = document.createParagraph();
        XWPFRun r13Contents = notedByContents.createRun();
        r13Contents.setText(polygraph.getNotedName());
        r13Contents.addBreak();
        r13Contents.setText(polygraph.getNotedRank());
        r13Contents.addBreak();
        r13Contents.setText(polygraph.getNotedPosition());
        r13Contents.addBreak();
        table.setInsideVBorder(XWPFTable.XWPFBorderType.NIL, 0, 0, "white");

        document.getXWPFDocument();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return document;
}

From source file:org.apache.tika.parser.image.ImageParser.java

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {
    String type = metadata.get(Metadata.CONTENT_TYPE);
    if (type != null) {
        // If the old (pre-RFC7903) BMP mime type is given,
        //  fix it up to the new one, so Java is happy
        if (OLD_BMP_TYPE.toString().equals(type)) {
            type = MAIN_BMP_TYPE.toString();
        }//from  w  ww  .  j a v a  2s. c  o m

        try {
            Iterator<ImageReader> iterator = ImageIO.getImageReadersByMIMEType(type);
            if (iterator.hasNext()) {
                ImageReader reader = iterator.next();
                try {
                    try (ImageInputStream imageStream = ImageIO
                            .createImageInputStream(new CloseShieldInputStream(stream))) {
                        reader.setInput(imageStream);

                        metadata.set(Metadata.IMAGE_WIDTH, Integer.toString(reader.getWidth(0)));
                        metadata.set(Metadata.IMAGE_LENGTH, Integer.toString(reader.getHeight(0)));
                        metadata.set("height", Integer.toString(reader.getHeight(0)));
                        metadata.set("width", Integer.toString(reader.getWidth(0)));

                        loadMetadata(reader.getImageMetadata(0), metadata);
                    }
                } finally {
                    reader.dispose();
                }
            }

            // Translate certain Metadata tags from the ImageIO
            //  specific namespace into the general Tika one
            setIfPresent(metadata, "CommentExtensions CommentExtension", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "markerSequence com", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "Data BitsPerSample", Metadata.BITS_PER_SAMPLE);
        } catch (IIOException e) {
            // TIKA-619: There is a known bug in the Sun API when dealing with GIF images
            //  which Tika will just ignore.
            if (!(e.getMessage() != null && e.getMessage().equals("Unexpected block type 0!")
                    && type.equals("image/gif"))) {
                throw new TikaException(type + " parse error", e);
            }
        }
    }

    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();
    xhtml.endDocument();
}

From source file:uk.bl.wa.analyser.payload.FaceDetectionAnalyser.java

@Override
public void analyse(String source, ArchiveRecordHeader header, InputStream tikainput, SolrRecord solr) {
    // Set up metadata object to pass to parsers:
    Metadata metadata = new Metadata();
    // Skip large images:
    if (header.getLength() > max_size_bytes) {
        return;/*from   w w w  .jav  a 2 s. c  om*/
    }

    // Only attempt to analyse a random sub-set of the data:
    // (prefixing with static test of a final value to allow JIT to fully
    // optimise out the "OR Math.random()" bit)
    if (sampleRate >= 1.0 || Math.random() < sampleRate) {
        // Increment number of images sampled:
        sampleCount++;

        // Attempt to extract faces etc.:
        if (this.extractFaces || this.extractDominantColours) {
            log.info("Attempting to parse image file: " + header.getUrl());
            final long deepStart = System.nanoTime();
            ParseRunner parser = new ParseRunner(fdp, tikainput, metadata, solr);
            try {
                TimeLimiter.run(parser, 30000L, false);
            } catch (Exception e) {
                log.error("WritableSolrRecord.extract(): " + e.getMessage());
                solr.addParseException("when scanning for faces", e);
            }
            // Store basic image data:
            solr.addField(SolrFields.IMAGE_HEIGHT, metadata.get(FaceDetectionParser.IMAGE_HEIGHT));
            solr.addField(SolrFields.IMAGE_WIDTH, metadata.get(FaceDetectionParser.IMAGE_WIDTH));
            solr.addField(SolrFields.IMAGE_SIZE, metadata.get(FaceDetectionParser.IMAGE_SIZE));
            if (this.extractFaces) {
                // Store faces in SOLR:
                for (String face : metadata.getValues(FaceDetectionParser.FACE_FRAGMENT_ID)) {
                    log.debug("Found a face!");
                    solr.addField(SolrFields.IMAGE_FACES, face);
                }
                int faces = metadata.getValues(FaceDetectionParser.FACE_FRAGMENT_ID).length;
                if (faces > 0)
                    solr.setField(SolrFields.IMAGE_FACES_COUNT, "" + faces);
            }
            if (this.extractDominantColours) {
                // Store colour:
                solr.addField(SolrFields.IMAGE_DOMINANT_COLOUR, metadata.get(FaceDetectionParser.DOM_COL));
                // TODO Extract multiple characteristic colours as well
            }
            Instrument.timeRel("WARCPayloadAnalyzers.analyze#total", "ImageAnalyzer.analyze#facesanddominant",
                    deepStart);
        } else { //images are enabled, we still want to extract image/height (fast)
            //This method takes 0.2ms for a large image. I can be done even faster if needed(but more complicated)).
            //see https://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java

            ImageInputStream input = null;
            ImageReader reader = null;
            try {
                input = ImageIO.createImageInputStream(tikainput);
                reader = ImageIO.getImageReaders(input).next();
                reader.setInput(input);
                // Get dimensions of first image in the stream, without decoding pixel values
                int width = reader.getWidth(0);
                int height = reader.getHeight(0);

                // Store basic image data:
                solr.addField(SolrFields.IMAGE_HEIGHT, "" + height);
                solr.addField(SolrFields.IMAGE_WIDTH, "" + width);
                solr.addField(SolrFields.IMAGE_SIZE, "" + (height * width));
            } catch (Exception e) {
                //it is known that (most) .ico and (all) .svg are not supported by java. Do not log, since it will spam.
                log.warn("Unable to extract image data for url:" + header.getUrl(), e);
            } finally {
                if (reader != null) {
                    reader.dispose();
                }
            }

        }
    }
}

From source file:org.dcm4che2.tool.dcm2jpg.Dcm2Jpg.java

public void convert(File src, File dest) throws IOException {
    Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
    ImageReader reader = iter.next();
    DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam();
    param.setWindowCenter(center);//from   ww w .  j  a v  a 2s .  com
    param.setWindowWidth(width);
    param.setVoiLutFunction(vlutFct);
    param.setPresentationState(prState);
    param.setPValue2Gray(pval2gray);
    param.setAutoWindowing(autoWindowing);
    ImageInputStream iis = ImageIO.createImageInputStream(src);
    BufferedImage bi;
    try {
        reader.setInput(iis, false);
        bi = reader.read(frame - 1, param);
        if (bi == null) {
            System.out.println("\nError: " + src + " - couldn't read!");
            return;
        }
        if (imageWriterClassname == null) {
            encodeByJPEGEncoder(bi, dest);
        } else {
            encodeByImageIO(bi, dest);
        }
    } finally {
        CloseUtils.safeClose(iis);
    }
    System.out.print('.');
}

From source file:sernet.verinice.service.commands.LoadAttachmentFile.java

private BufferedImage readImageFromByteArrayFallback() throws IOException {
    ImageInputStream in = ImageIO
            .createImageInputStream(new ByteArrayInputStream(getAttachmentFile().getFileData()));
    Iterator<ImageReader> iter = ImageIO.getImageReaders(in);
    BufferedImage image = null;//from www.j  av a  2 s.c o m

    while (iter.hasNext()) {
        ImageReader reader = null;
        try {
            reader = (ImageReader) iter.next();
            ImageReadParam param = reader.getDefaultReadParam();
            reader.setInput(in, true, true);
            Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);
            while (imageTypes.hasNext()) {
                ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
                int bufferedImageType = imageTypeSpecifier.getBufferedImageType();
                if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) {
                    param.setDestinationType(imageTypeSpecifier);
                    break;
                }
            }
            image = reader.read(0, param);
            if (null != image) {
                break;
            }
        } catch (Exception e) {
            getLog().error("Error while reading image the advanced way. DbId: " + getAttachmentFile().getDbId(),
                    e);
        } finally {
            if (null != reader) {
                reader.dispose();
            }
        }

    }
    return image;
}

From source file:com.sketchy.utils.image.SketchyImage.java

public static SketchyImage load(File file) throws Exception {
    SketchyImage sketchyImage = null;//from w w w  . jav a  2 s  .c  om

    if (!file.exists() || !file.canRead()) {
        throw new Exception("Can not find or read File: " + file.getPath() + "!");
    }

    if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) {
        throw new Exception("Can not load SketchyImage! Must be a .png file!");
    }

    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("png");
    ImageReader imageReader = null;
    if (imageReaders.hasNext()) { // Just get first one
        imageReader = imageReaders.next();
    }
    if (imageReader == null) {
        // this should never happen!! if so.. we got problems
        throw new Exception("Can not find ImageReader for .png Files!");
    }

    ImageInputStream is = null;
    try {
        is = ImageIO.createImageInputStream(file);
        imageReader.setInput(is, true);
        IIOMetadata metaData = imageReader.getImageMetadata(0); // always get first image
        IIOMetadataNode metaDataNode = (IIOMetadataNode) metaData
                .getAsTree(metaData.getNativeMetadataFormatName());
        if (metaDataNode == null) {
            throw new Exception("Error retreiving MetaData properties from .png File!");
        }

        NodeList childNodes = metaDataNode.getElementsByTagName("pHYs");
        // only look in the first node
        if (childNodes.getLength() == 0) {
            throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnit' MetaData!");
        }
        IIOMetadataNode physNode = (IIOMetadataNode) childNodes.item(0);
        String pixelsPerUnitXAxisAttribute = physNode.getAttribute("pixelsPerUnitXAxis");
        String pixelsPerUnitYAxisAttribute = physNode.getAttribute("pixelsPerUnitYAxis");
        // String unitSpecifierAttribute = physNode.getAttribute("unitSpecifier"); Just assuming meter
        if (StringUtils.isBlank(pixelsPerUnitXAxisAttribute)) {
            throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitXAxis' MetaData!");
        }
        if (StringUtils.isBlank(pixelsPerUnitYAxisAttribute)) {
            throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitYAxis' MetaData!");
        }

        int pixelsPerUnitXAxis;
        try {
            pixelsPerUnitXAxis = Integer.parseInt(pixelsPerUnitXAxisAttribute);
            if (pixelsPerUnitXAxis <= 0)
                throw new Exception("Value must be > 0");
        } catch (Exception e) {
            throw new Exception("Invalid 'pixelsPerUnitXAxis' MetaData Attribute! " + e.getMessage());
        }

        int pixelsPerUnitYAxis;
        try {
            pixelsPerUnitYAxis = Integer.parseInt(pixelsPerUnitYAxisAttribute);
            if (pixelsPerUnitYAxis <= 0)
                throw new Exception("Value must be > 0");
        } catch (Exception e) {
            throw new Exception("Invalid 'pixelsPerUnitYAxis' MetaData Attribute! " + e.getMessage());
        }

        // We successfully processed the MetaData.. now read/set the image 
        BufferedImage bufferedImage = imageReader.read(0); // always get first image

        double xPixelsPerMM = pixelsPerUnitXAxis / 1000.0;
        double yPixelsPerMM = pixelsPerUnitYAxis / 1000.0;

        sketchyImage = new SketchyImage(bufferedImage, xPixelsPerMM, yPixelsPerMM);
    } catch (Exception e) {
        throw new Exception("Error Loading SketchyImage File: " + file.getPath() + "! " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(is);
    }

    return sketchyImage;
}